babylon.no-module.max.js 5.2 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161
  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. /**
  8458. * Defines an GC Friendly array where the backfield array do not shrink to prevent over allocations.
  8459. */
  8460. var SmartArray = /** @class */ (function () {
  8461. /**
  8462. * Instantiates a Smart Array.
  8463. * @param capacity defines the default capacity of the array.
  8464. */
  8465. function SmartArray(capacity) {
  8466. /**
  8467. * The active length of the array.
  8468. */
  8469. this.length = 0;
  8470. this.data = new Array(capacity);
  8471. this._id = SmartArray._GlobalId++;
  8472. }
  8473. /**
  8474. * Pushes a value at the end of the active data.
  8475. * @param value defines the object to push in the array.
  8476. */
  8477. SmartArray.prototype.push = function (value) {
  8478. this.data[this.length++] = value;
  8479. if (this.length > this.data.length) {
  8480. this.data.length *= 2;
  8481. }
  8482. };
  8483. /**
  8484. * Iterates over the active data and apply the lambda to them.
  8485. * @param func defines the action to apply on each value.
  8486. */
  8487. SmartArray.prototype.forEach = function (func) {
  8488. for (var index = 0; index < this.length; index++) {
  8489. func(this.data[index]);
  8490. }
  8491. };
  8492. /**
  8493. * Sorts the full sets of data.
  8494. * @param compareFn defines the comparison function to apply.
  8495. */
  8496. SmartArray.prototype.sort = function (compareFn) {
  8497. this.data.sort(compareFn);
  8498. };
  8499. /**
  8500. * Resets the active data to an empty array.
  8501. */
  8502. SmartArray.prototype.reset = function () {
  8503. this.length = 0;
  8504. };
  8505. /**
  8506. * Releases all the data from the array as well as the array.
  8507. */
  8508. SmartArray.prototype.dispose = function () {
  8509. this.reset();
  8510. if (this.data) {
  8511. this.data.length = 0;
  8512. this.data = [];
  8513. }
  8514. };
  8515. /**
  8516. * Concats the active data with a given array.
  8517. * @param array defines the data to concatenate with.
  8518. */
  8519. SmartArray.prototype.concat = function (array) {
  8520. if (array.length === 0) {
  8521. return;
  8522. }
  8523. if (this.length + array.length > this.data.length) {
  8524. this.data.length = (this.length + array.length) * 2;
  8525. }
  8526. for (var index = 0; index < array.length; index++) {
  8527. this.data[this.length++] = (array.data || array)[index];
  8528. }
  8529. };
  8530. /**
  8531. * Returns the position of a value in the active data.
  8532. * @param value defines the value to find the index for
  8533. * @returns the index if found in the active data otherwise -1
  8534. */
  8535. SmartArray.prototype.indexOf = function (value) {
  8536. var position = this.data.indexOf(value);
  8537. if (position >= this.length) {
  8538. return -1;
  8539. }
  8540. return position;
  8541. };
  8542. /**
  8543. * Returns whether an element is part of the active data.
  8544. * @param value defines the value to look for
  8545. * @returns true if found in the active data otherwise false
  8546. */
  8547. SmartArray.prototype.contains = function (value) {
  8548. return this.indexOf(value) !== -1;
  8549. };
  8550. // Statics
  8551. SmartArray._GlobalId = 0;
  8552. return SmartArray;
  8553. }());
  8554. BABYLON.SmartArray = SmartArray;
  8555. /**
  8556. * Defines an GC Friendly array where the backfield array do not shrink to prevent over allocations.
  8557. * The data in this array can only be present once
  8558. */
  8559. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8560. __extends(SmartArrayNoDuplicate, _super);
  8561. function SmartArrayNoDuplicate() {
  8562. var _this = _super !== null && _super.apply(this, arguments) || this;
  8563. _this._duplicateId = 0;
  8564. return _this;
  8565. }
  8566. /**
  8567. * Pushes a value at the end of the active data.
  8568. * THIS DOES NOT PREVENT DUPPLICATE DATA
  8569. * @param value defines the object to push in the array.
  8570. */
  8571. SmartArrayNoDuplicate.prototype.push = function (value) {
  8572. _super.prototype.push.call(this, value);
  8573. if (!value.__smartArrayFlags) {
  8574. value.__smartArrayFlags = {};
  8575. }
  8576. value.__smartArrayFlags[this._id] = this._duplicateId;
  8577. };
  8578. /**
  8579. * Pushes a value at the end of the active data.
  8580. * If the data is already present, it won t be added again
  8581. * @param value defines the object to push in the array.
  8582. * @returns true if added false if it was already present
  8583. */
  8584. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8585. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8586. return false;
  8587. }
  8588. this.push(value);
  8589. return true;
  8590. };
  8591. /**
  8592. * Resets the active data to an empty array.
  8593. */
  8594. SmartArrayNoDuplicate.prototype.reset = function () {
  8595. _super.prototype.reset.call(this);
  8596. this._duplicateId++;
  8597. };
  8598. /**
  8599. * Concats the active data with a given array.
  8600. * This ensures no dupplicate will be present in the result.
  8601. * @param array defines the data to concatenate with.
  8602. */
  8603. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8604. if (array.length === 0) {
  8605. return;
  8606. }
  8607. if (this.length + array.length > this.data.length) {
  8608. this.data.length = (this.length + array.length) * 2;
  8609. }
  8610. for (var index = 0; index < array.length; index++) {
  8611. var item = (array.data || array)[index];
  8612. this.pushNoDuplicate(item);
  8613. }
  8614. };
  8615. return SmartArrayNoDuplicate;
  8616. }(SmartArray));
  8617. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8618. })(BABYLON || (BABYLON = {}));
  8619. //# sourceMappingURL=babylon.smartArray.js.map
  8620. var BABYLON;
  8621. (function (BABYLON) {
  8622. /** Class used to store color gradient */
  8623. var ColorGradient = /** @class */ (function () {
  8624. function ColorGradient() {
  8625. }
  8626. /**
  8627. * Will get a color picked randomly between color1 and color2.
  8628. * If color2 is undefined then color1 will be used
  8629. * @param result defines the target Color4 to store the result in
  8630. */
  8631. ColorGradient.prototype.getColorToRef = function (result) {
  8632. if (!this.color2) {
  8633. result.copyFrom(this.color1);
  8634. return;
  8635. }
  8636. BABYLON.Color4.LerpToRef(this.color1, this.color2, Math.random(), result);
  8637. };
  8638. return ColorGradient;
  8639. }());
  8640. BABYLON.ColorGradient = ColorGradient;
  8641. /** Class used to store factor gradient */
  8642. var FactorGradient = /** @class */ (function () {
  8643. function FactorGradient() {
  8644. }
  8645. /**
  8646. * Will get a number picked randomly between factor1 and factor2.
  8647. * If factor2 is undefined then factor1 will be used
  8648. * @returns the picked number
  8649. */
  8650. FactorGradient.prototype.getFactor = function () {
  8651. if (this.factor2 === undefined) {
  8652. return this.factor1;
  8653. }
  8654. return BABYLON.Scalar.Lerp(this.factor1, this.factor2, Math.random());
  8655. };
  8656. return FactorGradient;
  8657. }());
  8658. BABYLON.FactorGradient = FactorGradient;
  8659. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8660. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8661. var LoadFileError = /** @class */ (function (_super) {
  8662. __extends(LoadFileError, _super);
  8663. function LoadFileError(message, request) {
  8664. var _this = _super.call(this, message) || this;
  8665. _this.request = request;
  8666. _this.name = "LoadFileError";
  8667. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8668. return _this;
  8669. }
  8670. // Polyfill for Object.setPrototypeOf if necessary.
  8671. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8672. return LoadFileError;
  8673. }(Error));
  8674. BABYLON.LoadFileError = LoadFileError;
  8675. var RetryStrategy = /** @class */ (function () {
  8676. function RetryStrategy() {
  8677. }
  8678. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8679. if (maxRetries === void 0) { maxRetries = 3; }
  8680. if (baseInterval === void 0) { baseInterval = 500; }
  8681. return function (url, request, retryIndex) {
  8682. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8683. return -1;
  8684. }
  8685. return Math.pow(2, retryIndex) * baseInterval;
  8686. };
  8687. };
  8688. return RetryStrategy;
  8689. }());
  8690. BABYLON.RetryStrategy = RetryStrategy;
  8691. // Screenshots
  8692. var screenshotCanvas;
  8693. var cloneValue = function (source, destinationObject) {
  8694. if (!source)
  8695. return null;
  8696. if (source instanceof BABYLON.Mesh) {
  8697. return null;
  8698. }
  8699. if (source instanceof BABYLON.SubMesh) {
  8700. return source.clone(destinationObject);
  8701. }
  8702. else if (source.clone) {
  8703. return source.clone();
  8704. }
  8705. return null;
  8706. };
  8707. var Tools = /** @class */ (function () {
  8708. function Tools() {
  8709. }
  8710. /**
  8711. * Read the content of a byte array at a specified coordinates (taking in account wrapping)
  8712. * @param u defines the coordinate on X axis
  8713. * @param v defines the coordinate on Y axis
  8714. * @param width defines the width of the source data
  8715. * @param height defines the height of the source data
  8716. * @param pixels defines the source byte array
  8717. * @param color defines the output color
  8718. */
  8719. Tools.FetchToRef = function (u, v, width, height, pixels, color) {
  8720. var wrappedU = ((Math.abs(u) * width) % width) | 0;
  8721. var wrappedV = ((Math.abs(v) * height) % height) | 0;
  8722. var position = (wrappedU + wrappedV * width) * 4;
  8723. color.r = pixels[position] / 255;
  8724. color.g = pixels[position + 1] / 255;
  8725. color.b = pixels[position + 2] / 255;
  8726. color.a = pixels[position + 3] / 255;
  8727. };
  8728. /**
  8729. * Interpolates between a and b via alpha
  8730. * @param a The lower value (returned when alpha = 0)
  8731. * @param b The upper value (returned when alpha = 1)
  8732. * @param alpha The interpolation-factor
  8733. * @return The mixed value
  8734. */
  8735. Tools.Mix = function (a, b, alpha) {
  8736. return a * (1 - alpha) + b * alpha;
  8737. };
  8738. Tools.Instantiate = function (className) {
  8739. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8740. return Tools.RegisteredExternalClasses[className];
  8741. }
  8742. var arr = className.split(".");
  8743. var fn = (window || this);
  8744. for (var i = 0, len = arr.length; i < len; i++) {
  8745. fn = fn[arr[i]];
  8746. }
  8747. if (typeof fn !== "function") {
  8748. return null;
  8749. }
  8750. return fn;
  8751. };
  8752. /**
  8753. * Provides a slice function that will work even on IE
  8754. * @param data defines the array to slice
  8755. * @param start defines the start of the data (optional)
  8756. * @param end defines the end of the data (optional)
  8757. * @returns the new sliced array
  8758. */
  8759. Tools.Slice = function (data, start, end) {
  8760. if (data.slice) {
  8761. return data.slice(start, end);
  8762. }
  8763. return Array.prototype.slice.call(data, start, end);
  8764. };
  8765. Tools.SetImmediate = function (action) {
  8766. if (Tools.IsWindowObjectExist() && window.setImmediate) {
  8767. window.setImmediate(action);
  8768. }
  8769. else {
  8770. setTimeout(action, 1);
  8771. }
  8772. };
  8773. Tools.IsExponentOfTwo = function (value) {
  8774. var count = 1;
  8775. do {
  8776. count *= 2;
  8777. } while (count < value);
  8778. return count === value;
  8779. };
  8780. /**
  8781. * Returns the nearest 32-bit single precision float representation of a Number
  8782. * @param value A Number. If the parameter is of a different type, it will get converted
  8783. * to a number or to NaN if it cannot be converted
  8784. * @returns number
  8785. */
  8786. Tools.FloatRound = function (value) {
  8787. if (Math.fround) {
  8788. return Math.fround(value);
  8789. }
  8790. return (Tools._tmpFloatArray[0] = value);
  8791. };
  8792. /**
  8793. * Find the next highest power of two.
  8794. * @param x Number to start search from.
  8795. * @return Next highest power of two.
  8796. */
  8797. Tools.CeilingPOT = function (x) {
  8798. x--;
  8799. x |= x >> 1;
  8800. x |= x >> 2;
  8801. x |= x >> 4;
  8802. x |= x >> 8;
  8803. x |= x >> 16;
  8804. x++;
  8805. return x;
  8806. };
  8807. /**
  8808. * Find the next lowest power of two.
  8809. * @param x Number to start search from.
  8810. * @return Next lowest power of two.
  8811. */
  8812. Tools.FloorPOT = function (x) {
  8813. x = x | (x >> 1);
  8814. x = x | (x >> 2);
  8815. x = x | (x >> 4);
  8816. x = x | (x >> 8);
  8817. x = x | (x >> 16);
  8818. return x - (x >> 1);
  8819. };
  8820. /**
  8821. * Find the nearest power of two.
  8822. * @param x Number to start search from.
  8823. * @return Next nearest power of two.
  8824. */
  8825. Tools.NearestPOT = function (x) {
  8826. var c = Tools.CeilingPOT(x);
  8827. var f = Tools.FloorPOT(x);
  8828. return (c - x) > (x - f) ? f : c;
  8829. };
  8830. Tools.GetExponentOfTwo = function (value, max, mode) {
  8831. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8832. var pot;
  8833. switch (mode) {
  8834. case BABYLON.Engine.SCALEMODE_FLOOR:
  8835. pot = Tools.FloorPOT(value);
  8836. break;
  8837. case BABYLON.Engine.SCALEMODE_NEAREST:
  8838. pot = Tools.NearestPOT(value);
  8839. break;
  8840. case BABYLON.Engine.SCALEMODE_CEILING:
  8841. default:
  8842. pot = Tools.CeilingPOT(value);
  8843. break;
  8844. }
  8845. return Math.min(pot, max);
  8846. };
  8847. Tools.GetFilename = function (path) {
  8848. var index = path.lastIndexOf("/");
  8849. if (index < 0)
  8850. return path;
  8851. return path.substring(index + 1);
  8852. };
  8853. /**
  8854. * Extracts the "folder" part of a path (everything before the filename).
  8855. * @param uri The URI to extract the info from
  8856. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8857. * @returns The "folder" part of the path
  8858. */
  8859. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8860. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8861. var index = uri.lastIndexOf("/");
  8862. if (index < 0) {
  8863. if (returnUnchangedIfNoSlash) {
  8864. return uri;
  8865. }
  8866. return "";
  8867. }
  8868. return uri.substring(0, index + 1);
  8869. };
  8870. Tools.GetDOMTextContent = function (element) {
  8871. var result = "";
  8872. var child = element.firstChild;
  8873. while (child) {
  8874. if (child.nodeType === 3) {
  8875. result += child.textContent;
  8876. }
  8877. child = child.nextSibling;
  8878. }
  8879. return result;
  8880. };
  8881. Tools.ToDegrees = function (angle) {
  8882. return angle * 180 / Math.PI;
  8883. };
  8884. Tools.ToRadians = function (angle) {
  8885. return angle * Math.PI / 180;
  8886. };
  8887. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8888. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8889. var output = "";
  8890. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8891. var i = 0;
  8892. var bytes = new Uint8Array(buffer);
  8893. while (i < bytes.length) {
  8894. chr1 = bytes[i++];
  8895. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8896. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8897. enc1 = chr1 >> 2;
  8898. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8899. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8900. enc4 = chr3 & 63;
  8901. if (isNaN(chr2)) {
  8902. enc3 = enc4 = 64;
  8903. }
  8904. else if (isNaN(chr3)) {
  8905. enc4 = 64;
  8906. }
  8907. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8908. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8909. }
  8910. return "data:image/png;base64," + output;
  8911. };
  8912. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8913. if (bias === void 0) { bias = null; }
  8914. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8915. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8916. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8917. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8918. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8919. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8920. }
  8921. if (bias) {
  8922. minimum.x -= minimum.x * bias.x + bias.y;
  8923. minimum.y -= minimum.y * bias.x + bias.y;
  8924. minimum.z -= minimum.z * bias.x + bias.y;
  8925. maximum.x += maximum.x * bias.x + bias.y;
  8926. maximum.y += maximum.y * bias.x + bias.y;
  8927. maximum.z += maximum.z * bias.x + bias.y;
  8928. }
  8929. return {
  8930. minimum: minimum,
  8931. maximum: maximum
  8932. };
  8933. };
  8934. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8935. if (bias === void 0) { bias = null; }
  8936. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8937. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8938. if (!stride) {
  8939. stride = 3;
  8940. }
  8941. for (var index = start; index < start + count; index++) {
  8942. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8943. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8944. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8945. }
  8946. if (bias) {
  8947. minimum.x -= minimum.x * bias.x + bias.y;
  8948. minimum.y -= minimum.y * bias.x + bias.y;
  8949. minimum.z -= minimum.z * bias.x + bias.y;
  8950. maximum.x += maximum.x * bias.x + bias.y;
  8951. maximum.y += maximum.y * bias.x + bias.y;
  8952. maximum.z += maximum.z * bias.x + bias.y;
  8953. }
  8954. return {
  8955. minimum: minimum,
  8956. maximum: maximum
  8957. };
  8958. };
  8959. Tools.Vector2ArrayFeeder = function (array) {
  8960. return function (index) {
  8961. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8962. var length = isFloatArray ? array.length / 2 : array.length;
  8963. if (index >= length) {
  8964. return null;
  8965. }
  8966. if (isFloatArray) {
  8967. var fa = array;
  8968. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8969. }
  8970. var a = array;
  8971. return a[index];
  8972. };
  8973. };
  8974. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8975. if (bias === void 0) { bias = null; }
  8976. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8977. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8978. var i = 0;
  8979. var cur = feeder(i++);
  8980. while (cur) {
  8981. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8982. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8983. cur = feeder(i++);
  8984. }
  8985. if (bias) {
  8986. minimum.x -= minimum.x * bias.x + bias.y;
  8987. minimum.y -= minimum.y * bias.x + bias.y;
  8988. maximum.x += maximum.x * bias.x + bias.y;
  8989. maximum.y += maximum.y * bias.x + bias.y;
  8990. }
  8991. return {
  8992. minimum: minimum,
  8993. maximum: maximum
  8994. };
  8995. };
  8996. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8997. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8998. return null;
  8999. return Array.isArray(obj) ? obj : [obj];
  9000. };
  9001. // Misc.
  9002. Tools.GetPointerPrefix = function () {
  9003. var eventPrefix = "pointer";
  9004. // Check if pointer events are supported
  9005. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  9006. eventPrefix = "mouse";
  9007. }
  9008. return eventPrefix;
  9009. };
  9010. /**
  9011. * @param func - the function to be called
  9012. * @param requester - the object that will request the next frame. Falls back to window.
  9013. */
  9014. Tools.QueueNewFrame = function (func, requester) {
  9015. if (!Tools.IsWindowObjectExist()) {
  9016. return setTimeout(func, 16);
  9017. }
  9018. if (!requester) {
  9019. requester = window;
  9020. }
  9021. if (requester.requestAnimationFrame) {
  9022. return requester.requestAnimationFrame(func);
  9023. }
  9024. else if (requester.msRequestAnimationFrame) {
  9025. return requester.msRequestAnimationFrame(func);
  9026. }
  9027. else if (requester.webkitRequestAnimationFrame) {
  9028. return requester.webkitRequestAnimationFrame(func);
  9029. }
  9030. else if (requester.mozRequestAnimationFrame) {
  9031. return requester.mozRequestAnimationFrame(func);
  9032. }
  9033. else if (requester.oRequestAnimationFrame) {
  9034. return requester.oRequestAnimationFrame(func);
  9035. }
  9036. else {
  9037. return window.setTimeout(func, 16);
  9038. }
  9039. };
  9040. Tools.RequestFullscreen = function (element) {
  9041. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  9042. if (!requestFunction)
  9043. return;
  9044. requestFunction.call(element);
  9045. };
  9046. Tools.ExitFullscreen = function () {
  9047. if (document.exitFullscreen) {
  9048. document.exitFullscreen();
  9049. }
  9050. else if (document.mozCancelFullScreen) {
  9051. document.mozCancelFullScreen();
  9052. }
  9053. else if (document.webkitCancelFullScreen) {
  9054. document.webkitCancelFullScreen();
  9055. }
  9056. else if (document.msCancelFullScreen) {
  9057. document.msCancelFullScreen();
  9058. }
  9059. };
  9060. Tools.SetCorsBehavior = function (url, element) {
  9061. if (url && url.indexOf("data:") === 0) {
  9062. return;
  9063. }
  9064. if (Tools.CorsBehavior) {
  9065. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  9066. element.crossOrigin = Tools.CorsBehavior;
  9067. }
  9068. else {
  9069. var result = Tools.CorsBehavior(url);
  9070. if (result) {
  9071. element.crossOrigin = result;
  9072. }
  9073. }
  9074. }
  9075. };
  9076. // External files
  9077. Tools.CleanUrl = function (url) {
  9078. url = url.replace(/#/mg, "%23");
  9079. return url;
  9080. };
  9081. /**
  9082. * Loads an image as an HTMLImageElement.
  9083. * @param input url string, ArrayBuffer, or Blob to load
  9084. * @param onLoad callback called when the image successfully loads
  9085. * @param onError callback called when the image fails to load
  9086. * @param database database for caching
  9087. * @returns the HTMLImageElement of the loaded image
  9088. */
  9089. Tools.LoadImage = function (input, onLoad, onError, database) {
  9090. var url;
  9091. var usingObjectURL = false;
  9092. if (input instanceof ArrayBuffer) {
  9093. url = URL.createObjectURL(new Blob([input]));
  9094. usingObjectURL = true;
  9095. }
  9096. else if (input instanceof Blob) {
  9097. url = URL.createObjectURL(input);
  9098. usingObjectURL = true;
  9099. }
  9100. else {
  9101. url = Tools.CleanUrl(input);
  9102. url = Tools.PreprocessUrl(input);
  9103. }
  9104. var img = new Image();
  9105. Tools.SetCorsBehavior(url, img);
  9106. var loadHandler = function () {
  9107. if (usingObjectURL && img.src) {
  9108. URL.revokeObjectURL(img.src);
  9109. }
  9110. img.removeEventListener("load", loadHandler);
  9111. img.removeEventListener("error", errorHandler);
  9112. onLoad(img);
  9113. };
  9114. var errorHandler = function (err) {
  9115. if (usingObjectURL && img.src) {
  9116. URL.revokeObjectURL(img.src);
  9117. }
  9118. img.removeEventListener("load", loadHandler);
  9119. img.removeEventListener("error", errorHandler);
  9120. Tools.Error("Error while trying to load image: " + input);
  9121. if (onError) {
  9122. onError("Error while trying to load image: " + input, err);
  9123. }
  9124. };
  9125. img.addEventListener("load", loadHandler);
  9126. img.addEventListener("error", errorHandler);
  9127. var noIndexedDB = function () {
  9128. img.src = url;
  9129. };
  9130. var loadFromIndexedDB = function () {
  9131. if (database) {
  9132. database.loadImageFromDB(url, img);
  9133. }
  9134. };
  9135. //ANY database to do!
  9136. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  9137. database.openAsync(loadFromIndexedDB, noIndexedDB);
  9138. }
  9139. else {
  9140. if (url.indexOf("file:") !== -1) {
  9141. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  9142. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  9143. try {
  9144. var blobURL;
  9145. try {
  9146. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9147. }
  9148. catch (ex) {
  9149. // Chrome doesn't support oneTimeOnly parameter
  9150. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9151. }
  9152. img.src = blobURL;
  9153. usingObjectURL = true;
  9154. }
  9155. catch (e) {
  9156. img.src = "";
  9157. }
  9158. return img;
  9159. }
  9160. }
  9161. noIndexedDB();
  9162. }
  9163. return img;
  9164. };
  9165. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  9166. url = Tools.CleanUrl(url);
  9167. url = Tools.PreprocessUrl(url);
  9168. // If file and file input are set
  9169. if (url.indexOf("file:") !== -1) {
  9170. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  9171. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  9172. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  9173. }
  9174. }
  9175. var loadUrl = Tools.BaseUrl + url;
  9176. var aborted = false;
  9177. var fileRequest = {
  9178. onCompleteObservable: new BABYLON.Observable(),
  9179. abort: function () { return aborted = true; },
  9180. };
  9181. var requestFile = function () {
  9182. var request = new XMLHttpRequest();
  9183. var retryHandle = null;
  9184. fileRequest.abort = function () {
  9185. aborted = true;
  9186. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  9187. request.abort();
  9188. }
  9189. if (retryHandle !== null) {
  9190. clearTimeout(retryHandle);
  9191. retryHandle = null;
  9192. }
  9193. };
  9194. var retryLoop = function (retryIndex) {
  9195. request.open('GET', loadUrl, true);
  9196. if (useArrayBuffer) {
  9197. request.responseType = "arraybuffer";
  9198. }
  9199. if (onProgress) {
  9200. request.addEventListener("progress", onProgress);
  9201. }
  9202. var onLoadEnd = function () {
  9203. request.removeEventListener("loadend", onLoadEnd);
  9204. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9205. fileRequest.onCompleteObservable.clear();
  9206. };
  9207. request.addEventListener("loadend", onLoadEnd);
  9208. var onReadyStateChange = function () {
  9209. if (aborted) {
  9210. return;
  9211. }
  9212. // In case of undefined state in some browsers.
  9213. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  9214. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  9215. request.removeEventListener("readystatechange", onReadyStateChange);
  9216. if ((request.status >= 200 && request.status < 300) || (request.status === 0 && (!Tools.IsWindowObjectExist() || Tools.IsFileURL()))) {
  9217. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  9218. return;
  9219. }
  9220. var retryStrategy = Tools.DefaultRetryStrategy;
  9221. if (retryStrategy) {
  9222. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  9223. if (waitTime !== -1) {
  9224. // Prevent the request from completing for retry.
  9225. request.removeEventListener("loadend", onLoadEnd);
  9226. request = new XMLHttpRequest();
  9227. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  9228. return;
  9229. }
  9230. }
  9231. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  9232. if (onError) {
  9233. onError(request, e);
  9234. }
  9235. else {
  9236. throw e;
  9237. }
  9238. }
  9239. };
  9240. request.addEventListener("readystatechange", onReadyStateChange);
  9241. request.send();
  9242. };
  9243. retryLoop(0);
  9244. };
  9245. // Caching all files
  9246. if (database && database.enableSceneOffline) {
  9247. var noIndexedDB_1 = function (request) {
  9248. if (request && request.status > 400) {
  9249. if (onError) {
  9250. onError(request);
  9251. }
  9252. }
  9253. else {
  9254. if (!aborted) {
  9255. requestFile();
  9256. }
  9257. }
  9258. };
  9259. var loadFromIndexedDB = function () {
  9260. // TODO: database needs to support aborting and should return a IFileRequest
  9261. if (aborted) {
  9262. return;
  9263. }
  9264. if (database) {
  9265. database.loadFileFromDB(url, function (data) {
  9266. if (!aborted) {
  9267. onSuccess(data);
  9268. }
  9269. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9270. }, onProgress ? function (event) {
  9271. if (!aborted) {
  9272. onProgress(event);
  9273. }
  9274. } : undefined, noIndexedDB_1, useArrayBuffer);
  9275. }
  9276. };
  9277. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9278. }
  9279. else {
  9280. requestFile();
  9281. }
  9282. return fileRequest;
  9283. };
  9284. /**
  9285. * Load a script (identified by an url). When the url returns, the
  9286. * content of this file is added into a new script element, attached to the DOM (body element)
  9287. */
  9288. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9289. if (!Tools.IsWindowObjectExist()) {
  9290. return;
  9291. }
  9292. var head = document.getElementsByTagName('head')[0];
  9293. var script = document.createElement('script');
  9294. script.type = 'text/javascript';
  9295. script.src = scriptUrl;
  9296. script.onload = function () {
  9297. if (onSuccess) {
  9298. onSuccess();
  9299. }
  9300. };
  9301. script.onerror = function (e) {
  9302. if (onError) {
  9303. onError("Unable to load script '" + scriptUrl + "'", e);
  9304. }
  9305. };
  9306. head.appendChild(script);
  9307. };
  9308. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9309. var reader = new FileReader();
  9310. var request = {
  9311. onCompleteObservable: new BABYLON.Observable(),
  9312. abort: function () { return reader.abort(); },
  9313. };
  9314. reader.onloadend = function (e) {
  9315. request.onCompleteObservable.notifyObservers(request);
  9316. };
  9317. reader.onload = function (e) {
  9318. //target doesn't have result from ts 1.3
  9319. callback(e.target['result']);
  9320. };
  9321. reader.onprogress = progressCallback;
  9322. reader.readAsDataURL(fileToLoad);
  9323. return request;
  9324. };
  9325. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9326. var reader = new FileReader();
  9327. var request = {
  9328. onCompleteObservable: new BABYLON.Observable(),
  9329. abort: function () { return reader.abort(); },
  9330. };
  9331. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9332. reader.onerror = function (e) {
  9333. Tools.Log("Error while reading file: " + fileToLoad.name);
  9334. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9335. };
  9336. reader.onload = function (e) {
  9337. //target doesn't have result from ts 1.3
  9338. callback(e.target['result']);
  9339. };
  9340. if (progressCallBack) {
  9341. reader.onprogress = progressCallBack;
  9342. }
  9343. if (!useArrayBuffer) {
  9344. // Asynchronous read
  9345. reader.readAsText(fileToLoad);
  9346. }
  9347. else {
  9348. reader.readAsArrayBuffer(fileToLoad);
  9349. }
  9350. return request;
  9351. };
  9352. //returns a downloadable url to a file content.
  9353. Tools.FileAsURL = function (content) {
  9354. var fileBlob = new Blob([content]);
  9355. var url = window.URL || window.webkitURL;
  9356. var link = url.createObjectURL(fileBlob);
  9357. return link;
  9358. };
  9359. // Misc.
  9360. Tools.Format = function (value, decimals) {
  9361. if (decimals === void 0) { decimals = 2; }
  9362. return value.toFixed(decimals);
  9363. };
  9364. Tools.CheckExtends = function (v, min, max) {
  9365. if (v.x < min.x)
  9366. min.x = v.x;
  9367. if (v.y < min.y)
  9368. min.y = v.y;
  9369. if (v.z < min.z)
  9370. min.z = v.z;
  9371. if (v.x > max.x)
  9372. max.x = v.x;
  9373. if (v.y > max.y)
  9374. max.y = v.y;
  9375. if (v.z > max.z)
  9376. max.z = v.z;
  9377. };
  9378. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9379. for (var prop in source) {
  9380. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9381. continue;
  9382. }
  9383. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9384. continue;
  9385. }
  9386. var sourceValue = source[prop];
  9387. var typeOfSourceValue = typeof sourceValue;
  9388. if (typeOfSourceValue === "function") {
  9389. continue;
  9390. }
  9391. try {
  9392. if (typeOfSourceValue === "object") {
  9393. if (sourceValue instanceof Array) {
  9394. destination[prop] = [];
  9395. if (sourceValue.length > 0) {
  9396. if (typeof sourceValue[0] == "object") {
  9397. for (var index = 0; index < sourceValue.length; index++) {
  9398. var clonedValue = cloneValue(sourceValue[index], destination);
  9399. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9400. destination[prop].push(clonedValue);
  9401. }
  9402. }
  9403. }
  9404. else {
  9405. destination[prop] = sourceValue.slice(0);
  9406. }
  9407. }
  9408. }
  9409. else {
  9410. destination[prop] = cloneValue(sourceValue, destination);
  9411. }
  9412. }
  9413. else {
  9414. destination[prop] = sourceValue;
  9415. }
  9416. }
  9417. catch (e) {
  9418. // Just ignore error (it could be because of a read-only property)
  9419. }
  9420. }
  9421. };
  9422. Tools.IsEmpty = function (obj) {
  9423. for (var i in obj) {
  9424. if (obj.hasOwnProperty(i)) {
  9425. return false;
  9426. }
  9427. }
  9428. return true;
  9429. };
  9430. Tools.RegisterTopRootEvents = function (events) {
  9431. for (var index = 0; index < events.length; index++) {
  9432. var event = events[index];
  9433. window.addEventListener(event.name, event.handler, false);
  9434. try {
  9435. if (window.parent) {
  9436. window.parent.addEventListener(event.name, event.handler, false);
  9437. }
  9438. }
  9439. catch (e) {
  9440. // Silently fails...
  9441. }
  9442. }
  9443. };
  9444. Tools.UnregisterTopRootEvents = function (events) {
  9445. for (var index = 0; index < events.length; index++) {
  9446. var event = events[index];
  9447. window.removeEventListener(event.name, event.handler);
  9448. try {
  9449. if (window.parent) {
  9450. window.parent.removeEventListener(event.name, event.handler);
  9451. }
  9452. }
  9453. catch (e) {
  9454. // Silently fails...
  9455. }
  9456. }
  9457. };
  9458. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9459. if (mimeType === void 0) { mimeType = "image/png"; }
  9460. // Read the contents of the framebuffer
  9461. var numberOfChannelsByLine = width * 4;
  9462. var halfHeight = height / 2;
  9463. //Reading datas from WebGL
  9464. var data = engine.readPixels(0, 0, width, height);
  9465. //To flip image on Y axis.
  9466. for (var i = 0; i < halfHeight; i++) {
  9467. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9468. var currentCell = j + i * numberOfChannelsByLine;
  9469. var targetLine = height - i - 1;
  9470. var targetCell = j + targetLine * numberOfChannelsByLine;
  9471. var temp = data[currentCell];
  9472. data[currentCell] = data[targetCell];
  9473. data[targetCell] = temp;
  9474. }
  9475. }
  9476. // Create a 2D canvas to store the result
  9477. if (!screenshotCanvas) {
  9478. screenshotCanvas = document.createElement('canvas');
  9479. }
  9480. screenshotCanvas.width = width;
  9481. screenshotCanvas.height = height;
  9482. var context = screenshotCanvas.getContext('2d');
  9483. if (context) {
  9484. // Copy the pixels to a 2D canvas
  9485. var imageData = context.createImageData(width, height);
  9486. var castData = (imageData.data);
  9487. castData.set(data);
  9488. context.putImageData(imageData, 0, 0);
  9489. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9490. }
  9491. };
  9492. /**
  9493. * Converts the canvas data to blob.
  9494. * This acts as a polyfill for browsers not supporting the to blob function.
  9495. * @param canvas Defines the canvas to extract the data from
  9496. * @param successCallback Defines the callback triggered once the data are available
  9497. * @param mimeType Defines the mime type of the result
  9498. */
  9499. Tools.ToBlob = function (canvas, successCallback, mimeType) {
  9500. if (mimeType === void 0) { mimeType = "image/png"; }
  9501. // We need HTMLCanvasElement.toBlob for HD screenshots
  9502. if (!canvas.toBlob) {
  9503. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9504. canvas.toBlob = function (callback, type, quality) {
  9505. var _this = this;
  9506. setTimeout(function () {
  9507. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9508. for (var i = 0; i < len; i++) {
  9509. arr[i] = binStr.charCodeAt(i);
  9510. }
  9511. callback(new Blob([arr]));
  9512. });
  9513. };
  9514. }
  9515. canvas.toBlob(function (blob) {
  9516. successCallback(blob);
  9517. }, mimeType);
  9518. };
  9519. /**
  9520. * Encodes the canvas data to base 64 or automatically download the result if filename is defined
  9521. * @param successCallback Defines the callback triggered once the data are available
  9522. * @param mimeType Defines the mime type of the result
  9523. * @param fileName The filename to download. If present, the result will automatically be downloaded
  9524. */
  9525. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9526. if (mimeType === void 0) { mimeType = "image/png"; }
  9527. if (successCallback) {
  9528. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9529. successCallback(base64Image);
  9530. }
  9531. else {
  9532. this.ToBlob(screenshotCanvas, function (blob) {
  9533. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9534. if (("download" in document.createElement("a"))) {
  9535. if (!fileName) {
  9536. var date = new Date();
  9537. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9538. fileName = "screenshot_" + stringDate + ".png";
  9539. }
  9540. Tools.Download(blob, fileName);
  9541. }
  9542. else {
  9543. var url = URL.createObjectURL(blob);
  9544. var newWindow = window.open("");
  9545. if (!newWindow)
  9546. return;
  9547. var img = newWindow.document.createElement("img");
  9548. img.onload = function () {
  9549. // no longer need to read the blob so it's revoked
  9550. URL.revokeObjectURL(url);
  9551. };
  9552. img.src = url;
  9553. newWindow.document.body.appendChild(img);
  9554. }
  9555. }, mimeType);
  9556. }
  9557. };
  9558. /**
  9559. * Downloads a blob in the browser
  9560. * @param blob defines the blob to download
  9561. * @param fileName defines the name of the downloaded file
  9562. */
  9563. Tools.Download = function (blob, fileName) {
  9564. if (navigator && navigator.msSaveBlob) {
  9565. navigator.msSaveBlob(blob, fileName);
  9566. return;
  9567. }
  9568. var url = window.URL.createObjectURL(blob);
  9569. var a = document.createElement("a");
  9570. document.body.appendChild(a);
  9571. a.style.display = "none";
  9572. a.href = url;
  9573. a.download = fileName;
  9574. a.addEventListener("click", function () {
  9575. if (a.parentElement) {
  9576. a.parentElement.removeChild(a);
  9577. }
  9578. });
  9579. a.click();
  9580. window.URL.revokeObjectURL(url);
  9581. };
  9582. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9583. if (mimeType === void 0) { mimeType = "image/png"; }
  9584. var width;
  9585. var height;
  9586. // If a precision value is specified
  9587. if (size.precision) {
  9588. width = Math.round(engine.getRenderWidth() * size.precision);
  9589. height = Math.round(width / engine.getAspectRatio(camera));
  9590. }
  9591. else if (size.width && size.height) {
  9592. width = size.width;
  9593. height = size.height;
  9594. }
  9595. //If passing only width, computing height to keep display canvas ratio.
  9596. else if (size.width && !size.height) {
  9597. width = size.width;
  9598. height = Math.round(width / engine.getAspectRatio(camera));
  9599. }
  9600. //If passing only height, computing width to keep display canvas ratio.
  9601. else if (size.height && !size.width) {
  9602. height = size.height;
  9603. width = Math.round(height * engine.getAspectRatio(camera));
  9604. }
  9605. //Assuming here that "size" parameter is a number
  9606. else if (!isNaN(size)) {
  9607. height = size;
  9608. width = size;
  9609. }
  9610. else {
  9611. Tools.Error("Invalid 'size' parameter !");
  9612. return;
  9613. }
  9614. if (!screenshotCanvas) {
  9615. screenshotCanvas = document.createElement('canvas');
  9616. }
  9617. screenshotCanvas.width = width;
  9618. screenshotCanvas.height = height;
  9619. var renderContext = screenshotCanvas.getContext("2d");
  9620. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9621. var newWidth = width;
  9622. var newHeight = newWidth / ratio;
  9623. if (newHeight > height) {
  9624. newHeight = height;
  9625. newWidth = newHeight * ratio;
  9626. }
  9627. var offsetX = Math.max(0, width - newWidth) / 2;
  9628. var offsetY = Math.max(0, height - newHeight) / 2;
  9629. var renderingCanvas = engine.getRenderingCanvas();
  9630. if (renderContext && renderingCanvas) {
  9631. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9632. }
  9633. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9634. };
  9635. /**
  9636. * Generates an image screenshot from the specified camera.
  9637. *
  9638. * @param engine The engine to use for rendering
  9639. * @param camera The camera to use for rendering
  9640. * @param size This parameter can be set to a single number or to an object with the
  9641. * following (optional) properties: precision, width, height. If a single number is passed,
  9642. * it will be used for both width and height. If an object is passed, the screenshot size
  9643. * will be derived from the parameters. The precision property is a multiplier allowing
  9644. * rendering at a higher or lower resolution.
  9645. * @param successCallback The callback receives a single parameter which contains the
  9646. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9647. * src parameter of an <img> to display it.
  9648. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9649. * Check your browser for supported MIME types.
  9650. * @param samples Texture samples (default: 1)
  9651. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9652. * @param fileName A name for for the downloaded file.
  9653. * @constructor
  9654. */
  9655. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9656. if (mimeType === void 0) { mimeType = "image/png"; }
  9657. if (samples === void 0) { samples = 1; }
  9658. if (antialiasing === void 0) { antialiasing = false; }
  9659. var width;
  9660. var height;
  9661. //If a precision value is specified
  9662. if (size.precision) {
  9663. width = Math.round(engine.getRenderWidth() * size.precision);
  9664. height = Math.round(width / engine.getAspectRatio(camera));
  9665. size = { width: width, height: height };
  9666. }
  9667. else if (size.width && size.height) {
  9668. width = size.width;
  9669. height = size.height;
  9670. }
  9671. //If passing only width, computing height to keep display canvas ratio.
  9672. else if (size.width && !size.height) {
  9673. width = size.width;
  9674. height = Math.round(width / engine.getAspectRatio(camera));
  9675. size = { width: width, height: height };
  9676. }
  9677. //If passing only height, computing width to keep display canvas ratio.
  9678. else if (size.height && !size.width) {
  9679. height = size.height;
  9680. width = Math.round(height * engine.getAspectRatio(camera));
  9681. size = { width: width, height: height };
  9682. }
  9683. //Assuming here that "size" parameter is a number
  9684. else if (!isNaN(size)) {
  9685. height = size;
  9686. width = size;
  9687. }
  9688. else {
  9689. Tools.Error("Invalid 'size' parameter !");
  9690. return;
  9691. }
  9692. var scene = camera.getScene();
  9693. var previousCamera = null;
  9694. if (scene.activeCamera !== camera) {
  9695. previousCamera = scene.activeCamera;
  9696. scene.activeCamera = camera;
  9697. }
  9698. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9699. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9700. texture.renderList = null;
  9701. texture.samples = samples;
  9702. if (antialiasing) {
  9703. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9704. }
  9705. texture.onAfterRenderObservable.add(function () {
  9706. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9707. });
  9708. scene.incrementRenderId();
  9709. scene.resetCachedMaterial();
  9710. texture.render(true);
  9711. texture.dispose();
  9712. if (previousCamera) {
  9713. scene.activeCamera = previousCamera;
  9714. }
  9715. camera.getProjectionMatrix(true); // Force cache refresh;
  9716. };
  9717. // XHR response validator for local file scenario
  9718. Tools.ValidateXHRData = function (xhr, dataType) {
  9719. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9720. if (dataType === void 0) { dataType = 7; }
  9721. try {
  9722. if (dataType & 1) {
  9723. if (xhr.responseText && xhr.responseText.length > 0) {
  9724. return true;
  9725. }
  9726. else if (dataType === 1) {
  9727. return false;
  9728. }
  9729. }
  9730. if (dataType & 2) {
  9731. // Check header width and height since there is no "TGA" magic number
  9732. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9733. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9734. return true;
  9735. }
  9736. else if (dataType === 2) {
  9737. return false;
  9738. }
  9739. }
  9740. if (dataType & 4) {
  9741. // Check for the "DDS" magic number
  9742. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9743. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9744. return true;
  9745. }
  9746. else {
  9747. return false;
  9748. }
  9749. }
  9750. }
  9751. catch (e) {
  9752. // Global protection
  9753. }
  9754. return false;
  9755. };
  9756. /**
  9757. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9758. * Be aware Math.random() could cause collisions, but:
  9759. * "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"
  9760. */
  9761. Tools.RandomId = function () {
  9762. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9763. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9764. return v.toString(16);
  9765. });
  9766. };
  9767. /**
  9768. * Test if the given uri is a base64 string.
  9769. * @param uri The uri to test
  9770. * @return True if the uri is a base64 string or false otherwise.
  9771. */
  9772. Tools.IsBase64 = function (uri) {
  9773. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9774. };
  9775. /**
  9776. * Decode the given base64 uri.
  9777. * @param uri The uri to decode
  9778. * @return The decoded base64 data.
  9779. */
  9780. Tools.DecodeBase64 = function (uri) {
  9781. var decodedString = atob(uri.split(",")[1]);
  9782. var bufferLength = decodedString.length;
  9783. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9784. for (var i = 0; i < bufferLength; i++) {
  9785. bufferView[i] = decodedString.charCodeAt(i);
  9786. }
  9787. return bufferView.buffer;
  9788. };
  9789. Object.defineProperty(Tools, "NoneLogLevel", {
  9790. get: function () {
  9791. return Tools._NoneLogLevel;
  9792. },
  9793. enumerable: true,
  9794. configurable: true
  9795. });
  9796. Object.defineProperty(Tools, "MessageLogLevel", {
  9797. get: function () {
  9798. return Tools._MessageLogLevel;
  9799. },
  9800. enumerable: true,
  9801. configurable: true
  9802. });
  9803. Object.defineProperty(Tools, "WarningLogLevel", {
  9804. get: function () {
  9805. return Tools._WarningLogLevel;
  9806. },
  9807. enumerable: true,
  9808. configurable: true
  9809. });
  9810. Object.defineProperty(Tools, "ErrorLogLevel", {
  9811. get: function () {
  9812. return Tools._ErrorLogLevel;
  9813. },
  9814. enumerable: true,
  9815. configurable: true
  9816. });
  9817. Object.defineProperty(Tools, "AllLogLevel", {
  9818. get: function () {
  9819. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9820. },
  9821. enumerable: true,
  9822. configurable: true
  9823. });
  9824. Tools._AddLogEntry = function (entry) {
  9825. Tools._LogCache = entry + Tools._LogCache;
  9826. if (Tools.OnNewCacheEntry) {
  9827. Tools.OnNewCacheEntry(entry);
  9828. }
  9829. };
  9830. Tools._FormatMessage = function (message) {
  9831. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9832. var date = new Date();
  9833. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9834. };
  9835. Tools._LogDisabled = function (message) {
  9836. // nothing to do
  9837. };
  9838. Tools._LogEnabled = function (message) {
  9839. var formattedMessage = Tools._FormatMessage(message);
  9840. console.log("BJS - " + formattedMessage);
  9841. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9842. Tools._AddLogEntry(entry);
  9843. };
  9844. Tools._WarnDisabled = function (message) {
  9845. // nothing to do
  9846. };
  9847. Tools._WarnEnabled = function (message) {
  9848. var formattedMessage = Tools._FormatMessage(message);
  9849. console.warn("BJS - " + formattedMessage);
  9850. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9851. Tools._AddLogEntry(entry);
  9852. };
  9853. Tools._ErrorDisabled = function (message) {
  9854. // nothing to do
  9855. };
  9856. Tools._ErrorEnabled = function (message) {
  9857. Tools.errorsCount++;
  9858. var formattedMessage = Tools._FormatMessage(message);
  9859. console.error("BJS - " + formattedMessage);
  9860. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9861. Tools._AddLogEntry(entry);
  9862. };
  9863. Object.defineProperty(Tools, "LogCache", {
  9864. get: function () {
  9865. return Tools._LogCache;
  9866. },
  9867. enumerable: true,
  9868. configurable: true
  9869. });
  9870. Tools.ClearLogCache = function () {
  9871. Tools._LogCache = "";
  9872. Tools.errorsCount = 0;
  9873. };
  9874. Object.defineProperty(Tools, "LogLevels", {
  9875. set: function (level) {
  9876. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9877. Tools.Log = Tools._LogEnabled;
  9878. }
  9879. else {
  9880. Tools.Log = Tools._LogDisabled;
  9881. }
  9882. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9883. Tools.Warn = Tools._WarnEnabled;
  9884. }
  9885. else {
  9886. Tools.Warn = Tools._WarnDisabled;
  9887. }
  9888. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9889. Tools.Error = Tools._ErrorEnabled;
  9890. }
  9891. else {
  9892. Tools.Error = Tools._ErrorDisabled;
  9893. }
  9894. },
  9895. enumerable: true,
  9896. configurable: true
  9897. });
  9898. /**
  9899. * Check if the loaded document was accessed via `file:`-Protocol.
  9900. * @returns boolean
  9901. */
  9902. Tools.IsFileURL = function () {
  9903. return location.protocol === "file:";
  9904. };
  9905. Tools.IsWindowObjectExist = function () {
  9906. return (typeof window) !== "undefined";
  9907. };
  9908. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9909. get: function () {
  9910. return Tools._PerformanceNoneLogLevel;
  9911. },
  9912. enumerable: true,
  9913. configurable: true
  9914. });
  9915. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9916. get: function () {
  9917. return Tools._PerformanceUserMarkLogLevel;
  9918. },
  9919. enumerable: true,
  9920. configurable: true
  9921. });
  9922. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9923. get: function () {
  9924. return Tools._PerformanceConsoleLogLevel;
  9925. },
  9926. enumerable: true,
  9927. configurable: true
  9928. });
  9929. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9930. set: function (level) {
  9931. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9932. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9933. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9934. return;
  9935. }
  9936. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9937. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9938. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9939. return;
  9940. }
  9941. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9942. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9943. },
  9944. enumerable: true,
  9945. configurable: true
  9946. });
  9947. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9948. };
  9949. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9950. };
  9951. Tools._StartUserMark = function (counterName, condition) {
  9952. if (condition === void 0) { condition = true; }
  9953. if (!Tools._performance) {
  9954. if (!Tools.IsWindowObjectExist()) {
  9955. return;
  9956. }
  9957. Tools._performance = window.performance;
  9958. }
  9959. if (!condition || !Tools._performance.mark) {
  9960. return;
  9961. }
  9962. Tools._performance.mark(counterName + "-Begin");
  9963. };
  9964. Tools._EndUserMark = function (counterName, condition) {
  9965. if (condition === void 0) { condition = true; }
  9966. if (!condition || !Tools._performance.mark) {
  9967. return;
  9968. }
  9969. Tools._performance.mark(counterName + "-End");
  9970. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9971. };
  9972. Tools._StartPerformanceConsole = function (counterName, condition) {
  9973. if (condition === void 0) { condition = true; }
  9974. if (!condition) {
  9975. return;
  9976. }
  9977. Tools._StartUserMark(counterName, condition);
  9978. if (console.time) {
  9979. console.time(counterName);
  9980. }
  9981. };
  9982. Tools._EndPerformanceConsole = function (counterName, condition) {
  9983. if (condition === void 0) { condition = true; }
  9984. if (!condition) {
  9985. return;
  9986. }
  9987. Tools._EndUserMark(counterName, condition);
  9988. if (console.time) {
  9989. console.timeEnd(counterName);
  9990. }
  9991. };
  9992. Object.defineProperty(Tools, "Now", {
  9993. get: function () {
  9994. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9995. return window.performance.now();
  9996. }
  9997. return Date.now();
  9998. },
  9999. enumerable: true,
  10000. configurable: true
  10001. });
  10002. /**
  10003. * This method will return the name of the class used to create the instance of the given object.
  10004. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  10005. * @param object the object to get the class name from
  10006. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  10007. */
  10008. Tools.GetClassName = function (object, isType) {
  10009. if (isType === void 0) { isType = false; }
  10010. var name = null;
  10011. if (!isType && object.getClassName) {
  10012. name = object.getClassName();
  10013. }
  10014. else {
  10015. if (object instanceof Object) {
  10016. var classObj = isType ? object : Object.getPrototypeOf(object);
  10017. name = classObj.constructor["__bjsclassName__"];
  10018. }
  10019. if (!name) {
  10020. name = typeof object;
  10021. }
  10022. }
  10023. return name;
  10024. };
  10025. Tools.First = function (array, predicate) {
  10026. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  10027. var el = array_1[_i];
  10028. if (predicate(el)) {
  10029. return el;
  10030. }
  10031. }
  10032. return null;
  10033. };
  10034. /**
  10035. * This method will return the name of the full name of the class, including its owning module (if any).
  10036. * 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).
  10037. * @param object the object to get the class name from
  10038. * @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.
  10039. */
  10040. Tools.getFullClassName = function (object, isType) {
  10041. if (isType === void 0) { isType = false; }
  10042. var className = null;
  10043. var moduleName = null;
  10044. if (!isType && object.getClassName) {
  10045. className = object.getClassName();
  10046. }
  10047. else {
  10048. if (object instanceof Object) {
  10049. var classObj = isType ? object : Object.getPrototypeOf(object);
  10050. className = classObj.constructor["__bjsclassName__"];
  10051. moduleName = classObj.constructor["__bjsmoduleName__"];
  10052. }
  10053. if (!className) {
  10054. className = typeof object;
  10055. }
  10056. }
  10057. if (!className) {
  10058. return null;
  10059. }
  10060. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  10061. };
  10062. /**
  10063. * 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.
  10064. * @param array
  10065. */
  10066. Tools.arrayOrStringFeeder = function (array) {
  10067. return function (index) {
  10068. if (index >= array.length) {
  10069. return null;
  10070. }
  10071. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  10072. if (val && val.getHashCode) {
  10073. val = val.getHashCode();
  10074. }
  10075. if (typeof val === "string") {
  10076. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  10077. }
  10078. return val;
  10079. };
  10080. };
  10081. /**
  10082. * Compute the hashCode of a stream of number
  10083. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  10084. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  10085. * @return the hash code computed
  10086. */
  10087. Tools.hashCodeFromStream = function (feeder) {
  10088. // Based from here: http://stackoverflow.com/a/7616484/802124
  10089. var hash = 0;
  10090. var index = 0;
  10091. var chr = feeder(index++);
  10092. while (chr != null) {
  10093. hash = ((hash << 5) - hash) + chr;
  10094. hash |= 0; // Convert to 32bit integer
  10095. chr = feeder(index++);
  10096. }
  10097. return hash;
  10098. };
  10099. /**
  10100. * Returns a promise that resolves after the given amount of time.
  10101. * @param delay Number of milliseconds to delay
  10102. * @returns Promise that resolves after the given amount of time
  10103. */
  10104. Tools.DelayAsync = function (delay) {
  10105. return new Promise(function (resolve) {
  10106. setTimeout(function () {
  10107. resolve();
  10108. }, delay);
  10109. });
  10110. };
  10111. /**
  10112. * Gets the current gradient from an array of IValueGradient
  10113. * @param ratio defines the current ratio to get
  10114. * @param gradients defines the array of IValueGradient
  10115. * @param updateFunc defines the callback function used to get the final value from the selected gradients
  10116. */
  10117. Tools.GetCurrentGradient = function (ratio, gradients, updateFunc) {
  10118. for (var gradientIndex = 0; gradientIndex < gradients.length - 1; gradientIndex++) {
  10119. var currentGradient = gradients[gradientIndex];
  10120. var nextGradient = gradients[gradientIndex + 1];
  10121. if (ratio >= currentGradient.gradient && ratio <= nextGradient.gradient) {
  10122. var scale = (ratio - currentGradient.gradient) / (nextGradient.gradient - currentGradient.gradient);
  10123. updateFunc(currentGradient, nextGradient, scale);
  10124. return;
  10125. }
  10126. }
  10127. // Use last index if over
  10128. var lastIndex = gradients.length - 1;
  10129. updateFunc(gradients[lastIndex], gradients[lastIndex], 1.0);
  10130. };
  10131. Tools.BaseUrl = "";
  10132. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  10133. /**
  10134. * Default behaviour for cors in the application.
  10135. * It can be a string if the expected behavior is identical in the entire app.
  10136. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  10137. */
  10138. Tools.CorsBehavior = "anonymous";
  10139. Tools.UseFallbackTexture = true;
  10140. /**
  10141. * Use this object to register external classes like custom textures or material
  10142. * to allow the laoders to instantiate them
  10143. */
  10144. Tools.RegisteredExternalClasses = {};
  10145. // Used in case of a texture loading problem
  10146. 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";
  10147. Tools._tmpFloatArray = new Float32Array(1);
  10148. Tools.PreprocessUrl = function (url) {
  10149. return url;
  10150. };
  10151. // Logs
  10152. Tools._NoneLogLevel = 0;
  10153. Tools._MessageLogLevel = 1;
  10154. Tools._WarningLogLevel = 2;
  10155. Tools._ErrorLogLevel = 4;
  10156. Tools._LogCache = "";
  10157. Tools.errorsCount = 0;
  10158. Tools.Log = Tools._LogEnabled;
  10159. Tools.Warn = Tools._WarnEnabled;
  10160. Tools.Error = Tools._ErrorEnabled;
  10161. // Performances
  10162. Tools._PerformanceNoneLogLevel = 0;
  10163. Tools._PerformanceUserMarkLogLevel = 1;
  10164. Tools._PerformanceConsoleLogLevel = 2;
  10165. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  10166. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  10167. return Tools;
  10168. }());
  10169. BABYLON.Tools = Tools;
  10170. /**
  10171. * This class is used to track a performance counter which is number based.
  10172. * The user has access to many properties which give statistics of different nature
  10173. *
  10174. * The implementer can track two kinds of Performance Counter: time and count
  10175. * 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.
  10176. * 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.
  10177. */
  10178. var PerfCounter = /** @class */ (function () {
  10179. function PerfCounter() {
  10180. this._startMonitoringTime = 0;
  10181. this._min = 0;
  10182. this._max = 0;
  10183. this._average = 0;
  10184. this._lastSecAverage = 0;
  10185. this._current = 0;
  10186. this._totalValueCount = 0;
  10187. this._totalAccumulated = 0;
  10188. this._lastSecAccumulated = 0;
  10189. this._lastSecTime = 0;
  10190. this._lastSecValueCount = 0;
  10191. }
  10192. Object.defineProperty(PerfCounter.prototype, "min", {
  10193. /**
  10194. * Returns the smallest value ever
  10195. */
  10196. get: function () {
  10197. return this._min;
  10198. },
  10199. enumerable: true,
  10200. configurable: true
  10201. });
  10202. Object.defineProperty(PerfCounter.prototype, "max", {
  10203. /**
  10204. * Returns the biggest value ever
  10205. */
  10206. get: function () {
  10207. return this._max;
  10208. },
  10209. enumerable: true,
  10210. configurable: true
  10211. });
  10212. Object.defineProperty(PerfCounter.prototype, "average", {
  10213. /**
  10214. * Returns the average value since the performance counter is running
  10215. */
  10216. get: function () {
  10217. return this._average;
  10218. },
  10219. enumerable: true,
  10220. configurable: true
  10221. });
  10222. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  10223. /**
  10224. * Returns the average value of the last second the counter was monitored
  10225. */
  10226. get: function () {
  10227. return this._lastSecAverage;
  10228. },
  10229. enumerable: true,
  10230. configurable: true
  10231. });
  10232. Object.defineProperty(PerfCounter.prototype, "current", {
  10233. /**
  10234. * Returns the current value
  10235. */
  10236. get: function () {
  10237. return this._current;
  10238. },
  10239. enumerable: true,
  10240. configurable: true
  10241. });
  10242. Object.defineProperty(PerfCounter.prototype, "total", {
  10243. get: function () {
  10244. return this._totalAccumulated;
  10245. },
  10246. enumerable: true,
  10247. configurable: true
  10248. });
  10249. Object.defineProperty(PerfCounter.prototype, "count", {
  10250. get: function () {
  10251. return this._totalValueCount;
  10252. },
  10253. enumerable: true,
  10254. configurable: true
  10255. });
  10256. /**
  10257. * Call this method to start monitoring a new frame.
  10258. * 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.
  10259. */
  10260. PerfCounter.prototype.fetchNewFrame = function () {
  10261. this._totalValueCount++;
  10262. this._current = 0;
  10263. this._lastSecValueCount++;
  10264. };
  10265. /**
  10266. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  10267. * @param newCount the count value to add to the monitored count
  10268. * @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.
  10269. */
  10270. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  10271. if (!PerfCounter.Enabled) {
  10272. return;
  10273. }
  10274. this._current += newCount;
  10275. if (fetchResult) {
  10276. this._fetchResult();
  10277. }
  10278. };
  10279. /**
  10280. * Start monitoring this performance counter
  10281. */
  10282. PerfCounter.prototype.beginMonitoring = function () {
  10283. if (!PerfCounter.Enabled) {
  10284. return;
  10285. }
  10286. this._startMonitoringTime = Tools.Now;
  10287. };
  10288. /**
  10289. * Compute the time lapsed since the previous beginMonitoring() call.
  10290. * @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
  10291. */
  10292. PerfCounter.prototype.endMonitoring = function (newFrame) {
  10293. if (newFrame === void 0) { newFrame = true; }
  10294. if (!PerfCounter.Enabled) {
  10295. return;
  10296. }
  10297. if (newFrame) {
  10298. this.fetchNewFrame();
  10299. }
  10300. var currentTime = Tools.Now;
  10301. this._current = currentTime - this._startMonitoringTime;
  10302. if (newFrame) {
  10303. this._fetchResult();
  10304. }
  10305. };
  10306. PerfCounter.prototype._fetchResult = function () {
  10307. this._totalAccumulated += this._current;
  10308. this._lastSecAccumulated += this._current;
  10309. // Min/Max update
  10310. this._min = Math.min(this._min, this._current);
  10311. this._max = Math.max(this._max, this._current);
  10312. this._average = this._totalAccumulated / this._totalValueCount;
  10313. // Reset last sec?
  10314. var now = Tools.Now;
  10315. if ((now - this._lastSecTime) > 1000) {
  10316. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  10317. this._lastSecTime = now;
  10318. this._lastSecAccumulated = 0;
  10319. this._lastSecValueCount = 0;
  10320. }
  10321. };
  10322. PerfCounter.Enabled = true;
  10323. return PerfCounter;
  10324. }());
  10325. BABYLON.PerfCounter = PerfCounter;
  10326. /**
  10327. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  10328. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  10329. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  10330. * @param name The name of the class, case should be preserved
  10331. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  10332. */
  10333. function className(name, module) {
  10334. return function (target) {
  10335. target["__bjsclassName__"] = name;
  10336. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10337. };
  10338. }
  10339. BABYLON.className = className;
  10340. /**
  10341. * An implementation of a loop for asynchronous functions.
  10342. */
  10343. var AsyncLoop = /** @class */ (function () {
  10344. /**
  10345. * Constroctor.
  10346. * @param iterations the number of iterations.
  10347. * @param _fn the function to run each iteration
  10348. * @param _successCallback the callback that will be called upon succesful execution
  10349. * @param offset starting offset.
  10350. */
  10351. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  10352. if (offset === void 0) { offset = 0; }
  10353. this.iterations = iterations;
  10354. this._fn = _fn;
  10355. this._successCallback = _successCallback;
  10356. this.index = offset - 1;
  10357. this._done = false;
  10358. }
  10359. /**
  10360. * Execute the next iteration. Must be called after the last iteration was finished.
  10361. */
  10362. AsyncLoop.prototype.executeNext = function () {
  10363. if (!this._done) {
  10364. if (this.index + 1 < this.iterations) {
  10365. ++this.index;
  10366. this._fn(this);
  10367. }
  10368. else {
  10369. this.breakLoop();
  10370. }
  10371. }
  10372. };
  10373. /**
  10374. * Break the loop and run the success callback.
  10375. */
  10376. AsyncLoop.prototype.breakLoop = function () {
  10377. this._done = true;
  10378. this._successCallback();
  10379. };
  10380. /**
  10381. * Helper function
  10382. */
  10383. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  10384. if (offset === void 0) { offset = 0; }
  10385. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  10386. loop.executeNext();
  10387. return loop;
  10388. };
  10389. /**
  10390. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10391. * @param iterations total number of iterations
  10392. * @param syncedIterations number of synchronous iterations in each async iteration.
  10393. * @param fn the function to call each iteration.
  10394. * @param callback a success call back that will be called when iterating stops.
  10395. * @param breakFunction a break condition (optional)
  10396. * @param timeout timeout settings for the setTimeout function. default - 0.
  10397. * @constructor
  10398. */
  10399. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10400. if (timeout === void 0) { timeout = 0; }
  10401. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10402. if (breakFunction && breakFunction())
  10403. loop.breakLoop();
  10404. else {
  10405. setTimeout(function () {
  10406. for (var i = 0; i < syncedIterations; ++i) {
  10407. var iteration = (loop.index * syncedIterations) + i;
  10408. if (iteration >= iterations)
  10409. break;
  10410. fn(iteration);
  10411. if (breakFunction && breakFunction()) {
  10412. loop.breakLoop();
  10413. break;
  10414. }
  10415. }
  10416. loop.executeNext();
  10417. }, timeout);
  10418. }
  10419. }, callback);
  10420. };
  10421. return AsyncLoop;
  10422. }());
  10423. BABYLON.AsyncLoop = AsyncLoop;
  10424. })(BABYLON || (BABYLON = {}));
  10425. //# sourceMappingURL=babylon.tools.js.map
  10426. var BABYLON;
  10427. (function (BABYLON) {
  10428. var PromiseStates;
  10429. (function (PromiseStates) {
  10430. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10431. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10432. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10433. })(PromiseStates || (PromiseStates = {}));
  10434. var FulFillmentAgregator = /** @class */ (function () {
  10435. function FulFillmentAgregator() {
  10436. this.count = 0;
  10437. this.target = 0;
  10438. this.results = [];
  10439. }
  10440. return FulFillmentAgregator;
  10441. }());
  10442. var InternalPromise = /** @class */ (function () {
  10443. function InternalPromise(resolver) {
  10444. var _this = this;
  10445. this._state = PromiseStates.Pending;
  10446. this._children = new Array();
  10447. this._rejectWasConsumed = false;
  10448. if (!resolver) {
  10449. return;
  10450. }
  10451. try {
  10452. resolver(function (value) {
  10453. _this._resolve(value);
  10454. }, function (reason) {
  10455. _this._reject(reason);
  10456. });
  10457. }
  10458. catch (e) {
  10459. this._reject(e);
  10460. }
  10461. }
  10462. Object.defineProperty(InternalPromise.prototype, "_result", {
  10463. get: function () {
  10464. return this._resultValue;
  10465. },
  10466. set: function (value) {
  10467. this._resultValue = value;
  10468. if (this._parent && this._parent._result === undefined) {
  10469. this._parent._result = value;
  10470. }
  10471. },
  10472. enumerable: true,
  10473. configurable: true
  10474. });
  10475. InternalPromise.prototype.catch = function (onRejected) {
  10476. return this.then(undefined, onRejected);
  10477. };
  10478. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10479. var _this = this;
  10480. var newPromise = new InternalPromise();
  10481. newPromise._onFulfilled = onFulfilled;
  10482. newPromise._onRejected = onRejected;
  10483. // Composition
  10484. this._children.push(newPromise);
  10485. newPromise._parent = this;
  10486. if (this._state !== PromiseStates.Pending) {
  10487. BABYLON.Tools.SetImmediate(function () {
  10488. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10489. var returnedValue = newPromise._resolve(_this._result);
  10490. if (returnedValue !== undefined && returnedValue !== null) {
  10491. if (returnedValue._state !== undefined) {
  10492. var returnedPromise = returnedValue;
  10493. newPromise._children.push(returnedPromise);
  10494. returnedPromise._parent = newPromise;
  10495. newPromise = returnedPromise;
  10496. }
  10497. else {
  10498. newPromise._result = returnedValue;
  10499. }
  10500. }
  10501. }
  10502. else {
  10503. newPromise._reject(_this._reason);
  10504. }
  10505. });
  10506. }
  10507. return newPromise;
  10508. };
  10509. InternalPromise.prototype._moveChildren = function (children) {
  10510. var _this = this;
  10511. var _a;
  10512. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10513. this._children.forEach(function (child) {
  10514. child._parent = _this;
  10515. });
  10516. if (this._state === PromiseStates.Fulfilled) {
  10517. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10518. var child = _b[_i];
  10519. child._resolve(this._result);
  10520. }
  10521. }
  10522. else if (this._state === PromiseStates.Rejected) {
  10523. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10524. var child = _d[_c];
  10525. child._reject(this._reason);
  10526. }
  10527. }
  10528. };
  10529. InternalPromise.prototype._resolve = function (value) {
  10530. try {
  10531. this._state = PromiseStates.Fulfilled;
  10532. var returnedValue = null;
  10533. if (this._onFulfilled) {
  10534. returnedValue = this._onFulfilled(value);
  10535. }
  10536. if (returnedValue !== undefined && returnedValue !== null) {
  10537. if (returnedValue._state !== undefined) {
  10538. // Transmit children
  10539. var returnedPromise = returnedValue;
  10540. returnedPromise._parent = this;
  10541. returnedPromise._moveChildren(this._children);
  10542. value = returnedPromise._result;
  10543. }
  10544. else {
  10545. value = returnedValue;
  10546. }
  10547. }
  10548. this._result = value;
  10549. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10550. var child = _a[_i];
  10551. child._resolve(value);
  10552. }
  10553. this._children.length = 0;
  10554. delete this._onFulfilled;
  10555. delete this._onRejected;
  10556. }
  10557. catch (e) {
  10558. this._reject(e, true);
  10559. }
  10560. };
  10561. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10562. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10563. this._state = PromiseStates.Rejected;
  10564. this._reason = reason;
  10565. if (this._onRejected && !onLocalThrow) {
  10566. try {
  10567. this._onRejected(reason);
  10568. this._rejectWasConsumed = true;
  10569. }
  10570. catch (e) {
  10571. reason = e;
  10572. }
  10573. }
  10574. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10575. var child = _a[_i];
  10576. if (this._rejectWasConsumed) {
  10577. child._resolve(null);
  10578. }
  10579. else {
  10580. child._reject(reason);
  10581. }
  10582. }
  10583. this._children.length = 0;
  10584. delete this._onFulfilled;
  10585. delete this._onRejected;
  10586. };
  10587. InternalPromise.resolve = function (value) {
  10588. var newPromise = new InternalPromise();
  10589. newPromise._resolve(value);
  10590. return newPromise;
  10591. };
  10592. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10593. promise.then(function (value) {
  10594. agregator.results[index] = value;
  10595. agregator.count++;
  10596. if (agregator.count === agregator.target) {
  10597. agregator.rootPromise._resolve(agregator.results);
  10598. }
  10599. return null;
  10600. }, function (reason) {
  10601. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10602. agregator.rootPromise._reject(reason);
  10603. }
  10604. });
  10605. };
  10606. InternalPromise.all = function (promises) {
  10607. var newPromise = new InternalPromise();
  10608. var agregator = new FulFillmentAgregator();
  10609. agregator.target = promises.length;
  10610. agregator.rootPromise = newPromise;
  10611. if (promises.length) {
  10612. for (var index = 0; index < promises.length; index++) {
  10613. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10614. }
  10615. }
  10616. else {
  10617. newPromise._resolve([]);
  10618. }
  10619. return newPromise;
  10620. };
  10621. InternalPromise.race = function (promises) {
  10622. var newPromise = new InternalPromise();
  10623. if (promises.length) {
  10624. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10625. var promise = promises_1[_i];
  10626. promise.then(function (value) {
  10627. if (newPromise) {
  10628. newPromise._resolve(value);
  10629. newPromise = null;
  10630. }
  10631. return null;
  10632. }, function (reason) {
  10633. if (newPromise) {
  10634. newPromise._reject(reason);
  10635. newPromise = null;
  10636. }
  10637. });
  10638. }
  10639. }
  10640. return newPromise;
  10641. };
  10642. return InternalPromise;
  10643. }());
  10644. /**
  10645. * Helper class that provides a small promise polyfill
  10646. */
  10647. var PromisePolyfill = /** @class */ (function () {
  10648. function PromisePolyfill() {
  10649. }
  10650. /**
  10651. * Static function used to check if the polyfill is required
  10652. * If this is the case then the function will inject the polyfill to window.Promise
  10653. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10654. */
  10655. PromisePolyfill.Apply = function (force) {
  10656. if (force === void 0) { force = false; }
  10657. if (force || typeof Promise === 'undefined') {
  10658. var root = window;
  10659. root.Promise = InternalPromise;
  10660. }
  10661. };
  10662. return PromisePolyfill;
  10663. }());
  10664. BABYLON.PromisePolyfill = PromisePolyfill;
  10665. })(BABYLON || (BABYLON = {}));
  10666. //# sourceMappingURL=babylon.promise.js.map
  10667. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10668. var BABYLON;
  10669. (function (BABYLON) {
  10670. /**
  10671. * Helper class to push actions to a pool of workers.
  10672. */
  10673. var WorkerPool = /** @class */ (function () {
  10674. /**
  10675. * Constructor
  10676. * @param workers Array of workers to use for actions
  10677. */
  10678. function WorkerPool(workers) {
  10679. this._pendingActions = new Array();
  10680. this._workerInfos = workers.map(function (worker) { return ({
  10681. worker: worker,
  10682. active: false
  10683. }); });
  10684. }
  10685. /**
  10686. * Terminates all workers and clears any pending actions.
  10687. */
  10688. WorkerPool.prototype.dispose = function () {
  10689. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10690. var workerInfo = _a[_i];
  10691. workerInfo.worker.terminate();
  10692. }
  10693. delete this._workerInfos;
  10694. delete this._pendingActions;
  10695. };
  10696. /**
  10697. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10698. * pended until a worker has completed its action.
  10699. * @param action The action to perform. Call onComplete when the action is complete.
  10700. */
  10701. WorkerPool.prototype.push = function (action) {
  10702. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10703. var workerInfo = _a[_i];
  10704. if (!workerInfo.active) {
  10705. this._execute(workerInfo, action);
  10706. return;
  10707. }
  10708. }
  10709. this._pendingActions.push(action);
  10710. };
  10711. WorkerPool.prototype._execute = function (workerInfo, action) {
  10712. var _this = this;
  10713. workerInfo.active = true;
  10714. action(workerInfo.worker, function () {
  10715. workerInfo.active = false;
  10716. var nextAction = _this._pendingActions.shift();
  10717. if (nextAction) {
  10718. _this._execute(workerInfo, nextAction);
  10719. }
  10720. });
  10721. };
  10722. return WorkerPool;
  10723. }());
  10724. BABYLON.WorkerPool = WorkerPool;
  10725. })(BABYLON || (BABYLON = {}));
  10726. //# sourceMappingURL=babylon.workerPool.js.map
  10727. var BABYLON;
  10728. (function (BABYLON) {
  10729. /**
  10730. * @hidden
  10731. **/
  10732. var _AlphaState = /** @class */ (function () {
  10733. /**
  10734. * Initializes the state.
  10735. */
  10736. function _AlphaState() {
  10737. this._isAlphaBlendDirty = false;
  10738. this._isBlendFunctionParametersDirty = false;
  10739. this._isBlendEquationParametersDirty = false;
  10740. this._isBlendConstantsDirty = false;
  10741. this._alphaBlend = false;
  10742. this._blendFunctionParameters = new Array(4);
  10743. this._blendEquationParameters = new Array(2);
  10744. this._blendConstants = new Array(4);
  10745. this.reset();
  10746. }
  10747. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10748. get: function () {
  10749. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10750. },
  10751. enumerable: true,
  10752. configurable: true
  10753. });
  10754. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10755. get: function () {
  10756. return this._alphaBlend;
  10757. },
  10758. set: function (value) {
  10759. if (this._alphaBlend === value) {
  10760. return;
  10761. }
  10762. this._alphaBlend = value;
  10763. this._isAlphaBlendDirty = true;
  10764. },
  10765. enumerable: true,
  10766. configurable: true
  10767. });
  10768. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10769. if (this._blendConstants[0] === r &&
  10770. this._blendConstants[1] === g &&
  10771. this._blendConstants[2] === b &&
  10772. this._blendConstants[3] === a) {
  10773. return;
  10774. }
  10775. this._blendConstants[0] = r;
  10776. this._blendConstants[1] = g;
  10777. this._blendConstants[2] = b;
  10778. this._blendConstants[3] = a;
  10779. this._isBlendConstantsDirty = true;
  10780. };
  10781. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10782. if (this._blendFunctionParameters[0] === value0 &&
  10783. this._blendFunctionParameters[1] === value1 &&
  10784. this._blendFunctionParameters[2] === value2 &&
  10785. this._blendFunctionParameters[3] === value3) {
  10786. return;
  10787. }
  10788. this._blendFunctionParameters[0] = value0;
  10789. this._blendFunctionParameters[1] = value1;
  10790. this._blendFunctionParameters[2] = value2;
  10791. this._blendFunctionParameters[3] = value3;
  10792. this._isBlendFunctionParametersDirty = true;
  10793. };
  10794. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10795. if (this._blendEquationParameters[0] === rgb &&
  10796. this._blendEquationParameters[1] === alpha) {
  10797. return;
  10798. }
  10799. this._blendEquationParameters[0] = rgb;
  10800. this._blendEquationParameters[1] = alpha;
  10801. this._isBlendEquationParametersDirty = true;
  10802. };
  10803. _AlphaState.prototype.reset = function () {
  10804. this._alphaBlend = false;
  10805. this._blendFunctionParameters[0] = null;
  10806. this._blendFunctionParameters[1] = null;
  10807. this._blendFunctionParameters[2] = null;
  10808. this._blendFunctionParameters[3] = null;
  10809. this._blendEquationParameters[0] = null;
  10810. this._blendEquationParameters[1] = null;
  10811. this._blendConstants[0] = null;
  10812. this._blendConstants[1] = null;
  10813. this._blendConstants[2] = null;
  10814. this._blendConstants[3] = null;
  10815. this._isAlphaBlendDirty = true;
  10816. this._isBlendFunctionParametersDirty = false;
  10817. this._isBlendEquationParametersDirty = false;
  10818. this._isBlendConstantsDirty = false;
  10819. };
  10820. _AlphaState.prototype.apply = function (gl) {
  10821. if (!this.isDirty) {
  10822. return;
  10823. }
  10824. // Alpha blend
  10825. if (this._isAlphaBlendDirty) {
  10826. if (this._alphaBlend) {
  10827. gl.enable(gl.BLEND);
  10828. }
  10829. else {
  10830. gl.disable(gl.BLEND);
  10831. }
  10832. this._isAlphaBlendDirty = false;
  10833. }
  10834. // Alpha function
  10835. if (this._isBlendFunctionParametersDirty) {
  10836. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10837. this._isBlendFunctionParametersDirty = false;
  10838. }
  10839. // Alpha equation
  10840. if (this._isBlendEquationParametersDirty) {
  10841. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10842. this._isBlendEquationParametersDirty = false;
  10843. }
  10844. // Constants
  10845. if (this._isBlendConstantsDirty) {
  10846. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10847. this._isBlendConstantsDirty = false;
  10848. }
  10849. };
  10850. return _AlphaState;
  10851. }());
  10852. BABYLON._AlphaState = _AlphaState;
  10853. })(BABYLON || (BABYLON = {}));
  10854. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10855. var BABYLON;
  10856. (function (BABYLON) {
  10857. /**
  10858. * @hidden
  10859. **/
  10860. var _DepthCullingState = /** @class */ (function () {
  10861. /**
  10862. * Initializes the state.
  10863. */
  10864. function _DepthCullingState() {
  10865. this._isDepthTestDirty = false;
  10866. this._isDepthMaskDirty = false;
  10867. this._isDepthFuncDirty = false;
  10868. this._isCullFaceDirty = false;
  10869. this._isCullDirty = false;
  10870. this._isZOffsetDirty = false;
  10871. this._isFrontFaceDirty = false;
  10872. this.reset();
  10873. }
  10874. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10875. get: function () {
  10876. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10877. },
  10878. enumerable: true,
  10879. configurable: true
  10880. });
  10881. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10882. get: function () {
  10883. return this._zOffset;
  10884. },
  10885. set: function (value) {
  10886. if (this._zOffset === value) {
  10887. return;
  10888. }
  10889. this._zOffset = value;
  10890. this._isZOffsetDirty = true;
  10891. },
  10892. enumerable: true,
  10893. configurable: true
  10894. });
  10895. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10896. get: function () {
  10897. return this._cullFace;
  10898. },
  10899. set: function (value) {
  10900. if (this._cullFace === value) {
  10901. return;
  10902. }
  10903. this._cullFace = value;
  10904. this._isCullFaceDirty = true;
  10905. },
  10906. enumerable: true,
  10907. configurable: true
  10908. });
  10909. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10910. get: function () {
  10911. return this._cull;
  10912. },
  10913. set: function (value) {
  10914. if (this._cull === value) {
  10915. return;
  10916. }
  10917. this._cull = value;
  10918. this._isCullDirty = true;
  10919. },
  10920. enumerable: true,
  10921. configurable: true
  10922. });
  10923. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10924. get: function () {
  10925. return this._depthFunc;
  10926. },
  10927. set: function (value) {
  10928. if (this._depthFunc === value) {
  10929. return;
  10930. }
  10931. this._depthFunc = value;
  10932. this._isDepthFuncDirty = true;
  10933. },
  10934. enumerable: true,
  10935. configurable: true
  10936. });
  10937. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10938. get: function () {
  10939. return this._depthMask;
  10940. },
  10941. set: function (value) {
  10942. if (this._depthMask === value) {
  10943. return;
  10944. }
  10945. this._depthMask = value;
  10946. this._isDepthMaskDirty = true;
  10947. },
  10948. enumerable: true,
  10949. configurable: true
  10950. });
  10951. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10952. get: function () {
  10953. return this._depthTest;
  10954. },
  10955. set: function (value) {
  10956. if (this._depthTest === value) {
  10957. return;
  10958. }
  10959. this._depthTest = value;
  10960. this._isDepthTestDirty = true;
  10961. },
  10962. enumerable: true,
  10963. configurable: true
  10964. });
  10965. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10966. get: function () {
  10967. return this._frontFace;
  10968. },
  10969. set: function (value) {
  10970. if (this._frontFace === value) {
  10971. return;
  10972. }
  10973. this._frontFace = value;
  10974. this._isFrontFaceDirty = true;
  10975. },
  10976. enumerable: true,
  10977. configurable: true
  10978. });
  10979. _DepthCullingState.prototype.reset = function () {
  10980. this._depthMask = true;
  10981. this._depthTest = true;
  10982. this._depthFunc = null;
  10983. this._cullFace = null;
  10984. this._cull = null;
  10985. this._zOffset = 0;
  10986. this._frontFace = null;
  10987. this._isDepthTestDirty = true;
  10988. this._isDepthMaskDirty = true;
  10989. this._isDepthFuncDirty = false;
  10990. this._isCullFaceDirty = false;
  10991. this._isCullDirty = false;
  10992. this._isZOffsetDirty = false;
  10993. this._isFrontFaceDirty = false;
  10994. };
  10995. _DepthCullingState.prototype.apply = function (gl) {
  10996. if (!this.isDirty) {
  10997. return;
  10998. }
  10999. // Cull
  11000. if (this._isCullDirty) {
  11001. if (this.cull) {
  11002. gl.enable(gl.CULL_FACE);
  11003. }
  11004. else {
  11005. gl.disable(gl.CULL_FACE);
  11006. }
  11007. this._isCullDirty = false;
  11008. }
  11009. // Cull face
  11010. if (this._isCullFaceDirty) {
  11011. gl.cullFace(this.cullFace);
  11012. this._isCullFaceDirty = false;
  11013. }
  11014. // Depth mask
  11015. if (this._isDepthMaskDirty) {
  11016. gl.depthMask(this.depthMask);
  11017. this._isDepthMaskDirty = false;
  11018. }
  11019. // Depth test
  11020. if (this._isDepthTestDirty) {
  11021. if (this.depthTest) {
  11022. gl.enable(gl.DEPTH_TEST);
  11023. }
  11024. else {
  11025. gl.disable(gl.DEPTH_TEST);
  11026. }
  11027. this._isDepthTestDirty = false;
  11028. }
  11029. // Depth func
  11030. if (this._isDepthFuncDirty) {
  11031. gl.depthFunc(this.depthFunc);
  11032. this._isDepthFuncDirty = false;
  11033. }
  11034. // zOffset
  11035. if (this._isZOffsetDirty) {
  11036. if (this.zOffset) {
  11037. gl.enable(gl.POLYGON_OFFSET_FILL);
  11038. gl.polygonOffset(this.zOffset, 0);
  11039. }
  11040. else {
  11041. gl.disable(gl.POLYGON_OFFSET_FILL);
  11042. }
  11043. this._isZOffsetDirty = false;
  11044. }
  11045. // Front face
  11046. if (this._isFrontFaceDirty) {
  11047. gl.frontFace(this.frontFace);
  11048. this._isFrontFaceDirty = false;
  11049. }
  11050. };
  11051. return _DepthCullingState;
  11052. }());
  11053. BABYLON._DepthCullingState = _DepthCullingState;
  11054. })(BABYLON || (BABYLON = {}));
  11055. //# sourceMappingURL=babylon.depthCullingState.js.map
  11056. var BABYLON;
  11057. (function (BABYLON) {
  11058. /**
  11059. * @hidden
  11060. **/
  11061. var _StencilState = /** @class */ (function () {
  11062. function _StencilState() {
  11063. this._isStencilTestDirty = false;
  11064. this._isStencilMaskDirty = false;
  11065. this._isStencilFuncDirty = false;
  11066. this._isStencilOpDirty = false;
  11067. this.reset();
  11068. }
  11069. Object.defineProperty(_StencilState.prototype, "isDirty", {
  11070. get: function () {
  11071. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  11072. },
  11073. enumerable: true,
  11074. configurable: true
  11075. });
  11076. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  11077. get: function () {
  11078. return this._stencilFunc;
  11079. },
  11080. set: function (value) {
  11081. if (this._stencilFunc === value) {
  11082. return;
  11083. }
  11084. this._stencilFunc = value;
  11085. this._isStencilFuncDirty = true;
  11086. },
  11087. enumerable: true,
  11088. configurable: true
  11089. });
  11090. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  11091. get: function () {
  11092. return this._stencilFuncRef;
  11093. },
  11094. set: function (value) {
  11095. if (this._stencilFuncRef === value) {
  11096. return;
  11097. }
  11098. this._stencilFuncRef = value;
  11099. this._isStencilFuncDirty = true;
  11100. },
  11101. enumerable: true,
  11102. configurable: true
  11103. });
  11104. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  11105. get: function () {
  11106. return this._stencilFuncMask;
  11107. },
  11108. set: function (value) {
  11109. if (this._stencilFuncMask === value) {
  11110. return;
  11111. }
  11112. this._stencilFuncMask = value;
  11113. this._isStencilFuncDirty = true;
  11114. },
  11115. enumerable: true,
  11116. configurable: true
  11117. });
  11118. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  11119. get: function () {
  11120. return this._stencilOpStencilFail;
  11121. },
  11122. set: function (value) {
  11123. if (this._stencilOpStencilFail === value) {
  11124. return;
  11125. }
  11126. this._stencilOpStencilFail = value;
  11127. this._isStencilOpDirty = true;
  11128. },
  11129. enumerable: true,
  11130. configurable: true
  11131. });
  11132. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  11133. get: function () {
  11134. return this._stencilOpDepthFail;
  11135. },
  11136. set: function (value) {
  11137. if (this._stencilOpDepthFail === value) {
  11138. return;
  11139. }
  11140. this._stencilOpDepthFail = value;
  11141. this._isStencilOpDirty = true;
  11142. },
  11143. enumerable: true,
  11144. configurable: true
  11145. });
  11146. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  11147. get: function () {
  11148. return this._stencilOpStencilDepthPass;
  11149. },
  11150. set: function (value) {
  11151. if (this._stencilOpStencilDepthPass === value) {
  11152. return;
  11153. }
  11154. this._stencilOpStencilDepthPass = value;
  11155. this._isStencilOpDirty = true;
  11156. },
  11157. enumerable: true,
  11158. configurable: true
  11159. });
  11160. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  11161. get: function () {
  11162. return this._stencilMask;
  11163. },
  11164. set: function (value) {
  11165. if (this._stencilMask === value) {
  11166. return;
  11167. }
  11168. this._stencilMask = value;
  11169. this._isStencilMaskDirty = true;
  11170. },
  11171. enumerable: true,
  11172. configurable: true
  11173. });
  11174. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  11175. get: function () {
  11176. return this._stencilTest;
  11177. },
  11178. set: function (value) {
  11179. if (this._stencilTest === value) {
  11180. return;
  11181. }
  11182. this._stencilTest = value;
  11183. this._isStencilTestDirty = true;
  11184. },
  11185. enumerable: true,
  11186. configurable: true
  11187. });
  11188. _StencilState.prototype.reset = function () {
  11189. this._stencilTest = false;
  11190. this._stencilMask = 0xFF;
  11191. this._stencilFunc = BABYLON.Engine.ALWAYS;
  11192. this._stencilFuncRef = 1;
  11193. this._stencilFuncMask = 0xFF;
  11194. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  11195. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  11196. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  11197. this._isStencilTestDirty = true;
  11198. this._isStencilMaskDirty = true;
  11199. this._isStencilFuncDirty = true;
  11200. this._isStencilOpDirty = true;
  11201. };
  11202. _StencilState.prototype.apply = function (gl) {
  11203. if (!this.isDirty) {
  11204. return;
  11205. }
  11206. // Stencil test
  11207. if (this._isStencilTestDirty) {
  11208. if (this.stencilTest) {
  11209. gl.enable(gl.STENCIL_TEST);
  11210. }
  11211. else {
  11212. gl.disable(gl.STENCIL_TEST);
  11213. }
  11214. this._isStencilTestDirty = false;
  11215. }
  11216. // Stencil mask
  11217. if (this._isStencilMaskDirty) {
  11218. gl.stencilMask(this.stencilMask);
  11219. this._isStencilMaskDirty = false;
  11220. }
  11221. // Stencil func
  11222. if (this._isStencilFuncDirty) {
  11223. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  11224. this._isStencilFuncDirty = false;
  11225. }
  11226. // Stencil op
  11227. if (this._isStencilOpDirty) {
  11228. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  11229. this._isStencilOpDirty = false;
  11230. }
  11231. };
  11232. return _StencilState;
  11233. }());
  11234. BABYLON._StencilState = _StencilState;
  11235. })(BABYLON || (BABYLON = {}));
  11236. //# sourceMappingURL=babylon.stencilState.js.map
  11237. var __assign = (this && this.__assign) || function () {
  11238. __assign = Object.assign || function(t) {
  11239. for (var s, i = 1, n = arguments.length; i < n; i++) {
  11240. s = arguments[i];
  11241. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  11242. t[p] = s[p];
  11243. }
  11244. return t;
  11245. };
  11246. return __assign.apply(this, arguments);
  11247. };
  11248. var BABYLON;
  11249. (function (BABYLON) {
  11250. /**
  11251. * Keeps track of all the buffer info used in engine.
  11252. */
  11253. var BufferPointer = /** @class */ (function () {
  11254. function BufferPointer() {
  11255. }
  11256. return BufferPointer;
  11257. }());
  11258. /**
  11259. * Interface for attribute information associated with buffer instanciation
  11260. */
  11261. var InstancingAttributeInfo = /** @class */ (function () {
  11262. function InstancingAttributeInfo() {
  11263. }
  11264. return InstancingAttributeInfo;
  11265. }());
  11266. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11267. /**
  11268. * Define options used to create a render target texture
  11269. */
  11270. var RenderTargetCreationOptions = /** @class */ (function () {
  11271. function RenderTargetCreationOptions() {
  11272. }
  11273. return RenderTargetCreationOptions;
  11274. }());
  11275. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11276. /**
  11277. * Define options used to create a depth texture
  11278. */
  11279. var DepthTextureCreationOptions = /** @class */ (function () {
  11280. function DepthTextureCreationOptions() {
  11281. }
  11282. return DepthTextureCreationOptions;
  11283. }());
  11284. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11285. /**
  11286. * Class used to describe the capabilities of the engine relatively to the current browser
  11287. */
  11288. var EngineCapabilities = /** @class */ (function () {
  11289. function EngineCapabilities() {
  11290. }
  11291. return EngineCapabilities;
  11292. }());
  11293. BABYLON.EngineCapabilities = EngineCapabilities;
  11294. /**
  11295. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11296. */
  11297. var Engine = /** @class */ (function () {
  11298. /**
  11299. * Creates a new engine
  11300. * @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
  11301. * @param antialias defines enable antialiasing (default: false)
  11302. * @param options defines further options to be sent to the getContext() function
  11303. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11304. */
  11305. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11306. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11307. var _this = this;
  11308. // Public members
  11309. /**
  11310. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11311. */
  11312. this.forcePOTTextures = false;
  11313. /**
  11314. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11315. */
  11316. this.isFullscreen = false;
  11317. /**
  11318. * Gets a boolean indicating if the pointer is currently locked
  11319. */
  11320. this.isPointerLock = false;
  11321. /**
  11322. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11323. */
  11324. this.cullBackFaces = true;
  11325. /**
  11326. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11327. */
  11328. this.renderEvenInBackground = true;
  11329. /**
  11330. * Gets or sets a boolean indicating that cache can be kept between frames
  11331. */
  11332. this.preventCacheWipeBetweenFrames = false;
  11333. /**
  11334. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11335. **/
  11336. this.enableOfflineSupport = false;
  11337. /**
  11338. * 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)
  11339. **/
  11340. this.disableManifestCheck = false;
  11341. /**
  11342. * Gets the list of created scenes
  11343. */
  11344. this.scenes = new Array();
  11345. /**
  11346. * Gets the list of created postprocesses
  11347. */
  11348. this.postProcesses = new Array();
  11349. /** Gets or sets a boolean indicating if the engine should validate programs after compilation */
  11350. this.validateShaderPrograms = false;
  11351. // Observables
  11352. /**
  11353. * Observable event triggered each time the rendering canvas is resized
  11354. */
  11355. this.onResizeObservable = new BABYLON.Observable();
  11356. /**
  11357. * Observable event triggered each time the canvas loses focus
  11358. */
  11359. this.onCanvasBlurObservable = new BABYLON.Observable();
  11360. /**
  11361. * Observable event triggered each time the canvas gains focus
  11362. */
  11363. this.onCanvasFocusObservable = new BABYLON.Observable();
  11364. /**
  11365. * Observable event triggered each time the canvas receives pointerout event
  11366. */
  11367. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11368. /**
  11369. * Observable event triggered before each texture is initialized
  11370. */
  11371. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11372. //WebVR
  11373. this._vrDisplay = undefined;
  11374. this._vrSupported = false;
  11375. this._vrExclusivePointerMode = false;
  11376. // Uniform buffers list
  11377. /**
  11378. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11379. */
  11380. this.disableUniformBuffers = false;
  11381. /** @hidden */
  11382. this._uniformBuffers = new Array();
  11383. // Observables
  11384. /**
  11385. * Observable raised when the engine begins a new frame
  11386. */
  11387. this.onBeginFrameObservable = new BABYLON.Observable();
  11388. /**
  11389. * Observable raised when the engine ends the current frame
  11390. */
  11391. this.onEndFrameObservable = new BABYLON.Observable();
  11392. /**
  11393. * Observable raised when the engine is about to compile a shader
  11394. */
  11395. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11396. /**
  11397. * Observable raised when the engine has jsut compiled a shader
  11398. */
  11399. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11400. this._windowIsBackground = false;
  11401. this._webGLVersion = 1.0;
  11402. /** @hidden */
  11403. this._badOS = false;
  11404. /** @hidden */
  11405. this._badDesktopOS = false;
  11406. /**
  11407. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11408. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11409. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11410. */
  11411. this.disableTextureBindingOptimization = false;
  11412. /**
  11413. * Observable signaled when VR display mode changes
  11414. */
  11415. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11416. /**
  11417. * Observable signaled when VR request present is complete
  11418. */
  11419. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11420. /**
  11421. * Observable signaled when VR request present starts
  11422. */
  11423. this.onVRRequestPresentStart = new BABYLON.Observable();
  11424. this._colorWrite = true;
  11425. /** @hidden */
  11426. this._drawCalls = new BABYLON.PerfCounter();
  11427. /** @hidden */
  11428. this._textureCollisions = new BABYLON.PerfCounter();
  11429. this._renderingQueueLaunched = false;
  11430. this._activeRenderLoops = new Array();
  11431. // Deterministic lockstepMaxSteps
  11432. this._deterministicLockstep = false;
  11433. this._lockstepMaxSteps = 4;
  11434. // Lost context
  11435. /**
  11436. * Observable signaled when a context lost event is raised
  11437. */
  11438. this.onContextLostObservable = new BABYLON.Observable();
  11439. /**
  11440. * Observable signaled when a context restored event is raised
  11441. */
  11442. this.onContextRestoredObservable = new BABYLON.Observable();
  11443. this._contextWasLost = false;
  11444. this._doNotHandleContextLost = false;
  11445. // FPS
  11446. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11447. this._fps = 60;
  11448. this._deltaTime = 0;
  11449. /**
  11450. * Turn this value on if you want to pause FPS computation when in background
  11451. */
  11452. this.disablePerformanceMonitorInBackground = false;
  11453. // States
  11454. /** @hidden */
  11455. this._depthCullingState = new BABYLON._DepthCullingState();
  11456. /** @hidden */
  11457. this._stencilState = new BABYLON._StencilState();
  11458. /** @hidden */
  11459. this._alphaState = new BABYLON._AlphaState();
  11460. /** @hidden */
  11461. this._alphaMode = Engine.ALPHA_DISABLE;
  11462. // Cache
  11463. this._internalTexturesCache = new Array();
  11464. /** @hidden */
  11465. this._activeChannel = 0;
  11466. this._currentTextureChannel = -1;
  11467. /** @hidden */
  11468. this._boundTexturesCache = {};
  11469. this._compiledEffects = {};
  11470. this._vertexAttribArraysEnabled = [];
  11471. this._uintIndicesCurrentlySet = false;
  11472. this._currentBoundBuffer = new Array();
  11473. /** @hidden */
  11474. this._currentFramebuffer = null;
  11475. this._currentBufferPointers = new Array();
  11476. this._currentInstanceLocations = new Array();
  11477. this._currentInstanceBuffers = new Array();
  11478. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11479. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11480. this._vaoRecordInProgress = false;
  11481. this._mustWipeVertexAttributes = false;
  11482. this._nextFreeTextureSlots = new Array();
  11483. this._maxSimultaneousTextures = 0;
  11484. this._activeRequests = new Array();
  11485. // Hardware supported Compressed Textures
  11486. this._texturesSupported = new Array();
  11487. /**
  11488. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  11489. */
  11490. this.premultipliedAlpha = true;
  11491. this._viewportCached = new BABYLON.Vector4(0, 0, 0, 0);
  11492. this._onVRFullScreenTriggered = function () {
  11493. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11494. //get the old size before we change
  11495. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11496. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11497. //get the width and height, change the render size
  11498. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11499. _this.setHardwareScalingLevel(1);
  11500. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11501. }
  11502. else {
  11503. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11504. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11505. }
  11506. };
  11507. this._unpackFlipYCached = null;
  11508. /**
  11509. * In case you are sharing the context with other applications, it might
  11510. * be interested to not cache the unpack flip y state to ensure a consistent
  11511. * value would be set.
  11512. */
  11513. this.enableUnpackFlipYCached = true;
  11514. this._boundUniforms = {};
  11515. // Register promises
  11516. BABYLON.PromisePolyfill.Apply();
  11517. var canvas = null;
  11518. Engine.Instances.push(this);
  11519. if (!canvasOrContext) {
  11520. return;
  11521. }
  11522. options = options || {};
  11523. if (canvasOrContext.getContext) {
  11524. canvas = canvasOrContext;
  11525. this._renderingCanvas = canvas;
  11526. if (antialias != null) {
  11527. options.antialias = antialias;
  11528. }
  11529. if (options.deterministicLockstep === undefined) {
  11530. options.deterministicLockstep = false;
  11531. }
  11532. if (options.lockstepMaxSteps === undefined) {
  11533. options.lockstepMaxSteps = 4;
  11534. }
  11535. if (options.preserveDrawingBuffer === undefined) {
  11536. options.preserveDrawingBuffer = false;
  11537. }
  11538. if (options.audioEngine === undefined) {
  11539. options.audioEngine = true;
  11540. }
  11541. if (options.stencil === undefined) {
  11542. options.stencil = true;
  11543. }
  11544. if (options.premultipliedAlpha === false) {
  11545. this.premultipliedAlpha = false;
  11546. }
  11547. this._deterministicLockstep = options.deterministicLockstep;
  11548. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11549. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11550. // Exceptions
  11551. if (navigator && navigator.userAgent) {
  11552. var ua = navigator.userAgent;
  11553. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11554. var exception = _a[_i];
  11555. var key = exception.key;
  11556. var targets = exception.targets;
  11557. if (ua.indexOf(key) > -1) {
  11558. if (exception.capture && exception.captureConstraint) {
  11559. var capture = exception.capture;
  11560. var constraint = exception.captureConstraint;
  11561. var regex = new RegExp(capture);
  11562. var matches = regex.exec(ua);
  11563. if (matches && matches.length > 0) {
  11564. var capturedValue = parseInt(matches[matches.length - 1]);
  11565. if (capturedValue >= constraint) {
  11566. continue;
  11567. }
  11568. }
  11569. }
  11570. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11571. var target = targets_1[_b];
  11572. switch (target) {
  11573. case "uniformBuffer":
  11574. this.disableUniformBuffers = true;
  11575. break;
  11576. case "textureBindingOptimization":
  11577. this.disableTextureBindingOptimization = true;
  11578. break;
  11579. }
  11580. }
  11581. }
  11582. }
  11583. }
  11584. // GL
  11585. if (!options.disableWebGL2Support) {
  11586. try {
  11587. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11588. if (this._gl) {
  11589. this._webGLVersion = 2.0;
  11590. }
  11591. }
  11592. catch (e) {
  11593. // Do nothing
  11594. }
  11595. }
  11596. if (!this._gl) {
  11597. if (!canvas) {
  11598. throw new Error("The provided canvas is null or undefined.");
  11599. }
  11600. try {
  11601. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11602. }
  11603. catch (e) {
  11604. throw new Error("WebGL not supported");
  11605. }
  11606. }
  11607. if (!this._gl) {
  11608. throw new Error("WebGL not supported");
  11609. }
  11610. this._onCanvasFocus = function () {
  11611. _this.onCanvasFocusObservable.notifyObservers(_this);
  11612. };
  11613. this._onCanvasBlur = function () {
  11614. _this.onCanvasBlurObservable.notifyObservers(_this);
  11615. };
  11616. canvas.addEventListener("focus", this._onCanvasFocus);
  11617. canvas.addEventListener("blur", this._onCanvasBlur);
  11618. this._onBlur = function () {
  11619. if (_this.disablePerformanceMonitorInBackground) {
  11620. _this._performanceMonitor.disable();
  11621. }
  11622. _this._windowIsBackground = true;
  11623. };
  11624. this._onFocus = function () {
  11625. if (_this.disablePerformanceMonitorInBackground) {
  11626. _this._performanceMonitor.enable();
  11627. }
  11628. _this._windowIsBackground = false;
  11629. };
  11630. this._onCanvasPointerOut = function (ev) {
  11631. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11632. };
  11633. window.addEventListener("blur", this._onBlur);
  11634. window.addEventListener("focus", this._onFocus);
  11635. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11636. // Context lost
  11637. if (!this._doNotHandleContextLost) {
  11638. this._onContextLost = function (evt) {
  11639. evt.preventDefault();
  11640. _this._contextWasLost = true;
  11641. BABYLON.Tools.Warn("WebGL context lost.");
  11642. _this.onContextLostObservable.notifyObservers(_this);
  11643. };
  11644. this._onContextRestored = function (evt) {
  11645. // Adding a timeout to avoid race condition at browser level
  11646. setTimeout(function () {
  11647. // Rebuild gl context
  11648. _this._initGLContext();
  11649. // Rebuild effects
  11650. _this._rebuildEffects();
  11651. // Rebuild textures
  11652. _this._rebuildInternalTextures();
  11653. // Rebuild buffers
  11654. _this._rebuildBuffers();
  11655. // Cache
  11656. _this.wipeCaches(true);
  11657. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11658. _this.onContextRestoredObservable.notifyObservers(_this);
  11659. _this._contextWasLost = false;
  11660. }, 0);
  11661. };
  11662. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11663. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11664. }
  11665. }
  11666. else {
  11667. this._gl = canvasOrContext;
  11668. this._renderingCanvas = this._gl.canvas;
  11669. if (this._gl.renderbufferStorageMultisample) {
  11670. this._webGLVersion = 2.0;
  11671. }
  11672. options.stencil = this._gl.getContextAttributes().stencil;
  11673. }
  11674. // Viewport
  11675. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11676. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11677. this.resize();
  11678. this._isStencilEnable = options.stencil ? true : false;
  11679. this._initGLContext();
  11680. if (canvas) {
  11681. // Fullscreen
  11682. this._onFullscreenChange = function () {
  11683. if (document.fullscreen !== undefined) {
  11684. _this.isFullscreen = document.fullscreen;
  11685. }
  11686. else if (document.mozFullScreen !== undefined) {
  11687. _this.isFullscreen = document.mozFullScreen;
  11688. }
  11689. else if (document.webkitIsFullScreen !== undefined) {
  11690. _this.isFullscreen = document.webkitIsFullScreen;
  11691. }
  11692. else if (document.msIsFullScreen !== undefined) {
  11693. _this.isFullscreen = document.msIsFullScreen;
  11694. }
  11695. // Pointer lock
  11696. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11697. canvas.requestPointerLock = canvas.requestPointerLock ||
  11698. canvas.msRequestPointerLock ||
  11699. canvas.mozRequestPointerLock ||
  11700. canvas.webkitRequestPointerLock;
  11701. if (canvas.requestPointerLock) {
  11702. canvas.requestPointerLock();
  11703. }
  11704. }
  11705. };
  11706. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11707. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11708. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11709. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11710. // Pointer lock
  11711. this._onPointerLockChange = function () {
  11712. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11713. document.webkitPointerLockElement === canvas ||
  11714. document.msPointerLockElement === canvas ||
  11715. document.pointerLockElement === canvas);
  11716. };
  11717. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11718. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11719. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11720. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11721. this._onVRDisplayPointerRestricted = function () {
  11722. if (canvas) {
  11723. canvas.requestPointerLock();
  11724. }
  11725. };
  11726. this._onVRDisplayPointerUnrestricted = function () {
  11727. document.exitPointerLock();
  11728. };
  11729. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11730. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11731. }
  11732. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  11733. Engine.audioEngine = new BABYLON.AudioEngine();
  11734. }
  11735. // Prepare buffer pointers
  11736. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11737. this._currentBufferPointers[i] = new BufferPointer();
  11738. }
  11739. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11740. // Load WebVR Devices
  11741. if (options.autoEnableWebVR) {
  11742. this.initWebVR();
  11743. }
  11744. // Detect if we are running on a faulty buggy OS.
  11745. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11746. // Detect if we are running on a faulty buggy desktop OS.
  11747. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11748. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11749. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11750. }
  11751. Object.defineProperty(Engine, "LastCreatedEngine", {
  11752. /**
  11753. * Gets the latest created engine
  11754. */
  11755. get: function () {
  11756. if (Engine.Instances.length === 0) {
  11757. return null;
  11758. }
  11759. return Engine.Instances[Engine.Instances.length - 1];
  11760. },
  11761. enumerable: true,
  11762. configurable: true
  11763. });
  11764. Object.defineProperty(Engine, "LastCreatedScene", {
  11765. /**
  11766. * Gets the latest created scene
  11767. */
  11768. get: function () {
  11769. var lastCreatedEngine = Engine.LastCreatedEngine;
  11770. if (!lastCreatedEngine) {
  11771. return null;
  11772. }
  11773. if (lastCreatedEngine.scenes.length === 0) {
  11774. return null;
  11775. }
  11776. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11777. },
  11778. enumerable: true,
  11779. configurable: true
  11780. });
  11781. /**
  11782. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11783. * @param flag defines which part of the materials must be marked as dirty
  11784. * @param predicate defines a predicate used to filter which materials should be affected
  11785. */
  11786. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11787. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11788. var engine = Engine.Instances[engineIndex];
  11789. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11790. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11791. }
  11792. }
  11793. };
  11794. Object.defineProperty(Engine, "Version", {
  11795. /**
  11796. * Returns the current version of the framework
  11797. */
  11798. get: function () {
  11799. return "3.3.0-beta.5";
  11800. },
  11801. enumerable: true,
  11802. configurable: true
  11803. });
  11804. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11805. /**
  11806. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  11807. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  11808. */
  11809. get: function () {
  11810. return this._vrExclusivePointerMode;
  11811. },
  11812. enumerable: true,
  11813. configurable: true
  11814. });
  11815. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11816. /**
  11817. * Gets a boolean indicating that the engine supports uniform buffers
  11818. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  11819. */
  11820. get: function () {
  11821. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11822. },
  11823. enumerable: true,
  11824. configurable: true
  11825. });
  11826. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11827. /**
  11828. * Gets a boolean indicating that only power of 2 textures are supported
  11829. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  11830. */
  11831. get: function () {
  11832. return this._webGLVersion < 2 || this.forcePOTTextures;
  11833. },
  11834. enumerable: true,
  11835. configurable: true
  11836. });
  11837. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  11838. /**
  11839. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  11840. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  11841. */
  11842. get: function () {
  11843. return this._doNotHandleContextLost;
  11844. },
  11845. set: function (value) {
  11846. this._doNotHandleContextLost = value;
  11847. },
  11848. enumerable: true,
  11849. configurable: true
  11850. });
  11851. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11852. /**
  11853. * Gets the performance monitor attached to this engine
  11854. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  11855. */
  11856. get: function () {
  11857. return this._performanceMonitor;
  11858. },
  11859. enumerable: true,
  11860. configurable: true
  11861. });
  11862. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11863. /**
  11864. * Gets the list of texture formats supported
  11865. */
  11866. get: function () {
  11867. return this._texturesSupported;
  11868. },
  11869. enumerable: true,
  11870. configurable: true
  11871. });
  11872. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11873. /**
  11874. * Gets the list of texture formats in use
  11875. */
  11876. get: function () {
  11877. return this._textureFormatInUse;
  11878. },
  11879. enumerable: true,
  11880. configurable: true
  11881. });
  11882. Object.defineProperty(Engine.prototype, "currentViewport", {
  11883. /**
  11884. * Gets the current viewport
  11885. */
  11886. get: function () {
  11887. return this._cachedViewport;
  11888. },
  11889. enumerable: true,
  11890. configurable: true
  11891. });
  11892. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11893. /**
  11894. * Gets the default empty texture
  11895. */
  11896. get: function () {
  11897. if (!this._emptyTexture) {
  11898. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11899. }
  11900. return this._emptyTexture;
  11901. },
  11902. enumerable: true,
  11903. configurable: true
  11904. });
  11905. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  11906. /**
  11907. * Gets the default empty 3D texture
  11908. */
  11909. get: function () {
  11910. if (!this._emptyTexture3D) {
  11911. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11912. }
  11913. return this._emptyTexture3D;
  11914. },
  11915. enumerable: true,
  11916. configurable: true
  11917. });
  11918. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11919. /**
  11920. * Gets the default empty cube texture
  11921. */
  11922. get: function () {
  11923. if (!this._emptyCubeTexture) {
  11924. var faceData = new Uint8Array(4);
  11925. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11926. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11927. }
  11928. return this._emptyCubeTexture;
  11929. },
  11930. enumerable: true,
  11931. configurable: true
  11932. });
  11933. Engine.prototype._rebuildInternalTextures = function () {
  11934. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  11935. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  11936. var internalTexture = currentState_1[_i];
  11937. internalTexture._rebuild();
  11938. }
  11939. };
  11940. Engine.prototype._rebuildEffects = function () {
  11941. for (var key in this._compiledEffects) {
  11942. var effect = this._compiledEffects[key];
  11943. effect._prepareEffect();
  11944. }
  11945. BABYLON.Effect.ResetCache();
  11946. };
  11947. Engine.prototype._rebuildBuffers = function () {
  11948. // Index / Vertex
  11949. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  11950. var scene = _a[_i];
  11951. scene.resetCachedMaterial();
  11952. scene._rebuildGeometries();
  11953. scene._rebuildTextures();
  11954. }
  11955. // Uniforms
  11956. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  11957. var uniformBuffer = _c[_b];
  11958. uniformBuffer._rebuild();
  11959. }
  11960. };
  11961. Engine.prototype._initGLContext = function () {
  11962. // Caps
  11963. this._caps = new EngineCapabilities();
  11964. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  11965. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  11966. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  11967. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  11968. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  11969. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  11970. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  11971. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  11972. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  11973. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  11974. // Infos
  11975. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  11976. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  11977. if (rendererInfo != null) {
  11978. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  11979. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  11980. }
  11981. if (!this._glVendor) {
  11982. this._glVendor = "Unknown vendor";
  11983. }
  11984. if (!this._glRenderer) {
  11985. this._glRenderer = "Unknown renderer";
  11986. }
  11987. // Constants
  11988. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  11989. if (this._gl.RGBA16F !== 0x881A) {
  11990. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  11991. }
  11992. if (this._gl.RGBA32F !== 0x8814) {
  11993. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  11994. }
  11995. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  11996. this._gl.DEPTH24_STENCIL8 = 35056;
  11997. }
  11998. // Extensions
  11999. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  12000. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  12001. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  12002. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  12003. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  12004. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  12005. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  12006. 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');
  12007. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  12008. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  12009. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  12010. this._caps.highPrecisionShaderSupported = true;
  12011. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  12012. if (this._caps.timerQuery) {
  12013. if (this._webGLVersion === 1) {
  12014. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  12015. }
  12016. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  12017. }
  12018. // Checks if some of the format renders first to allow the use of webgl inspector.
  12019. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  12020. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  12021. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  12022. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  12023. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  12024. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  12025. if (this._webGLVersion > 1) {
  12026. this._gl.HALF_FLOAT_OES = 0x140B;
  12027. }
  12028. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  12029. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  12030. // Draw buffers
  12031. if (this._webGLVersion > 1) {
  12032. this._caps.drawBuffersExtension = true;
  12033. }
  12034. else {
  12035. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  12036. if (drawBuffersExtension !== null) {
  12037. this._caps.drawBuffersExtension = true;
  12038. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12039. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12040. for (var i = 0; i < 16; i++) {
  12041. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12042. }
  12043. }
  12044. else {
  12045. this._caps.drawBuffersExtension = false;
  12046. }
  12047. }
  12048. // Depth Texture
  12049. if (this._webGLVersion > 1) {
  12050. this._caps.depthTextureExtension = true;
  12051. }
  12052. else {
  12053. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12054. if (depthTextureExtension != null) {
  12055. this._caps.depthTextureExtension = true;
  12056. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12057. }
  12058. }
  12059. // Vertex array object
  12060. if (this._webGLVersion > 1) {
  12061. this._caps.vertexArrayObject = true;
  12062. }
  12063. else {
  12064. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12065. if (vertexArrayObjectExtension != null) {
  12066. this._caps.vertexArrayObject = true;
  12067. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12068. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12069. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12070. }
  12071. else {
  12072. this._caps.vertexArrayObject = false;
  12073. }
  12074. }
  12075. // Instances count
  12076. if (this._webGLVersion > 1) {
  12077. this._caps.instancedArrays = true;
  12078. }
  12079. else {
  12080. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12081. if (instanceExtension != null) {
  12082. this._caps.instancedArrays = true;
  12083. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12084. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12085. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12086. }
  12087. else {
  12088. this._caps.instancedArrays = false;
  12089. }
  12090. }
  12091. // Intelligently add supported compressed formats in order to check for.
  12092. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12093. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12094. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12095. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12096. if (this._caps.astc)
  12097. this.texturesSupported.push('-astc.ktx');
  12098. if (this._caps.s3tc)
  12099. this.texturesSupported.push('-dxt.ktx');
  12100. if (this._caps.pvrtc)
  12101. this.texturesSupported.push('-pvrtc.ktx');
  12102. if (this._caps.etc2)
  12103. this.texturesSupported.push('-etc2.ktx');
  12104. if (this._caps.etc1)
  12105. this.texturesSupported.push('-etc1.ktx');
  12106. if (this._gl.getShaderPrecisionFormat) {
  12107. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12108. if (highp) {
  12109. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12110. }
  12111. }
  12112. // Depth buffer
  12113. this.setDepthBuffer(true);
  12114. this.setDepthFunctionToLessOrEqual();
  12115. this.setDepthWrite(true);
  12116. // Texture maps
  12117. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12118. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12119. this._nextFreeTextureSlots.push(slot);
  12120. }
  12121. };
  12122. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12123. /**
  12124. * Gets version of the current webGL context
  12125. */
  12126. get: function () {
  12127. return this._webGLVersion;
  12128. },
  12129. enumerable: true,
  12130. configurable: true
  12131. });
  12132. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12133. /**
  12134. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12135. */
  12136. get: function () {
  12137. return this._isStencilEnable;
  12138. },
  12139. enumerable: true,
  12140. configurable: true
  12141. });
  12142. Engine.prototype._prepareWorkingCanvas = function () {
  12143. if (this._workingCanvas) {
  12144. return;
  12145. }
  12146. this._workingCanvas = document.createElement("canvas");
  12147. var context = this._workingCanvas.getContext("2d");
  12148. if (context) {
  12149. this._workingContext = context;
  12150. }
  12151. };
  12152. /**
  12153. * Reset the texture cache to empty state
  12154. */
  12155. Engine.prototype.resetTextureCache = function () {
  12156. for (var key in this._boundTexturesCache) {
  12157. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12158. continue;
  12159. }
  12160. var boundTexture = this._boundTexturesCache[key];
  12161. if (boundTexture) {
  12162. this._removeDesignatedSlot(boundTexture);
  12163. }
  12164. this._boundTexturesCache[key] = null;
  12165. }
  12166. if (!this.disableTextureBindingOptimization) {
  12167. this._nextFreeTextureSlots = [];
  12168. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12169. this._nextFreeTextureSlots.push(slot);
  12170. }
  12171. }
  12172. this._currentTextureChannel = -1;
  12173. };
  12174. /**
  12175. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12176. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12177. * @returns true if engine is in deterministic lock step mode
  12178. */
  12179. Engine.prototype.isDeterministicLockStep = function () {
  12180. return this._deterministicLockstep;
  12181. };
  12182. /**
  12183. * Gets the max steps when engine is running in deterministic lock step
  12184. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12185. * @returns the max steps
  12186. */
  12187. Engine.prototype.getLockstepMaxSteps = function () {
  12188. return this._lockstepMaxSteps;
  12189. };
  12190. /**
  12191. * Gets an object containing information about the current webGL context
  12192. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12193. */
  12194. Engine.prototype.getGlInfo = function () {
  12195. return {
  12196. vendor: this._glVendor,
  12197. renderer: this._glRenderer,
  12198. version: this._glVersion
  12199. };
  12200. };
  12201. /**
  12202. * Gets current aspect ratio
  12203. * @param camera defines the camera to use to get the aspect ratio
  12204. * @param useScreen defines if screen size must be used (or the current render target if any)
  12205. * @returns a number defining the aspect ratio
  12206. */
  12207. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12208. if (useScreen === void 0) { useScreen = false; }
  12209. var viewport = camera.viewport;
  12210. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12211. };
  12212. /**
  12213. * Gets current screen aspect ratio
  12214. * @returns a number defining the aspect ratio
  12215. */
  12216. Engine.prototype.getScreenAspectRatio = function () {
  12217. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  12218. };
  12219. /**
  12220. * Gets the current render width
  12221. * @param useScreen defines if screen size must be used (or the current render target if any)
  12222. * @returns a number defining the current render width
  12223. */
  12224. Engine.prototype.getRenderWidth = function (useScreen) {
  12225. if (useScreen === void 0) { useScreen = false; }
  12226. if (!useScreen && this._currentRenderTarget) {
  12227. return this._currentRenderTarget.width;
  12228. }
  12229. return this._gl.drawingBufferWidth;
  12230. };
  12231. /**
  12232. * Gets the current render height
  12233. * @param useScreen defines if screen size must be used (or the current render target if any)
  12234. * @returns a number defining the current render height
  12235. */
  12236. Engine.prototype.getRenderHeight = function (useScreen) {
  12237. if (useScreen === void 0) { useScreen = false; }
  12238. if (!useScreen && this._currentRenderTarget) {
  12239. return this._currentRenderTarget.height;
  12240. }
  12241. return this._gl.drawingBufferHeight;
  12242. };
  12243. /**
  12244. * Gets the HTML canvas attached with the current webGL context
  12245. * @returns a HTML canvas
  12246. */
  12247. Engine.prototype.getRenderingCanvas = function () {
  12248. return this._renderingCanvas;
  12249. };
  12250. /**
  12251. * Gets the client rect of the HTML canvas attached with the current webGL context
  12252. * @returns a client rectanglee
  12253. */
  12254. Engine.prototype.getRenderingCanvasClientRect = function () {
  12255. if (!this._renderingCanvas) {
  12256. return null;
  12257. }
  12258. return this._renderingCanvas.getBoundingClientRect();
  12259. };
  12260. /**
  12261. * Defines the hardware scaling level.
  12262. * By default the hardware scaling level is computed from the window device ratio.
  12263. * 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.
  12264. * @param level defines the level to use
  12265. */
  12266. Engine.prototype.setHardwareScalingLevel = function (level) {
  12267. this._hardwareScalingLevel = level;
  12268. this.resize();
  12269. };
  12270. /**
  12271. * Gets the current hardware scaling level.
  12272. * By default the hardware scaling level is computed from the window device ratio.
  12273. * 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.
  12274. * @returns a number indicating the current hardware scaling level
  12275. */
  12276. Engine.prototype.getHardwareScalingLevel = function () {
  12277. return this._hardwareScalingLevel;
  12278. };
  12279. /**
  12280. * Gets the list of loaded textures
  12281. * @returns an array containing all loaded textures
  12282. */
  12283. Engine.prototype.getLoadedTexturesCache = function () {
  12284. return this._internalTexturesCache;
  12285. };
  12286. /**
  12287. * Gets the object containing all engine capabilities
  12288. * @returns the EngineCapabilities object
  12289. */
  12290. Engine.prototype.getCaps = function () {
  12291. return this._caps;
  12292. };
  12293. Object.defineProperty(Engine.prototype, "drawCalls", {
  12294. /** @hidden */
  12295. get: function () {
  12296. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12297. return 0;
  12298. },
  12299. enumerable: true,
  12300. configurable: true
  12301. });
  12302. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12303. /** @hidden */
  12304. get: function () {
  12305. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12306. return null;
  12307. },
  12308. enumerable: true,
  12309. configurable: true
  12310. });
  12311. /**
  12312. * Gets the current depth function
  12313. * @returns a number defining the depth function
  12314. */
  12315. Engine.prototype.getDepthFunction = function () {
  12316. return this._depthCullingState.depthFunc;
  12317. };
  12318. /**
  12319. * Sets the current depth function
  12320. * @param depthFunc defines the function to use
  12321. */
  12322. Engine.prototype.setDepthFunction = function (depthFunc) {
  12323. this._depthCullingState.depthFunc = depthFunc;
  12324. };
  12325. /**
  12326. * Sets the current depth function to GREATER
  12327. */
  12328. Engine.prototype.setDepthFunctionToGreater = function () {
  12329. this._depthCullingState.depthFunc = this._gl.GREATER;
  12330. };
  12331. /**
  12332. * Sets the current depth function to GEQUAL
  12333. */
  12334. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12335. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12336. };
  12337. /**
  12338. * Sets the current depth function to LESS
  12339. */
  12340. Engine.prototype.setDepthFunctionToLess = function () {
  12341. this._depthCullingState.depthFunc = this._gl.LESS;
  12342. };
  12343. /**
  12344. * Sets the current depth function to LEQUAL
  12345. */
  12346. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12347. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12348. };
  12349. /**
  12350. * Gets a boolean indicating if stencil buffer is enabled
  12351. * @returns the current stencil buffer state
  12352. */
  12353. Engine.prototype.getStencilBuffer = function () {
  12354. return this._stencilState.stencilTest;
  12355. };
  12356. /**
  12357. * Enable or disable the stencil buffer
  12358. * @param enable defines if the stencil buffer must be enabled or disabled
  12359. */
  12360. Engine.prototype.setStencilBuffer = function (enable) {
  12361. this._stencilState.stencilTest = enable;
  12362. };
  12363. /**
  12364. * Gets the current stencil mask
  12365. * @returns a number defining the new stencil mask to use
  12366. */
  12367. Engine.prototype.getStencilMask = function () {
  12368. return this._stencilState.stencilMask;
  12369. };
  12370. /**
  12371. * Sets the current stencil mask
  12372. * @param mask defines the new stencil mask to use
  12373. */
  12374. Engine.prototype.setStencilMask = function (mask) {
  12375. this._stencilState.stencilMask = mask;
  12376. };
  12377. /**
  12378. * Gets the current stencil function
  12379. * @returns a number defining the stencil function to use
  12380. */
  12381. Engine.prototype.getStencilFunction = function () {
  12382. return this._stencilState.stencilFunc;
  12383. };
  12384. /**
  12385. * Gets the current stencil reference value
  12386. * @returns a number defining the stencil reference value to use
  12387. */
  12388. Engine.prototype.getStencilFunctionReference = function () {
  12389. return this._stencilState.stencilFuncRef;
  12390. };
  12391. /**
  12392. * Gets the current stencil mask
  12393. * @returns a number defining the stencil mask to use
  12394. */
  12395. Engine.prototype.getStencilFunctionMask = function () {
  12396. return this._stencilState.stencilFuncMask;
  12397. };
  12398. /**
  12399. * Sets the current stencil function
  12400. * @param stencilFunc defines the new stencil function to use
  12401. */
  12402. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12403. this._stencilState.stencilFunc = stencilFunc;
  12404. };
  12405. /**
  12406. * Sets the current stencil reference
  12407. * @param reference defines the new stencil reference to use
  12408. */
  12409. Engine.prototype.setStencilFunctionReference = function (reference) {
  12410. this._stencilState.stencilFuncRef = reference;
  12411. };
  12412. /**
  12413. * Sets the current stencil mask
  12414. * @param mask defines the new stencil mask to use
  12415. */
  12416. Engine.prototype.setStencilFunctionMask = function (mask) {
  12417. this._stencilState.stencilFuncMask = mask;
  12418. };
  12419. /**
  12420. * Gets the current stencil operation when stencil fails
  12421. * @returns a number defining stencil operation to use when stencil fails
  12422. */
  12423. Engine.prototype.getStencilOperationFail = function () {
  12424. return this._stencilState.stencilOpStencilFail;
  12425. };
  12426. /**
  12427. * Gets the current stencil operation when depth fails
  12428. * @returns a number defining stencil operation to use when depth fails
  12429. */
  12430. Engine.prototype.getStencilOperationDepthFail = function () {
  12431. return this._stencilState.stencilOpDepthFail;
  12432. };
  12433. /**
  12434. * Gets the current stencil operation when stencil passes
  12435. * @returns a number defining stencil operation to use when stencil passes
  12436. */
  12437. Engine.prototype.getStencilOperationPass = function () {
  12438. return this._stencilState.stencilOpStencilDepthPass;
  12439. };
  12440. /**
  12441. * Sets the stencil operation to use when stencil fails
  12442. * @param operation defines the stencil operation to use when stencil fails
  12443. */
  12444. Engine.prototype.setStencilOperationFail = function (operation) {
  12445. this._stencilState.stencilOpStencilFail = operation;
  12446. };
  12447. /**
  12448. * Sets the stencil operation to use when depth fails
  12449. * @param operation defines the stencil operation to use when depth fails
  12450. */
  12451. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12452. this._stencilState.stencilOpDepthFail = operation;
  12453. };
  12454. /**
  12455. * Sets the stencil operation to use when stencil passes
  12456. * @param operation defines the stencil operation to use when stencil passes
  12457. */
  12458. Engine.prototype.setStencilOperationPass = function (operation) {
  12459. this._stencilState.stencilOpStencilDepthPass = operation;
  12460. };
  12461. /**
  12462. * Sets a boolean indicating if the dithering state is enabled or disabled
  12463. * @param value defines the dithering state
  12464. */
  12465. Engine.prototype.setDitheringState = function (value) {
  12466. if (value) {
  12467. this._gl.enable(this._gl.DITHER);
  12468. }
  12469. else {
  12470. this._gl.disable(this._gl.DITHER);
  12471. }
  12472. };
  12473. /**
  12474. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12475. * @param value defines the rasterizer state
  12476. */
  12477. Engine.prototype.setRasterizerState = function (value) {
  12478. if (value) {
  12479. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12480. }
  12481. else {
  12482. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12483. }
  12484. };
  12485. /**
  12486. * stop executing a render loop function and remove it from the execution array
  12487. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12488. */
  12489. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12490. if (!renderFunction) {
  12491. this._activeRenderLoops = [];
  12492. return;
  12493. }
  12494. var index = this._activeRenderLoops.indexOf(renderFunction);
  12495. if (index >= 0) {
  12496. this._activeRenderLoops.splice(index, 1);
  12497. }
  12498. };
  12499. /** @hidden */
  12500. Engine.prototype._renderLoop = function () {
  12501. if (!this._contextWasLost) {
  12502. var shouldRender = true;
  12503. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12504. shouldRender = false;
  12505. }
  12506. if (shouldRender) {
  12507. // Start new frame
  12508. this.beginFrame();
  12509. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12510. var renderFunction = this._activeRenderLoops[index];
  12511. renderFunction();
  12512. }
  12513. // Present
  12514. this.endFrame();
  12515. }
  12516. }
  12517. if (this._activeRenderLoops.length > 0) {
  12518. // Register new frame
  12519. var requester = null;
  12520. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12521. requester = this._vrDisplay;
  12522. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12523. }
  12524. else {
  12525. this._renderingQueueLaunched = false;
  12526. }
  12527. };
  12528. /**
  12529. * Register and execute a render loop. The engine can have more than one render function
  12530. * @param renderFunction defines the function to continuously execute
  12531. */
  12532. Engine.prototype.runRenderLoop = function (renderFunction) {
  12533. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12534. return;
  12535. }
  12536. this._activeRenderLoops.push(renderFunction);
  12537. if (!this._renderingQueueLaunched) {
  12538. this._renderingQueueLaunched = true;
  12539. this._bindedRenderFunction = this._renderLoop.bind(this);
  12540. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12541. }
  12542. };
  12543. /**
  12544. * Toggle full screen mode
  12545. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12546. * @param options defines an option object to be sent to the requestFullscreen function
  12547. */
  12548. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12549. if (this.isFullscreen) {
  12550. BABYLON.Tools.ExitFullscreen();
  12551. }
  12552. else {
  12553. this._pointerLockRequested = requestPointerLock;
  12554. if (this._renderingCanvas) {
  12555. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12556. }
  12557. }
  12558. };
  12559. /**
  12560. * Clear the current render buffer or the current render target (if any is set up)
  12561. * @param color defines the color to use
  12562. * @param backBuffer defines if the back buffer must be cleared
  12563. * @param depth defines if the depth buffer must be cleared
  12564. * @param stencil defines if the stencil buffer must be cleared
  12565. */
  12566. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12567. if (stencil === void 0) { stencil = false; }
  12568. this.applyStates();
  12569. var mode = 0;
  12570. if (backBuffer && color) {
  12571. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12572. mode |= this._gl.COLOR_BUFFER_BIT;
  12573. }
  12574. if (depth) {
  12575. this._gl.clearDepth(1.0);
  12576. mode |= this._gl.DEPTH_BUFFER_BIT;
  12577. }
  12578. if (stencil) {
  12579. this._gl.clearStencil(0);
  12580. mode |= this._gl.STENCIL_BUFFER_BIT;
  12581. }
  12582. this._gl.clear(mode);
  12583. };
  12584. /**
  12585. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12586. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12587. * @param y defines the y-coordinate of the corner of the clear rectangle
  12588. * @param width defines the width of the clear rectangle
  12589. * @param height defines the height of the clear rectangle
  12590. * @param clearColor defines the clear color
  12591. */
  12592. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12593. var gl = this._gl;
  12594. // Save state
  12595. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12596. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12597. // Change state
  12598. gl.enable(gl.SCISSOR_TEST);
  12599. gl.scissor(x, y, width, height);
  12600. // Clear
  12601. this.clear(clearColor, true, true, true);
  12602. // Restore state
  12603. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12604. if (curScissor === true) {
  12605. gl.enable(gl.SCISSOR_TEST);
  12606. }
  12607. else {
  12608. gl.disable(gl.SCISSOR_TEST);
  12609. }
  12610. };
  12611. /** @hidden */
  12612. Engine.prototype._viewport = function (x, y, width, height) {
  12613. if (x !== this._viewportCached.x ||
  12614. y !== this._viewportCached.y ||
  12615. width !== this._viewportCached.z ||
  12616. height !== this._viewportCached.w) {
  12617. this._viewportCached.x = x;
  12618. this._viewportCached.y = y;
  12619. this._viewportCached.z = width;
  12620. this._viewportCached.w = height;
  12621. this._gl.viewport(x, y, width, height);
  12622. }
  12623. };
  12624. /**
  12625. * Set the WebGL's viewport
  12626. * @param viewport defines the viewport element to be used
  12627. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12628. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12629. */
  12630. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12631. var width = requiredWidth || this.getRenderWidth();
  12632. var height = requiredHeight || this.getRenderHeight();
  12633. var x = viewport.x || 0;
  12634. var y = viewport.y || 0;
  12635. this._cachedViewport = viewport;
  12636. this._viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12637. };
  12638. /**
  12639. * Directly set the WebGL Viewport
  12640. * @param x defines the x coordinate of the viewport (in screen space)
  12641. * @param y defines the y coordinate of the viewport (in screen space)
  12642. * @param width defines the width of the viewport (in screen space)
  12643. * @param height defines the height of the viewport (in screen space)
  12644. * @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
  12645. */
  12646. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12647. var currentViewport = this._cachedViewport;
  12648. this._cachedViewport = null;
  12649. this._viewport(x, y, width, height);
  12650. return currentViewport;
  12651. };
  12652. /**
  12653. * Begin a new frame
  12654. */
  12655. Engine.prototype.beginFrame = function () {
  12656. this.onBeginFrameObservable.notifyObservers(this);
  12657. this._measureFps();
  12658. };
  12659. /**
  12660. * Enf the current frame
  12661. */
  12662. Engine.prototype.endFrame = function () {
  12663. // Force a flush in case we are using a bad OS.
  12664. if (this._badOS) {
  12665. this.flushFramebuffer();
  12666. }
  12667. // Submit frame to the vr device, if enabled
  12668. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12669. // TODO: We should only submit the frame if we read frameData successfully.
  12670. this._vrDisplay.submitFrame();
  12671. }
  12672. this.onEndFrameObservable.notifyObservers(this);
  12673. };
  12674. /**
  12675. * Resize the view according to the canvas' size
  12676. */
  12677. Engine.prototype.resize = function () {
  12678. // We're not resizing the size of the canvas while in VR mode & presenting
  12679. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12680. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12681. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12682. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12683. }
  12684. };
  12685. /**
  12686. * Force a specific size of the canvas
  12687. * @param width defines the new canvas' width
  12688. * @param height defines the new canvas' height
  12689. */
  12690. Engine.prototype.setSize = function (width, height) {
  12691. if (!this._renderingCanvas) {
  12692. return;
  12693. }
  12694. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12695. return;
  12696. }
  12697. this._renderingCanvas.width = width;
  12698. this._renderingCanvas.height = height;
  12699. for (var index = 0; index < this.scenes.length; index++) {
  12700. var scene = this.scenes[index];
  12701. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12702. var cam = scene.cameras[camIndex];
  12703. cam._currentRenderId = 0;
  12704. }
  12705. }
  12706. if (this.onResizeObservable.hasObservers) {
  12707. this.onResizeObservable.notifyObservers(this);
  12708. }
  12709. };
  12710. // WebVR functions
  12711. /**
  12712. * Gets a boolean indicating if a webVR device was detected
  12713. * @returns true if a webVR device was detected
  12714. */
  12715. Engine.prototype.isVRDevicePresent = function () {
  12716. return !!this._vrDisplay;
  12717. };
  12718. /**
  12719. * Gets the current webVR device
  12720. * @returns the current webVR device (or null)
  12721. */
  12722. Engine.prototype.getVRDevice = function () {
  12723. return this._vrDisplay;
  12724. };
  12725. /**
  12726. * Initializes a webVR display and starts listening to display change events
  12727. * The onVRDisplayChangedObservable will be notified upon these changes
  12728. * @returns The onVRDisplayChangedObservable
  12729. */
  12730. Engine.prototype.initWebVR = function () {
  12731. this.initWebVRAsync();
  12732. return this.onVRDisplayChangedObservable;
  12733. };
  12734. /**
  12735. * Initializes a webVR display and starts listening to display change events
  12736. * The onVRDisplayChangedObservable will be notified upon these changes
  12737. * @returns A promise containing a VRDisplay and if vr is supported
  12738. */
  12739. Engine.prototype.initWebVRAsync = function () {
  12740. var _this = this;
  12741. var notifyObservers = function () {
  12742. var eventArgs = {
  12743. vrDisplay: _this._vrDisplay,
  12744. vrSupported: _this._vrSupported
  12745. };
  12746. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  12747. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  12748. };
  12749. if (!this._onVrDisplayConnect) {
  12750. this._onVrDisplayConnect = function (event) {
  12751. _this._vrDisplay = event.display;
  12752. notifyObservers();
  12753. };
  12754. this._onVrDisplayDisconnect = function () {
  12755. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  12756. _this._vrDisplay = undefined;
  12757. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  12758. notifyObservers();
  12759. };
  12760. this._onVrDisplayPresentChange = function () {
  12761. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  12762. };
  12763. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12764. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12765. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12766. }
  12767. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  12768. this._webVRInitPromise.then(notifyObservers);
  12769. return this._webVRInitPromise;
  12770. };
  12771. /**
  12772. * Call this function to switch to webVR mode
  12773. * Will do nothing if webVR is not supported or if there is no webVR device
  12774. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12775. */
  12776. Engine.prototype.enableVR = function () {
  12777. var _this = this;
  12778. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  12779. var onResolved = function () {
  12780. _this.onVRRequestPresentComplete.notifyObservers(true);
  12781. _this._onVRFullScreenTriggered();
  12782. };
  12783. var onRejected = function () {
  12784. _this.onVRRequestPresentComplete.notifyObservers(false);
  12785. };
  12786. this.onVRRequestPresentStart.notifyObservers(this);
  12787. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  12788. }
  12789. };
  12790. /**
  12791. * Call this function to leave webVR mode
  12792. * Will do nothing if webVR is not supported or if there is no webVR device
  12793. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12794. */
  12795. Engine.prototype.disableVR = function () {
  12796. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12797. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  12798. }
  12799. };
  12800. Engine.prototype._getVRDisplaysAsync = function () {
  12801. var _this = this;
  12802. return new Promise(function (res, rej) {
  12803. if (navigator.getVRDisplays) {
  12804. navigator.getVRDisplays().then(function (devices) {
  12805. _this._vrSupported = true;
  12806. // note that devices may actually be an empty array. This is fine;
  12807. // we expect this._vrDisplay to be undefined in this case.
  12808. _this._vrDisplay = devices[0];
  12809. res({
  12810. vrDisplay: _this._vrDisplay,
  12811. vrSupported: _this._vrSupported
  12812. });
  12813. });
  12814. }
  12815. else {
  12816. _this._vrDisplay = undefined;
  12817. _this._vrSupported = false;
  12818. res({
  12819. vrDisplay: _this._vrDisplay,
  12820. vrSupported: _this._vrSupported
  12821. });
  12822. }
  12823. });
  12824. };
  12825. /**
  12826. * Binds the frame buffer to the specified texture.
  12827. * @param texture The texture to render to or null for the default canvas
  12828. * @param faceIndex The face of the texture to render to in case of cube texture
  12829. * @param requiredWidth The width of the target to render to
  12830. * @param requiredHeight The height of the target to render to
  12831. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  12832. * @param depthStencilTexture The depth stencil texture to use to render
  12833. * @param lodLevel defines le lod level to bind to the frame buffer
  12834. */
  12835. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) {
  12836. if (lodLevel === void 0) { lodLevel = 0; }
  12837. if (this._currentRenderTarget) {
  12838. this.unBindFramebuffer(this._currentRenderTarget);
  12839. }
  12840. this._currentRenderTarget = texture;
  12841. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  12842. var gl = this._gl;
  12843. if (texture.isCube) {
  12844. if (faceIndex === undefined) {
  12845. faceIndex = 0;
  12846. }
  12847. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  12848. if (depthStencilTexture) {
  12849. if (depthStencilTexture._generateStencilBuffer) {
  12850. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  12851. }
  12852. else {
  12853. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  12854. }
  12855. }
  12856. }
  12857. if (this._cachedViewport && !forceFullscreenViewport) {
  12858. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  12859. }
  12860. else {
  12861. if (!requiredWidth) {
  12862. requiredWidth = texture.width;
  12863. if (lodLevel) {
  12864. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  12865. }
  12866. }
  12867. if (!requiredHeight) {
  12868. requiredHeight = texture.height;
  12869. if (lodLevel) {
  12870. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  12871. }
  12872. }
  12873. this._viewport(0, 0, requiredWidth, requiredHeight);
  12874. }
  12875. this.wipeCaches();
  12876. };
  12877. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  12878. if (this._currentFramebuffer !== framebuffer) {
  12879. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  12880. this._currentFramebuffer = framebuffer;
  12881. }
  12882. };
  12883. /**
  12884. * Unbind the current render target texture from the webGL context
  12885. * @param texture defines the render target texture to unbind
  12886. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12887. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12888. */
  12889. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  12890. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12891. this._currentRenderTarget = null;
  12892. // If MSAA, we need to bitblt back to main texture
  12893. var gl = this._gl;
  12894. if (texture._MSAAFramebuffer) {
  12895. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  12896. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  12897. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12898. }
  12899. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12900. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12901. gl.generateMipmap(gl.TEXTURE_2D);
  12902. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12903. }
  12904. if (onBeforeUnbind) {
  12905. if (texture._MSAAFramebuffer) {
  12906. // Bind the correct framebuffer
  12907. this.bindUnboundFramebuffer(texture._framebuffer);
  12908. }
  12909. onBeforeUnbind();
  12910. }
  12911. this.bindUnboundFramebuffer(null);
  12912. };
  12913. /**
  12914. * Unbind a list of render target textures from the webGL context
  12915. * This is used only when drawBuffer extension or webGL2 are active
  12916. * @param textures defines the render target textures to unbind
  12917. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12918. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12919. */
  12920. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  12921. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12922. this._currentRenderTarget = null;
  12923. // If MSAA, we need to bitblt back to main texture
  12924. var gl = this._gl;
  12925. if (textures[0]._MSAAFramebuffer) {
  12926. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  12927. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  12928. var attachments = textures[0]._attachments;
  12929. if (!attachments) {
  12930. attachments = new Array(textures.length);
  12931. textures[0]._attachments = attachments;
  12932. }
  12933. for (var i = 0; i < textures.length; i++) {
  12934. var texture = textures[i];
  12935. for (var j = 0; j < attachments.length; j++) {
  12936. attachments[j] = gl.NONE;
  12937. }
  12938. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12939. gl.readBuffer(attachments[i]);
  12940. gl.drawBuffers(attachments);
  12941. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12942. }
  12943. for (var i = 0; i < attachments.length; i++) {
  12944. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12945. }
  12946. gl.drawBuffers(attachments);
  12947. }
  12948. for (var i = 0; i < textures.length; i++) {
  12949. var texture = textures[i];
  12950. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12951. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  12952. gl.generateMipmap(gl.TEXTURE_2D);
  12953. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12954. }
  12955. }
  12956. if (onBeforeUnbind) {
  12957. if (textures[0]._MSAAFramebuffer) {
  12958. // Bind the correct framebuffer
  12959. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12960. }
  12961. onBeforeUnbind();
  12962. }
  12963. this.bindUnboundFramebuffer(null);
  12964. };
  12965. /**
  12966. * Force the mipmap generation for the given render target texture
  12967. * @param texture defines the render target texture to use
  12968. */
  12969. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  12970. if (texture.generateMipMaps) {
  12971. var gl = this._gl;
  12972. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12973. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12974. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12975. }
  12976. };
  12977. /**
  12978. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  12979. */
  12980. Engine.prototype.flushFramebuffer = function () {
  12981. this._gl.flush();
  12982. };
  12983. /**
  12984. * Unbind the current render target and bind the default framebuffer
  12985. */
  12986. Engine.prototype.restoreDefaultFramebuffer = function () {
  12987. if (this._currentRenderTarget) {
  12988. this.unBindFramebuffer(this._currentRenderTarget);
  12989. }
  12990. else {
  12991. this.bindUnboundFramebuffer(null);
  12992. }
  12993. if (this._cachedViewport) {
  12994. this.setViewport(this._cachedViewport);
  12995. }
  12996. this.wipeCaches();
  12997. };
  12998. // UBOs
  12999. /**
  13000. * Create an uniform buffer
  13001. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13002. * @param elements defines the content of the uniform buffer
  13003. * @returns the webGL uniform buffer
  13004. */
  13005. Engine.prototype.createUniformBuffer = function (elements) {
  13006. var ubo = this._gl.createBuffer();
  13007. if (!ubo) {
  13008. throw new Error("Unable to create uniform buffer");
  13009. }
  13010. this.bindUniformBuffer(ubo);
  13011. if (elements instanceof Float32Array) {
  13012. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  13013. }
  13014. else {
  13015. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  13016. }
  13017. this.bindUniformBuffer(null);
  13018. ubo.references = 1;
  13019. return ubo;
  13020. };
  13021. /**
  13022. * Create a dynamic uniform buffer
  13023. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13024. * @param elements defines the content of the uniform buffer
  13025. * @returns the webGL uniform buffer
  13026. */
  13027. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  13028. var ubo = this._gl.createBuffer();
  13029. if (!ubo) {
  13030. throw new Error("Unable to create dynamic uniform buffer");
  13031. }
  13032. this.bindUniformBuffer(ubo);
  13033. if (elements instanceof Float32Array) {
  13034. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  13035. }
  13036. else {
  13037. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  13038. }
  13039. this.bindUniformBuffer(null);
  13040. ubo.references = 1;
  13041. return ubo;
  13042. };
  13043. /**
  13044. * Update an existing uniform buffer
  13045. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13046. * @param uniformBuffer defines the target uniform buffer
  13047. * @param elements defines the content to update
  13048. * @param offset defines the offset in the uniform buffer where update should start
  13049. * @param count defines the size of the data to update
  13050. */
  13051. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13052. this.bindUniformBuffer(uniformBuffer);
  13053. if (offset === undefined) {
  13054. offset = 0;
  13055. }
  13056. if (count === undefined) {
  13057. if (elements instanceof Float32Array) {
  13058. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13059. }
  13060. else {
  13061. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13062. }
  13063. }
  13064. else {
  13065. if (elements instanceof Float32Array) {
  13066. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13067. }
  13068. else {
  13069. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13070. }
  13071. }
  13072. this.bindUniformBuffer(null);
  13073. };
  13074. // VBOs
  13075. Engine.prototype._resetVertexBufferBinding = function () {
  13076. this.bindArrayBuffer(null);
  13077. this._cachedVertexBuffers = null;
  13078. };
  13079. /**
  13080. * Creates a vertex buffer
  13081. * @param data the data for the vertex buffer
  13082. * @returns the new WebGL static buffer
  13083. */
  13084. Engine.prototype.createVertexBuffer = function (data) {
  13085. var vbo = this._gl.createBuffer();
  13086. if (!vbo) {
  13087. throw new Error("Unable to create vertex buffer");
  13088. }
  13089. this.bindArrayBuffer(vbo);
  13090. if (data instanceof Array) {
  13091. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13092. }
  13093. else {
  13094. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13095. }
  13096. this._resetVertexBufferBinding();
  13097. vbo.references = 1;
  13098. return vbo;
  13099. };
  13100. /**
  13101. * Creates a dynamic vertex buffer
  13102. * @param data the data for the dynamic vertex buffer
  13103. * @returns the new WebGL dynamic buffer
  13104. */
  13105. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13106. var vbo = this._gl.createBuffer();
  13107. if (!vbo) {
  13108. throw new Error("Unable to create dynamic vertex buffer");
  13109. }
  13110. this.bindArrayBuffer(vbo);
  13111. if (data instanceof Array) {
  13112. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13113. }
  13114. else {
  13115. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13116. }
  13117. this._resetVertexBufferBinding();
  13118. vbo.references = 1;
  13119. return vbo;
  13120. };
  13121. /**
  13122. * Update a dynamic index buffer
  13123. * @param indexBuffer defines the target index buffer
  13124. * @param indices defines the data to update
  13125. * @param offset defines the offset in the target index buffer where update should start
  13126. */
  13127. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13128. if (offset === void 0) { offset = 0; }
  13129. // Force cache update
  13130. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13131. this.bindIndexBuffer(indexBuffer);
  13132. var arrayBuffer;
  13133. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13134. arrayBuffer = indices;
  13135. }
  13136. else {
  13137. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13138. }
  13139. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13140. this._resetIndexBufferBinding();
  13141. };
  13142. /**
  13143. * Updates a dynamic vertex buffer.
  13144. * @param vertexBuffer the vertex buffer to update
  13145. * @param data the data used to update the vertex buffer
  13146. * @param byteOffset the byte offset of the data
  13147. * @param byteLength the byte length of the data
  13148. */
  13149. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13150. this.bindArrayBuffer(vertexBuffer);
  13151. if (byteOffset === undefined) {
  13152. byteOffset = 0;
  13153. }
  13154. if (byteLength === undefined) {
  13155. if (data instanceof Array) {
  13156. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13157. }
  13158. else {
  13159. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13160. }
  13161. }
  13162. else {
  13163. if (data instanceof Array) {
  13164. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13165. }
  13166. else {
  13167. if (data instanceof ArrayBuffer) {
  13168. data = new Uint8Array(data, byteOffset, byteLength);
  13169. }
  13170. else {
  13171. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13172. }
  13173. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13174. }
  13175. }
  13176. this._resetVertexBufferBinding();
  13177. };
  13178. Engine.prototype._resetIndexBufferBinding = function () {
  13179. this.bindIndexBuffer(null);
  13180. this._cachedIndexBuffer = null;
  13181. };
  13182. /**
  13183. * Creates a new index buffer
  13184. * @param indices defines the content of the index buffer
  13185. * @param updatable defines if the index buffer must be updatable
  13186. * @returns a new webGL buffer
  13187. */
  13188. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13189. var vbo = this._gl.createBuffer();
  13190. if (!vbo) {
  13191. throw new Error("Unable to create index buffer");
  13192. }
  13193. this.bindIndexBuffer(vbo);
  13194. // Check for 32 bits indices
  13195. var arrayBuffer;
  13196. var need32Bits = false;
  13197. if (indices instanceof Uint16Array) {
  13198. arrayBuffer = indices;
  13199. }
  13200. else {
  13201. //check 32 bit support
  13202. if (this._caps.uintIndices) {
  13203. if (indices instanceof Uint32Array) {
  13204. arrayBuffer = indices;
  13205. need32Bits = true;
  13206. }
  13207. else {
  13208. //number[] or Int32Array, check if 32 bit is necessary
  13209. for (var index = 0; index < indices.length; index++) {
  13210. if (indices[index] > 65535) {
  13211. need32Bits = true;
  13212. break;
  13213. }
  13214. }
  13215. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13216. }
  13217. }
  13218. else {
  13219. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13220. arrayBuffer = new Uint16Array(indices);
  13221. }
  13222. }
  13223. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13224. this._resetIndexBufferBinding();
  13225. vbo.references = 1;
  13226. vbo.is32Bits = need32Bits;
  13227. return vbo;
  13228. };
  13229. /**
  13230. * Bind a webGL buffer to the webGL context
  13231. * @param buffer defines the buffer to bind
  13232. */
  13233. Engine.prototype.bindArrayBuffer = function (buffer) {
  13234. if (!this._vaoRecordInProgress) {
  13235. this._unbindVertexArrayObject();
  13236. }
  13237. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13238. };
  13239. /**
  13240. * Bind an uniform buffer to the current webGL context
  13241. * @param buffer defines the buffer to bind
  13242. */
  13243. Engine.prototype.bindUniformBuffer = function (buffer) {
  13244. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13245. };
  13246. /**
  13247. * Bind a buffer to the current webGL context at a given location
  13248. * @param buffer defines the buffer to bind
  13249. * @param location defines the index where to bind the buffer
  13250. */
  13251. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13252. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13253. };
  13254. /**
  13255. * Bind a specific block at a given index in a specific shader program
  13256. * @param shaderProgram defines the shader program
  13257. * @param blockName defines the block name
  13258. * @param index defines the index where to bind the block
  13259. */
  13260. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13261. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13262. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13263. };
  13264. ;
  13265. Engine.prototype.bindIndexBuffer = function (buffer) {
  13266. if (!this._vaoRecordInProgress) {
  13267. this._unbindVertexArrayObject();
  13268. }
  13269. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13270. };
  13271. Engine.prototype.bindBuffer = function (buffer, target) {
  13272. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13273. this._gl.bindBuffer(target, buffer);
  13274. this._currentBoundBuffer[target] = buffer;
  13275. }
  13276. };
  13277. /**
  13278. * update the bound buffer with the given data
  13279. * @param data defines the data to update
  13280. */
  13281. Engine.prototype.updateArrayBuffer = function (data) {
  13282. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13283. };
  13284. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13285. var pointer = this._currentBufferPointers[indx];
  13286. var changed = false;
  13287. if (!pointer.active) {
  13288. changed = true;
  13289. pointer.active = true;
  13290. pointer.index = indx;
  13291. pointer.size = size;
  13292. pointer.type = type;
  13293. pointer.normalized = normalized;
  13294. pointer.stride = stride;
  13295. pointer.offset = offset;
  13296. pointer.buffer = buffer;
  13297. }
  13298. else {
  13299. if (pointer.buffer !== buffer) {
  13300. pointer.buffer = buffer;
  13301. changed = true;
  13302. }
  13303. if (pointer.size !== size) {
  13304. pointer.size = size;
  13305. changed = true;
  13306. }
  13307. if (pointer.type !== type) {
  13308. pointer.type = type;
  13309. changed = true;
  13310. }
  13311. if (pointer.normalized !== normalized) {
  13312. pointer.normalized = normalized;
  13313. changed = true;
  13314. }
  13315. if (pointer.stride !== stride) {
  13316. pointer.stride = stride;
  13317. changed = true;
  13318. }
  13319. if (pointer.offset !== offset) {
  13320. pointer.offset = offset;
  13321. changed = true;
  13322. }
  13323. }
  13324. if (changed || this._vaoRecordInProgress) {
  13325. this.bindArrayBuffer(buffer);
  13326. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13327. }
  13328. };
  13329. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13330. if (indexBuffer == null) {
  13331. return;
  13332. }
  13333. if (this._cachedIndexBuffer !== indexBuffer) {
  13334. this._cachedIndexBuffer = indexBuffer;
  13335. this.bindIndexBuffer(indexBuffer);
  13336. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13337. }
  13338. };
  13339. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13340. var attributes = effect.getAttributesNames();
  13341. if (!this._vaoRecordInProgress) {
  13342. this._unbindVertexArrayObject();
  13343. }
  13344. this.unbindAllAttributes();
  13345. for (var index = 0; index < attributes.length; index++) {
  13346. var order = effect.getAttributeLocation(index);
  13347. if (order >= 0) {
  13348. var vertexBuffer = vertexBuffers[attributes[index]];
  13349. if (!vertexBuffer) {
  13350. continue;
  13351. }
  13352. this._gl.enableVertexAttribArray(order);
  13353. if (!this._vaoRecordInProgress) {
  13354. this._vertexAttribArraysEnabled[order] = true;
  13355. }
  13356. var buffer = vertexBuffer.getBuffer();
  13357. if (buffer) {
  13358. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13359. if (vertexBuffer.getIsInstanced()) {
  13360. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13361. if (!this._vaoRecordInProgress) {
  13362. this._currentInstanceLocations.push(order);
  13363. this._currentInstanceBuffers.push(buffer);
  13364. }
  13365. }
  13366. }
  13367. }
  13368. }
  13369. };
  13370. /**
  13371. * Records a vertex array object
  13372. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13373. * @param vertexBuffers defines the list of vertex buffers to store
  13374. * @param indexBuffer defines the index buffer to store
  13375. * @param effect defines the effect to store
  13376. * @returns the new vertex array object
  13377. */
  13378. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13379. var vao = this._gl.createVertexArray();
  13380. this._vaoRecordInProgress = true;
  13381. this._gl.bindVertexArray(vao);
  13382. this._mustWipeVertexAttributes = true;
  13383. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13384. this.bindIndexBuffer(indexBuffer);
  13385. this._vaoRecordInProgress = false;
  13386. this._gl.bindVertexArray(null);
  13387. return vao;
  13388. };
  13389. /**
  13390. * Bind a specific vertex array object
  13391. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13392. * @param vertexArrayObject defines the vertex array object to bind
  13393. * @param indexBuffer defines the index buffer to bind
  13394. */
  13395. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13396. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13397. this._cachedVertexArrayObject = vertexArrayObject;
  13398. this._gl.bindVertexArray(vertexArrayObject);
  13399. this._cachedVertexBuffers = null;
  13400. this._cachedIndexBuffer = null;
  13401. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13402. this._mustWipeVertexAttributes = true;
  13403. }
  13404. };
  13405. /**
  13406. * Bind webGl buffers directly to the webGL context
  13407. * @param vertexBuffer defines the vertex buffer to bind
  13408. * @param indexBuffer defines the index buffer to bind
  13409. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13410. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13411. * @param effect defines the effect associated with the vertex buffer
  13412. */
  13413. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13414. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13415. this._cachedVertexBuffers = vertexBuffer;
  13416. this._cachedEffectForVertexBuffers = effect;
  13417. var attributesCount = effect.getAttributesCount();
  13418. this._unbindVertexArrayObject();
  13419. this.unbindAllAttributes();
  13420. var offset = 0;
  13421. for (var index = 0; index < attributesCount; index++) {
  13422. if (index < vertexDeclaration.length) {
  13423. var order = effect.getAttributeLocation(index);
  13424. if (order >= 0) {
  13425. this._gl.enableVertexAttribArray(order);
  13426. this._vertexAttribArraysEnabled[order] = true;
  13427. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13428. }
  13429. offset += vertexDeclaration[index] * 4;
  13430. }
  13431. }
  13432. }
  13433. this._bindIndexBufferWithCache(indexBuffer);
  13434. };
  13435. Engine.prototype._unbindVertexArrayObject = function () {
  13436. if (!this._cachedVertexArrayObject) {
  13437. return;
  13438. }
  13439. this._cachedVertexArrayObject = null;
  13440. this._gl.bindVertexArray(null);
  13441. };
  13442. /**
  13443. * Bind a list of vertex buffers to the webGL context
  13444. * @param vertexBuffers defines the list of vertex buffers to bind
  13445. * @param indexBuffer defines the index buffer to bind
  13446. * @param effect defines the effect associated with the vertex buffers
  13447. */
  13448. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13449. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13450. this._cachedVertexBuffers = vertexBuffers;
  13451. this._cachedEffectForVertexBuffers = effect;
  13452. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13453. }
  13454. this._bindIndexBufferWithCache(indexBuffer);
  13455. };
  13456. /**
  13457. * Unbind all instance attributes
  13458. */
  13459. Engine.prototype.unbindInstanceAttributes = function () {
  13460. var boundBuffer;
  13461. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13462. var instancesBuffer = this._currentInstanceBuffers[i];
  13463. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13464. boundBuffer = instancesBuffer;
  13465. this.bindArrayBuffer(instancesBuffer);
  13466. }
  13467. var offsetLocation = this._currentInstanceLocations[i];
  13468. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13469. }
  13470. this._currentInstanceBuffers.length = 0;
  13471. this._currentInstanceLocations.length = 0;
  13472. };
  13473. /**
  13474. * Release and free the memory of a vertex array object
  13475. * @param vao defines the vertex array object to delete
  13476. */
  13477. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13478. this._gl.deleteVertexArray(vao);
  13479. };
  13480. /** @hidden */
  13481. Engine.prototype._releaseBuffer = function (buffer) {
  13482. buffer.references--;
  13483. if (buffer.references === 0) {
  13484. this._gl.deleteBuffer(buffer);
  13485. return true;
  13486. }
  13487. return false;
  13488. };
  13489. /**
  13490. * Creates a webGL buffer to use with instanciation
  13491. * @param capacity defines the size of the buffer
  13492. * @returns the webGL buffer
  13493. */
  13494. Engine.prototype.createInstancesBuffer = function (capacity) {
  13495. var buffer = this._gl.createBuffer();
  13496. if (!buffer) {
  13497. throw new Error("Unable to create instance buffer");
  13498. }
  13499. buffer.capacity = capacity;
  13500. this.bindArrayBuffer(buffer);
  13501. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13502. return buffer;
  13503. };
  13504. /**
  13505. * Delete a webGL buffer used with instanciation
  13506. * @param buffer defines the webGL buffer to delete
  13507. */
  13508. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13509. this._gl.deleteBuffer(buffer);
  13510. };
  13511. /**
  13512. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13513. * @param instancesBuffer defines the webGL buffer to update and bind
  13514. * @param data defines the data to store in the buffer
  13515. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13516. */
  13517. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13518. this.bindArrayBuffer(instancesBuffer);
  13519. if (data) {
  13520. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13521. }
  13522. if (offsetLocations[0].index !== undefined) {
  13523. var stride = 0;
  13524. for (var i = 0; i < offsetLocations.length; i++) {
  13525. var ai = offsetLocations[i];
  13526. stride += ai.attributeSize * 4;
  13527. }
  13528. for (var i = 0; i < offsetLocations.length; i++) {
  13529. var ai = offsetLocations[i];
  13530. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13531. this._gl.enableVertexAttribArray(ai.index);
  13532. this._vertexAttribArraysEnabled[ai.index] = true;
  13533. }
  13534. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13535. this._gl.vertexAttribDivisor(ai.index, 1);
  13536. this._currentInstanceLocations.push(ai.index);
  13537. this._currentInstanceBuffers.push(instancesBuffer);
  13538. }
  13539. }
  13540. else {
  13541. for (var index = 0; index < 4; index++) {
  13542. var offsetLocation = offsetLocations[index];
  13543. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13544. this._gl.enableVertexAttribArray(offsetLocation);
  13545. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13546. }
  13547. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13548. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13549. this._currentInstanceLocations.push(offsetLocation);
  13550. this._currentInstanceBuffers.push(instancesBuffer);
  13551. }
  13552. }
  13553. };
  13554. /**
  13555. * Apply all cached states (depth, culling, stencil and alpha)
  13556. */
  13557. Engine.prototype.applyStates = function () {
  13558. this._depthCullingState.apply(this._gl);
  13559. this._stencilState.apply(this._gl);
  13560. this._alphaState.apply(this._gl);
  13561. };
  13562. /**
  13563. * Send a draw order
  13564. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13565. * @param indexStart defines the starting index
  13566. * @param indexCount defines the number of index to draw
  13567. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13568. */
  13569. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13570. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13571. };
  13572. /**
  13573. * Draw a list of points
  13574. * @param verticesStart defines the index of first vertex to draw
  13575. * @param verticesCount defines the count of vertices to draw
  13576. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13577. */
  13578. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13579. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13580. };
  13581. /**
  13582. * Draw a list of unindexed primitives
  13583. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13584. * @param verticesStart defines the index of first vertex to draw
  13585. * @param verticesCount defines the count of vertices to draw
  13586. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13587. */
  13588. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13589. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13590. };
  13591. /**
  13592. * Draw a list of indexed primitives
  13593. * @param fillMode defines the primitive to use
  13594. * @param indexStart defines the starting index
  13595. * @param indexCount defines the number of index to draw
  13596. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13597. */
  13598. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13599. // Apply states
  13600. this.applyStates();
  13601. this._drawCalls.addCount(1, false);
  13602. // Render
  13603. var drawMode = this._drawMode(fillMode);
  13604. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13605. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13606. if (instancesCount) {
  13607. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13608. }
  13609. else {
  13610. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13611. }
  13612. };
  13613. /**
  13614. * Draw a list of unindexed primitives
  13615. * @param fillMode defines the primitive to use
  13616. * @param verticesStart defines the index of first vertex to draw
  13617. * @param verticesCount defines the count of vertices to draw
  13618. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13619. */
  13620. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13621. // Apply states
  13622. this.applyStates();
  13623. this._drawCalls.addCount(1, false);
  13624. var drawMode = this._drawMode(fillMode);
  13625. if (instancesCount) {
  13626. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13627. }
  13628. else {
  13629. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13630. }
  13631. };
  13632. Engine.prototype._drawMode = function (fillMode) {
  13633. switch (fillMode) {
  13634. // Triangle views
  13635. case BABYLON.Material.TriangleFillMode:
  13636. return this._gl.TRIANGLES;
  13637. case BABYLON.Material.PointFillMode:
  13638. return this._gl.POINTS;
  13639. case BABYLON.Material.WireFrameFillMode:
  13640. return this._gl.LINES;
  13641. // Draw modes
  13642. case BABYLON.Material.PointListDrawMode:
  13643. return this._gl.POINTS;
  13644. case BABYLON.Material.LineListDrawMode:
  13645. return this._gl.LINES;
  13646. case BABYLON.Material.LineLoopDrawMode:
  13647. return this._gl.LINE_LOOP;
  13648. case BABYLON.Material.LineStripDrawMode:
  13649. return this._gl.LINE_STRIP;
  13650. case BABYLON.Material.TriangleStripDrawMode:
  13651. return this._gl.TRIANGLE_STRIP;
  13652. case BABYLON.Material.TriangleFanDrawMode:
  13653. return this._gl.TRIANGLE_FAN;
  13654. default:
  13655. return this._gl.TRIANGLES;
  13656. }
  13657. };
  13658. // Shaders
  13659. /** @hidden */
  13660. Engine.prototype._releaseEffect = function (effect) {
  13661. if (this._compiledEffects[effect._key]) {
  13662. delete this._compiledEffects[effect._key];
  13663. this._deleteProgram(effect.getProgram());
  13664. }
  13665. };
  13666. /** @hidden */
  13667. Engine.prototype._deleteProgram = function (program) {
  13668. if (program) {
  13669. program.__SPECTOR_rebuildProgram = null;
  13670. if (program.transformFeedback) {
  13671. this.deleteTransformFeedback(program.transformFeedback);
  13672. program.transformFeedback = null;
  13673. }
  13674. this._gl.deleteProgram(program);
  13675. }
  13676. };
  13677. /**
  13678. * Create a new effect (used to store vertex/fragment shaders)
  13679. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13680. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13681. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13682. * @param samplers defines an array of string used to represent textures
  13683. * @param defines defines the string containing the defines to use to compile the shaders
  13684. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13685. * @param onCompiled defines a function to call when the effect creation is successful
  13686. * @param onError defines a function to call when the effect creation has failed
  13687. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13688. * @returns the new Effect
  13689. */
  13690. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13691. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  13692. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  13693. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  13694. if (this._compiledEffects[name]) {
  13695. var compiledEffect = this._compiledEffects[name];
  13696. if (onCompiled && compiledEffect.isReady()) {
  13697. onCompiled(compiledEffect);
  13698. }
  13699. return compiledEffect;
  13700. }
  13701. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  13702. effect._key = name;
  13703. this._compiledEffects[name] = effect;
  13704. return effect;
  13705. };
  13706. Engine.prototype._compileShader = function (source, type, defines, shaderVersion) {
  13707. return this._compileRawShader(shaderVersion + (defines ? defines + "\n" : "") + source, type);
  13708. };
  13709. ;
  13710. Engine.prototype._compileRawShader = function (source, type) {
  13711. var gl = this._gl;
  13712. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  13713. gl.shaderSource(shader, source);
  13714. gl.compileShader(shader);
  13715. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  13716. var log = gl.getShaderInfoLog(shader);
  13717. if (log) {
  13718. throw new Error(log);
  13719. }
  13720. }
  13721. if (!shader) {
  13722. throw new Error("Something went wrong while compile the shader.");
  13723. }
  13724. return shader;
  13725. };
  13726. ;
  13727. /**
  13728. * Directly creates a webGL program
  13729. * @param vertexCode defines the vertex shader code to use
  13730. * @param fragmentCode defines the fragment shader code to use
  13731. * @param context defines the webGL context to use (if not set, the current one will be used)
  13732. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13733. * @returns the new webGL program
  13734. */
  13735. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  13736. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13737. context = context || this._gl;
  13738. var vertexShader = this._compileRawShader(vertexCode, "vertex");
  13739. var fragmentShader = this._compileRawShader(fragmentCode, "fragment");
  13740. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13741. };
  13742. /**
  13743. * Creates a webGL program
  13744. * @param vertexCode defines the vertex shader code to use
  13745. * @param fragmentCode defines the fragment shader code to use
  13746. * @param defines defines the string containing the defines to use to compile the shaders
  13747. * @param context defines the webGL context to use (if not set, the current one will be used)
  13748. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13749. * @returns the new webGL program
  13750. */
  13751. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  13752. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13753. context = context || this._gl;
  13754. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  13755. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  13756. var vertexShader = this._compileShader(vertexCode, "vertex", defines, shaderVersion);
  13757. var fragmentShader = this._compileShader(fragmentCode, "fragment", defines, shaderVersion);
  13758. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13759. this.onAfterShaderCompilationObservable.notifyObservers(this);
  13760. return program;
  13761. };
  13762. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  13763. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13764. var shaderProgram = context.createProgram();
  13765. if (!shaderProgram) {
  13766. throw new Error("Unable to create program");
  13767. }
  13768. context.attachShader(shaderProgram, vertexShader);
  13769. context.attachShader(shaderProgram, fragmentShader);
  13770. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13771. var transformFeedback = this.createTransformFeedback();
  13772. this.bindTransformFeedback(transformFeedback);
  13773. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  13774. shaderProgram.transformFeedback = transformFeedback;
  13775. }
  13776. context.linkProgram(shaderProgram);
  13777. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13778. this.bindTransformFeedback(null);
  13779. }
  13780. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  13781. if (!linked) {
  13782. var error = context.getProgramInfoLog(shaderProgram);
  13783. if (error) {
  13784. throw new Error(error);
  13785. }
  13786. }
  13787. if (this.validateShaderPrograms) {
  13788. context.validateProgram(shaderProgram);
  13789. var validated = context.getProgramParameter(shaderProgram, context.VALIDATE_STATUS);
  13790. if (!validated) {
  13791. var error = context.getProgramInfoLog(shaderProgram);
  13792. if (error) {
  13793. throw new Error(error);
  13794. }
  13795. }
  13796. }
  13797. context.deleteShader(vertexShader);
  13798. context.deleteShader(fragmentShader);
  13799. return shaderProgram;
  13800. };
  13801. /**
  13802. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  13803. * @param shaderProgram defines the webGL program to use
  13804. * @param uniformsNames defines the list of uniform names
  13805. * @returns an array of webGL uniform locations
  13806. */
  13807. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  13808. var results = new Array();
  13809. for (var index = 0; index < uniformsNames.length; index++) {
  13810. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  13811. }
  13812. return results;
  13813. };
  13814. /**
  13815. * Gets the lsit of active attributes for a given webGL program
  13816. * @param shaderProgram defines the webGL program to use
  13817. * @param attributesNames defines the list of attribute names to get
  13818. * @returns an array of indices indicating the offset of each attribute
  13819. */
  13820. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  13821. var results = [];
  13822. for (var index = 0; index < attributesNames.length; index++) {
  13823. try {
  13824. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  13825. }
  13826. catch (e) {
  13827. results.push(-1);
  13828. }
  13829. }
  13830. return results;
  13831. };
  13832. /**
  13833. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  13834. * @param effect defines the effect to activate
  13835. */
  13836. Engine.prototype.enableEffect = function (effect) {
  13837. if (!effect || effect === this._currentEffect) {
  13838. return;
  13839. }
  13840. // Use program
  13841. this.bindSamplers(effect);
  13842. this._currentEffect = effect;
  13843. if (effect.onBind) {
  13844. effect.onBind(effect);
  13845. }
  13846. if (effect._onBindObservable) {
  13847. effect._onBindObservable.notifyObservers(effect);
  13848. }
  13849. };
  13850. /**
  13851. * Set the value of an uniform to an array of int32
  13852. * @param uniform defines the webGL uniform location where to store the value
  13853. * @param array defines the array of int32 to store
  13854. */
  13855. Engine.prototype.setIntArray = function (uniform, array) {
  13856. if (!uniform)
  13857. return;
  13858. this._gl.uniform1iv(uniform, array);
  13859. };
  13860. /**
  13861. * Set the value of an uniform to an array of int32 (stored as vec2)
  13862. * @param uniform defines the webGL uniform location where to store the value
  13863. * @param array defines the array of int32 to store
  13864. */
  13865. Engine.prototype.setIntArray2 = function (uniform, array) {
  13866. if (!uniform || array.length % 2 !== 0)
  13867. return;
  13868. this._gl.uniform2iv(uniform, array);
  13869. };
  13870. /**
  13871. * Set the value of an uniform to an array of int32 (stored as vec3)
  13872. * @param uniform defines the webGL uniform location where to store the value
  13873. * @param array defines the array of int32 to store
  13874. */
  13875. Engine.prototype.setIntArray3 = function (uniform, array) {
  13876. if (!uniform || array.length % 3 !== 0)
  13877. return;
  13878. this._gl.uniform3iv(uniform, array);
  13879. };
  13880. /**
  13881. * Set the value of an uniform to an array of int32 (stored as vec4)
  13882. * @param uniform defines the webGL uniform location where to store the value
  13883. * @param array defines the array of int32 to store
  13884. */
  13885. Engine.prototype.setIntArray4 = function (uniform, array) {
  13886. if (!uniform || array.length % 4 !== 0)
  13887. return;
  13888. this._gl.uniform4iv(uniform, array);
  13889. };
  13890. /**
  13891. * Set the value of an uniform to an array of float32
  13892. * @param uniform defines the webGL uniform location where to store the value
  13893. * @param array defines the array of float32 to store
  13894. */
  13895. Engine.prototype.setFloatArray = function (uniform, array) {
  13896. if (!uniform)
  13897. return;
  13898. this._gl.uniform1fv(uniform, array);
  13899. };
  13900. /**
  13901. * Set the value of an uniform to an array of float32 (stored as vec2)
  13902. * @param uniform defines the webGL uniform location where to store the value
  13903. * @param array defines the array of float32 to store
  13904. */
  13905. Engine.prototype.setFloatArray2 = function (uniform, array) {
  13906. if (!uniform || array.length % 2 !== 0)
  13907. return;
  13908. this._gl.uniform2fv(uniform, array);
  13909. };
  13910. /**
  13911. * Set the value of an uniform to an array of float32 (stored as vec3)
  13912. * @param uniform defines the webGL uniform location where to store the value
  13913. * @param array defines the array of float32 to store
  13914. */
  13915. Engine.prototype.setFloatArray3 = function (uniform, array) {
  13916. if (!uniform || array.length % 3 !== 0)
  13917. return;
  13918. this._gl.uniform3fv(uniform, array);
  13919. };
  13920. /**
  13921. * Set the value of an uniform to an array of float32 (stored as vec4)
  13922. * @param uniform defines the webGL uniform location where to store the value
  13923. * @param array defines the array of float32 to store
  13924. */
  13925. Engine.prototype.setFloatArray4 = function (uniform, array) {
  13926. if (!uniform || array.length % 4 !== 0)
  13927. return;
  13928. this._gl.uniform4fv(uniform, array);
  13929. };
  13930. /**
  13931. * Set the value of an uniform to an array of number
  13932. * @param uniform defines the webGL uniform location where to store the value
  13933. * @param array defines the array of number to store
  13934. */
  13935. Engine.prototype.setArray = function (uniform, array) {
  13936. if (!uniform)
  13937. return;
  13938. this._gl.uniform1fv(uniform, array);
  13939. };
  13940. /**
  13941. * Set the value of an uniform to an array of number (stored as vec2)
  13942. * @param uniform defines the webGL uniform location where to store the value
  13943. * @param array defines the array of number to store
  13944. */
  13945. Engine.prototype.setArray2 = function (uniform, array) {
  13946. if (!uniform || array.length % 2 !== 0)
  13947. return;
  13948. this._gl.uniform2fv(uniform, array);
  13949. };
  13950. /**
  13951. * Set the value of an uniform to an array of number (stored as vec3)
  13952. * @param uniform defines the webGL uniform location where to store the value
  13953. * @param array defines the array of number to store
  13954. */
  13955. Engine.prototype.setArray3 = function (uniform, array) {
  13956. if (!uniform || array.length % 3 !== 0)
  13957. return;
  13958. this._gl.uniform3fv(uniform, array);
  13959. };
  13960. /**
  13961. * Set the value of an uniform to an array of number (stored as vec4)
  13962. * @param uniform defines the webGL uniform location where to store the value
  13963. * @param array defines the array of number to store
  13964. */
  13965. Engine.prototype.setArray4 = function (uniform, array) {
  13966. if (!uniform || array.length % 4 !== 0)
  13967. return;
  13968. this._gl.uniform4fv(uniform, array);
  13969. };
  13970. /**
  13971. * Set the value of an uniform to an array of float32 (stored as matrices)
  13972. * @param uniform defines the webGL uniform location where to store the value
  13973. * @param matrices defines the array of float32 to store
  13974. */
  13975. Engine.prototype.setMatrices = function (uniform, matrices) {
  13976. if (!uniform)
  13977. return;
  13978. this._gl.uniformMatrix4fv(uniform, false, matrices);
  13979. };
  13980. /**
  13981. * Set the value of an uniform to a matrix
  13982. * @param uniform defines the webGL uniform location where to store the value
  13983. * @param matrix defines the matrix to store
  13984. */
  13985. Engine.prototype.setMatrix = function (uniform, matrix) {
  13986. if (!uniform)
  13987. return;
  13988. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  13989. };
  13990. /**
  13991. * Set the value of an uniform to a matrix (3x3)
  13992. * @param uniform defines the webGL uniform location where to store the value
  13993. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  13994. */
  13995. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  13996. if (!uniform)
  13997. return;
  13998. this._gl.uniformMatrix3fv(uniform, false, matrix);
  13999. };
  14000. /**
  14001. * Set the value of an uniform to a matrix (2x2)
  14002. * @param uniform defines the webGL uniform location where to store the value
  14003. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  14004. */
  14005. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  14006. if (!uniform)
  14007. return;
  14008. this._gl.uniformMatrix2fv(uniform, false, matrix);
  14009. };
  14010. /**
  14011. * Set the value of an uniform to a number (int)
  14012. * @param uniform defines the webGL uniform location where to store the value
  14013. * @param value defines the int number to store
  14014. */
  14015. Engine.prototype.setInt = function (uniform, value) {
  14016. if (!uniform)
  14017. return;
  14018. this._gl.uniform1i(uniform, value);
  14019. };
  14020. /**
  14021. * Set the value of an uniform to a number (float)
  14022. * @param uniform defines the webGL uniform location where to store the value
  14023. * @param value defines the float number to store
  14024. */
  14025. Engine.prototype.setFloat = function (uniform, value) {
  14026. if (!uniform)
  14027. return;
  14028. this._gl.uniform1f(uniform, value);
  14029. };
  14030. /**
  14031. * Set the value of an uniform to a vec2
  14032. * @param uniform defines the webGL uniform location where to store the value
  14033. * @param x defines the 1st component of the value
  14034. * @param y defines the 2nd component of the value
  14035. */
  14036. Engine.prototype.setFloat2 = function (uniform, x, y) {
  14037. if (!uniform)
  14038. return;
  14039. this._gl.uniform2f(uniform, x, y);
  14040. };
  14041. /**
  14042. * Set the value of an uniform to a vec3
  14043. * @param uniform defines the webGL uniform location where to store the value
  14044. * @param x defines the 1st component of the value
  14045. * @param y defines the 2nd component of the value
  14046. * @param z defines the 3rd component of the value
  14047. */
  14048. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  14049. if (!uniform)
  14050. return;
  14051. this._gl.uniform3f(uniform, x, y, z);
  14052. };
  14053. /**
  14054. * Set the value of an uniform to a boolean
  14055. * @param uniform defines the webGL uniform location where to store the value
  14056. * @param bool defines the boolean to store
  14057. */
  14058. Engine.prototype.setBool = function (uniform, bool) {
  14059. if (!uniform)
  14060. return;
  14061. this._gl.uniform1i(uniform, bool);
  14062. };
  14063. /**
  14064. * Set the value of an uniform to a vec4
  14065. * @param uniform defines the webGL uniform location where to store the value
  14066. * @param x defines the 1st component of the value
  14067. * @param y defines the 2nd component of the value
  14068. * @param z defines the 3rd component of the value
  14069. * @param w defines the 4th component of the value
  14070. */
  14071. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14072. if (!uniform)
  14073. return;
  14074. this._gl.uniform4f(uniform, x, y, z, w);
  14075. };
  14076. /**
  14077. * Set the value of an uniform to a Color3
  14078. * @param uniform defines the webGL uniform location where to store the value
  14079. * @param color3 defines the color to store
  14080. */
  14081. Engine.prototype.setColor3 = function (uniform, color3) {
  14082. if (!uniform)
  14083. return;
  14084. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14085. };
  14086. /**
  14087. * Set the value of an uniform to a Color3 and an alpha value
  14088. * @param uniform defines the webGL uniform location where to store the value
  14089. * @param color3 defines the color to store
  14090. * @param alpha defines the alpha component to store
  14091. */
  14092. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14093. if (!uniform)
  14094. return;
  14095. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14096. };
  14097. /**
  14098. * Sets a Color4 on a uniform variable
  14099. * @param uniform defines the uniform location
  14100. * @param color4 defines the value to be set
  14101. */
  14102. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14103. if (!uniform)
  14104. return;
  14105. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14106. };
  14107. // States
  14108. /**
  14109. * Set various states to the webGL context
  14110. * @param culling defines backface culling state
  14111. * @param zOffset defines the value to apply to zOffset (0 by default)
  14112. * @param force defines if states must be applied even if cache is up to date
  14113. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14114. */
  14115. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14116. if (zOffset === void 0) { zOffset = 0; }
  14117. if (reverseSide === void 0) { reverseSide = false; }
  14118. // Culling
  14119. if (this._depthCullingState.cull !== culling || force) {
  14120. this._depthCullingState.cull = culling;
  14121. }
  14122. // Cull face
  14123. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14124. if (this._depthCullingState.cullFace !== cullFace || force) {
  14125. this._depthCullingState.cullFace = cullFace;
  14126. }
  14127. // Z offset
  14128. this.setZOffset(zOffset);
  14129. // Front face
  14130. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14131. if (this._depthCullingState.frontFace !== frontFace || force) {
  14132. this._depthCullingState.frontFace = frontFace;
  14133. }
  14134. };
  14135. /**
  14136. * Set the z offset to apply to current rendering
  14137. * @param value defines the offset to apply
  14138. */
  14139. Engine.prototype.setZOffset = function (value) {
  14140. this._depthCullingState.zOffset = value;
  14141. };
  14142. /**
  14143. * Gets the current value of the zOffset
  14144. * @returns the current zOffset state
  14145. */
  14146. Engine.prototype.getZOffset = function () {
  14147. return this._depthCullingState.zOffset;
  14148. };
  14149. /**
  14150. * Enable or disable depth buffering
  14151. * @param enable defines the state to set
  14152. */
  14153. Engine.prototype.setDepthBuffer = function (enable) {
  14154. this._depthCullingState.depthTest = enable;
  14155. };
  14156. /**
  14157. * Gets a boolean indicating if depth writing is enabled
  14158. * @returns the current depth writing state
  14159. */
  14160. Engine.prototype.getDepthWrite = function () {
  14161. return this._depthCullingState.depthMask;
  14162. };
  14163. /**
  14164. * Enable or disable depth writing
  14165. * @param enable defines the state to set
  14166. */
  14167. Engine.prototype.setDepthWrite = function (enable) {
  14168. this._depthCullingState.depthMask = enable;
  14169. };
  14170. /**
  14171. * Enable or disable color writing
  14172. * @param enable defines the state to set
  14173. */
  14174. Engine.prototype.setColorWrite = function (enable) {
  14175. this._gl.colorMask(enable, enable, enable, enable);
  14176. this._colorWrite = enable;
  14177. };
  14178. /**
  14179. * Gets a boolean indicating if color writing is enabled
  14180. * @returns the current color writing state
  14181. */
  14182. Engine.prototype.getColorWrite = function () {
  14183. return this._colorWrite;
  14184. };
  14185. /**
  14186. * Sets alpha constants used by some alpha blending modes
  14187. * @param r defines the red component
  14188. * @param g defines the green component
  14189. * @param b defines the blue component
  14190. * @param a defines the alpha component
  14191. */
  14192. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14193. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14194. };
  14195. /**
  14196. * Sets the current alpha mode
  14197. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14198. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14199. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14200. */
  14201. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14202. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14203. if (this._alphaMode === mode) {
  14204. return;
  14205. }
  14206. switch (mode) {
  14207. case Engine.ALPHA_DISABLE:
  14208. this._alphaState.alphaBlend = false;
  14209. break;
  14210. case Engine.ALPHA_PREMULTIPLIED:
  14211. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14212. this._alphaState.alphaBlend = true;
  14213. break;
  14214. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14215. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14216. this._alphaState.alphaBlend = true;
  14217. break;
  14218. case Engine.ALPHA_COMBINE:
  14219. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14220. this._alphaState.alphaBlend = true;
  14221. break;
  14222. case Engine.ALPHA_ONEONE:
  14223. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14224. this._alphaState.alphaBlend = true;
  14225. break;
  14226. case Engine.ALPHA_ADD:
  14227. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14228. this._alphaState.alphaBlend = true;
  14229. break;
  14230. case Engine.ALPHA_SUBTRACT:
  14231. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14232. this._alphaState.alphaBlend = true;
  14233. break;
  14234. case Engine.ALPHA_MULTIPLY:
  14235. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14236. this._alphaState.alphaBlend = true;
  14237. break;
  14238. case Engine.ALPHA_MAXIMIZED:
  14239. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14240. this._alphaState.alphaBlend = true;
  14241. break;
  14242. case Engine.ALPHA_INTERPOLATE:
  14243. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14244. this._alphaState.alphaBlend = true;
  14245. break;
  14246. case Engine.ALPHA_SCREENMODE:
  14247. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14248. this._alphaState.alphaBlend = true;
  14249. break;
  14250. }
  14251. if (!noDepthWriteChange) {
  14252. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14253. }
  14254. this._alphaMode = mode;
  14255. };
  14256. /**
  14257. * Gets the current alpha mode
  14258. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14259. * @returns the current alpha mode
  14260. */
  14261. Engine.prototype.getAlphaMode = function () {
  14262. return this._alphaMode;
  14263. };
  14264. // Textures
  14265. /**
  14266. * Clears the list of texture accessible through engine.
  14267. * This can help preventing texture load conflict due to name collision.
  14268. */
  14269. Engine.prototype.clearInternalTexturesCache = function () {
  14270. this._internalTexturesCache = [];
  14271. };
  14272. /**
  14273. * Force the entire cache to be cleared
  14274. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14275. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14276. */
  14277. Engine.prototype.wipeCaches = function (bruteForce) {
  14278. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14279. return;
  14280. }
  14281. this._currentEffect = null;
  14282. this._viewportCached.x = 0;
  14283. this._viewportCached.y = 0;
  14284. this._viewportCached.z = 0;
  14285. this._viewportCached.w = 0;
  14286. if (bruteForce) {
  14287. this.resetTextureCache();
  14288. this._currentProgram = null;
  14289. this._stencilState.reset();
  14290. this._depthCullingState.reset();
  14291. this.setDepthFunctionToLessOrEqual();
  14292. this._alphaState.reset();
  14293. this._unpackFlipYCached = null;
  14294. }
  14295. this._resetVertexBufferBinding();
  14296. this._cachedIndexBuffer = null;
  14297. this._cachedEffectForVertexBuffers = null;
  14298. this._unbindVertexArrayObject();
  14299. this.bindIndexBuffer(null);
  14300. };
  14301. /**
  14302. * Set the compressed texture format to use, based on the formats you have, and the formats
  14303. * supported by the hardware / browser.
  14304. *
  14305. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14306. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14307. * to API arguments needed to compressed textures. This puts the burden on the container
  14308. * generator to house the arcane code for determining these for current & future formats.
  14309. *
  14310. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14311. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14312. *
  14313. * Note: The result of this call is not taken into account when a texture is base64.
  14314. *
  14315. * @param formatsAvailable defines the list of those format families you have created
  14316. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14317. *
  14318. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14319. * @returns The extension selected.
  14320. */
  14321. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14322. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14323. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14324. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14325. return this._textureFormatInUse = this._texturesSupported[i];
  14326. }
  14327. }
  14328. }
  14329. // actively set format to nothing, to allow this to be called more than once
  14330. // and possibly fail the 2nd time
  14331. this._textureFormatInUse = null;
  14332. return null;
  14333. };
  14334. Engine.prototype._getSamplingParameters = function (samplingMode, generateMipMaps) {
  14335. var gl = this._gl;
  14336. var magFilter = gl.NEAREST;
  14337. var minFilter = gl.NEAREST;
  14338. switch (samplingMode) {
  14339. case Engine.TEXTURE_BILINEAR_SAMPLINGMODE:
  14340. magFilter = gl.LINEAR;
  14341. if (generateMipMaps) {
  14342. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  14343. }
  14344. else {
  14345. minFilter = gl.LINEAR;
  14346. }
  14347. break;
  14348. case Engine.TEXTURE_TRILINEAR_SAMPLINGMODE:
  14349. magFilter = gl.LINEAR;
  14350. if (generateMipMaps) {
  14351. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  14352. }
  14353. else {
  14354. minFilter = gl.LINEAR;
  14355. }
  14356. break;
  14357. case Engine.TEXTURE_NEAREST_SAMPLINGMODE:
  14358. magFilter = gl.NEAREST;
  14359. if (generateMipMaps) {
  14360. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  14361. }
  14362. else {
  14363. minFilter = gl.NEAREST;
  14364. }
  14365. break;
  14366. case Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST:
  14367. magFilter = gl.NEAREST;
  14368. if (generateMipMaps) {
  14369. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  14370. }
  14371. else {
  14372. minFilter = gl.NEAREST;
  14373. }
  14374. break;
  14375. case Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST:
  14376. magFilter = gl.NEAREST;
  14377. if (generateMipMaps) {
  14378. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  14379. }
  14380. else {
  14381. minFilter = gl.LINEAR;
  14382. }
  14383. break;
  14384. case Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR:
  14385. magFilter = gl.NEAREST;
  14386. if (generateMipMaps) {
  14387. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  14388. }
  14389. else {
  14390. minFilter = gl.LINEAR;
  14391. }
  14392. break;
  14393. case Engine.TEXTURE_NEAREST_LINEAR:
  14394. magFilter = gl.NEAREST;
  14395. minFilter = gl.LINEAR;
  14396. break;
  14397. case Engine.TEXTURE_NEAREST_NEAREST:
  14398. magFilter = gl.NEAREST;
  14399. minFilter = gl.NEAREST;
  14400. break;
  14401. case Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST:
  14402. magFilter = gl.LINEAR;
  14403. if (generateMipMaps) {
  14404. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  14405. }
  14406. else {
  14407. minFilter = gl.NEAREST;
  14408. }
  14409. break;
  14410. case Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR:
  14411. magFilter = gl.LINEAR;
  14412. if (generateMipMaps) {
  14413. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  14414. }
  14415. else {
  14416. minFilter = gl.NEAREST;
  14417. }
  14418. break;
  14419. case Engine.TEXTURE_LINEAR_LINEAR:
  14420. magFilter = gl.LINEAR;
  14421. minFilter = gl.LINEAR;
  14422. break;
  14423. case Engine.TEXTURE_LINEAR_NEAREST:
  14424. magFilter = gl.LINEAR;
  14425. minFilter = gl.NEAREST;
  14426. break;
  14427. }
  14428. return {
  14429. min: minFilter,
  14430. mag: magFilter
  14431. };
  14432. };
  14433. Engine.prototype._partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  14434. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  14435. var img;
  14436. var onload = function () {
  14437. loadedImages[index] = img;
  14438. loadedImages._internalCount++;
  14439. if (scene) {
  14440. scene._removePendingData(img);
  14441. }
  14442. if (loadedImages._internalCount === 6) {
  14443. onfinish(loadedImages);
  14444. }
  14445. };
  14446. var onerror = function (message, exception) {
  14447. if (scene) {
  14448. scene._removePendingData(img);
  14449. }
  14450. if (onErrorCallBack) {
  14451. onErrorCallBack(message, exception);
  14452. }
  14453. };
  14454. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14455. if (scene) {
  14456. scene._addPendingData(img);
  14457. }
  14458. };
  14459. Engine.prototype._cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  14460. if (onError === void 0) { onError = null; }
  14461. var loadedImages = [];
  14462. loadedImages._internalCount = 0;
  14463. for (var index = 0; index < 6; index++) {
  14464. this._partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  14465. }
  14466. };
  14467. ;
  14468. /** @hidden */
  14469. Engine.prototype._createTexture = function () {
  14470. var texture = this._gl.createTexture();
  14471. if (!texture) {
  14472. throw new Error("Unable to create texture");
  14473. }
  14474. return texture;
  14475. };
  14476. /**
  14477. * Usually called from BABYLON.Texture.ts.
  14478. * Passed information to create a WebGLTexture
  14479. * @param urlArg defines a value which contains one of the following:
  14480. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14481. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14482. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14483. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14484. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14485. * @param scene needed for loading to the correct scene
  14486. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14487. * @param onLoad optional callback to be called upon successful completion
  14488. * @param onError optional callback to be called upon failure
  14489. * @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
  14490. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14491. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14492. * @param forcedExtension defines the extension to use to pick the right loader
  14493. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14494. */
  14495. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format, forcedExtension) {
  14496. var _this = this;
  14497. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  14498. if (onLoad === void 0) { onLoad = null; }
  14499. if (onError === void 0) { onError = null; }
  14500. if (buffer === void 0) { buffer = null; }
  14501. if (fallback === void 0) { fallback = null; }
  14502. if (format === void 0) { format = null; }
  14503. if (forcedExtension === void 0) { forcedExtension = null; }
  14504. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14505. var fromData = url.substr(0, 5) === "data:";
  14506. var fromBlob = url.substr(0, 5) === "blob:";
  14507. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14508. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14509. // establish the file extension, if possible
  14510. var lastDot = url.lastIndexOf('.');
  14511. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? url.substring(lastDot).toLowerCase() : "");
  14512. var loader = null;
  14513. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  14514. var availableLoader = _a[_i];
  14515. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, isBase64, buffer ? true : false)) {
  14516. loader = availableLoader;
  14517. break;
  14518. }
  14519. }
  14520. if (loader) {
  14521. url = loader.transformUrl(url, this._textureFormatInUse);
  14522. }
  14523. if (scene) {
  14524. scene._addPendingData(texture);
  14525. }
  14526. texture.url = url;
  14527. texture.generateMipMaps = !noMipmap;
  14528. texture.samplingMode = samplingMode;
  14529. texture.invertY = invertY;
  14530. if (!this._doNotHandleContextLost) {
  14531. // Keep a link to the buffer only if we plan to handle context lost
  14532. texture._buffer = buffer;
  14533. }
  14534. var onLoadObserver = null;
  14535. if (onLoad && !fallback) {
  14536. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14537. }
  14538. if (!fallback)
  14539. this._internalTexturesCache.push(texture);
  14540. var onInternalError = function (message, exception) {
  14541. if (scene) {
  14542. scene._removePendingData(texture);
  14543. }
  14544. var customFallback = false;
  14545. if (loader) {
  14546. var fallbackUrl = loader.getFallbackTextureUrl(url, _this._textureFormatInUse);
  14547. if (fallbackUrl) {
  14548. // Add Back
  14549. customFallback = true;
  14550. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14551. }
  14552. }
  14553. if (!customFallback) {
  14554. if (onLoadObserver) {
  14555. texture.onLoadedObservable.remove(onLoadObserver);
  14556. }
  14557. if (BABYLON.Tools.UseFallbackTexture) {
  14558. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14559. }
  14560. }
  14561. if (onError) {
  14562. onError(message || "Unknown error", exception);
  14563. }
  14564. };
  14565. // processing for non-image formats
  14566. if (loader) {
  14567. var callback = function (data) {
  14568. loader.loadData(data, texture, function (width, height, loadMipmap, isCompressed, done) {
  14569. _this._prepareWebGLTexture(texture, scene, width, height, invertY, !loadMipmap, isCompressed, function () {
  14570. done();
  14571. return false;
  14572. }, samplingMode);
  14573. });
  14574. };
  14575. if (!buffer) {
  14576. this._loadFile(url, callback, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14577. onInternalError("Unable to load " + (request ? request.responseURL : url, exception));
  14578. });
  14579. }
  14580. else {
  14581. callback(buffer);
  14582. }
  14583. }
  14584. else {
  14585. var onload = function (img) {
  14586. if (fromBlob && !_this._doNotHandleContextLost) {
  14587. // We need to store the image if we need to rebuild the texture
  14588. // in case of a webgl context lost
  14589. texture._buffer = img;
  14590. }
  14591. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14592. var gl = _this._gl;
  14593. var isPot = (img.width === potWidth && img.height === potHeight);
  14594. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14595. if (isPot) {
  14596. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14597. return false;
  14598. }
  14599. var maxTextureSize = _this._caps.maxTextureSize;
  14600. if (img.width > maxTextureSize || img.height > maxTextureSize) {
  14601. _this._prepareWorkingCanvas();
  14602. if (!_this._workingCanvas || !_this._workingContext) {
  14603. return false;
  14604. }
  14605. _this._workingCanvas.width = potWidth;
  14606. _this._workingCanvas.height = potHeight;
  14607. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  14608. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  14609. texture.width = potWidth;
  14610. texture.height = potHeight;
  14611. return false;
  14612. }
  14613. else {
  14614. // Using shaders when possible to rescale because canvas.drawImage is lossy
  14615. var source_1 = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14616. _this._bindTextureDirectly(gl.TEXTURE_2D, source_1, true);
  14617. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14618. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14619. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14620. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14621. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14622. _this._rescaleTexture(source_1, texture, scene, internalFormat, function () {
  14623. _this._releaseTexture(source_1);
  14624. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14625. continuationCallback();
  14626. });
  14627. }
  14628. return true;
  14629. }, samplingMode);
  14630. };
  14631. if (!fromData || isBase64) {
  14632. if (buffer instanceof HTMLImageElement) {
  14633. onload(buffer);
  14634. }
  14635. else {
  14636. BABYLON.Tools.LoadImage(url, onload, onInternalError, scene ? scene.database : null);
  14637. }
  14638. }
  14639. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  14640. BABYLON.Tools.LoadImage(buffer, onload, onInternalError, scene ? scene.database : null);
  14641. }
  14642. else {
  14643. onload(buffer);
  14644. }
  14645. }
  14646. return texture;
  14647. };
  14648. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14649. var _this = this;
  14650. var rtt = this.createRenderTargetTexture({
  14651. width: destination.width,
  14652. height: destination.height,
  14653. }, {
  14654. generateMipMaps: false,
  14655. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14656. samplingMode: Engine.TEXTURE_BILINEAR_SAMPLINGMODE,
  14657. generateDepthBuffer: false,
  14658. generateStencilBuffer: false
  14659. });
  14660. if (!this._rescalePostProcess) {
  14661. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, Engine.TEXTURE_BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14662. }
  14663. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14664. _this._rescalePostProcess.onApply = function (effect) {
  14665. effect._bindTexture("textureSampler", source);
  14666. };
  14667. var hostingScene = scene;
  14668. if (!hostingScene) {
  14669. hostingScene = _this.scenes[_this.scenes.length - 1];
  14670. }
  14671. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14672. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14673. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14674. _this.unBindFramebuffer(rtt);
  14675. _this._releaseTexture(rtt);
  14676. if (onComplete) {
  14677. onComplete();
  14678. }
  14679. });
  14680. };
  14681. /**
  14682. * Update a raw texture
  14683. * @param texture defines the texture to update
  14684. * @param data defines the data to store in the texture
  14685. * @param format defines the format of the data
  14686. * @param invertY defines if data must be stored with Y axis inverted
  14687. * @param compression defines the compression used (null by default)
  14688. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14689. */
  14690. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14691. if (compression === void 0) { compression = null; }
  14692. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14693. if (!texture) {
  14694. return;
  14695. }
  14696. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  14697. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14698. // babylon's internalFormat but gl's texImage2D format
  14699. var internalFormat = this._getInternalFormat(format);
  14700. var textureType = this._getWebGLTextureType(type);
  14701. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14702. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  14703. if (!this._doNotHandleContextLost) {
  14704. texture._bufferView = data;
  14705. texture.format = format;
  14706. texture.type = type;
  14707. texture.invertY = invertY;
  14708. texture._compression = compression;
  14709. }
  14710. if (texture.width % 4 !== 0) {
  14711. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14712. }
  14713. if (compression && data) {
  14714. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14715. }
  14716. else {
  14717. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14718. }
  14719. if (texture.generateMipMaps) {
  14720. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14721. }
  14722. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14723. // this.resetTextureCache();
  14724. texture.isReady = true;
  14725. };
  14726. /**
  14727. * Creates a raw texture
  14728. * @param data defines the data to store in the texture
  14729. * @param width defines the width of the texture
  14730. * @param height defines the height of the texture
  14731. * @param format defines the format of the data
  14732. * @param generateMipMaps defines if the engine should generate the mip levels
  14733. * @param invertY defines if data must be stored with Y axis inverted
  14734. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14735. * @param compression defines the compression used (null by default)
  14736. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14737. * @returns the raw texture inside an InternalTexture
  14738. */
  14739. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14740. if (compression === void 0) { compression = null; }
  14741. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14742. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14743. texture.baseWidth = width;
  14744. texture.baseHeight = height;
  14745. texture.width = width;
  14746. texture.height = height;
  14747. texture.format = format;
  14748. texture.generateMipMaps = generateMipMaps;
  14749. texture.samplingMode = samplingMode;
  14750. texture.invertY = invertY;
  14751. texture._compression = compression;
  14752. texture.type = type;
  14753. if (!this._doNotHandleContextLost) {
  14754. texture._bufferView = data;
  14755. }
  14756. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14757. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14758. // Filters
  14759. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  14760. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14761. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14762. if (generateMipMaps) {
  14763. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14764. }
  14765. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14766. this._internalTexturesCache.push(texture);
  14767. return texture;
  14768. };
  14769. /** @hidden */
  14770. Engine.prototype._unpackFlipY = function (value) {
  14771. if (this._unpackFlipYCached !== value) {
  14772. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);
  14773. if (this.enableUnpackFlipYCached) {
  14774. this._unpackFlipYCached = value;
  14775. }
  14776. }
  14777. };
  14778. /** @hidden */
  14779. Engine.prototype._getUnpackAlignement = function () {
  14780. return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT);
  14781. };
  14782. /**
  14783. * Creates a dynamic texture
  14784. * @param width defines the width of the texture
  14785. * @param height defines the height of the texture
  14786. * @param generateMipMaps defines if the engine should generate the mip levels
  14787. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14788. * @returns the dynamic texture inside an InternalTexture
  14789. */
  14790. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14791. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14792. texture.baseWidth = width;
  14793. texture.baseHeight = height;
  14794. if (generateMipMaps) {
  14795. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14796. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14797. }
  14798. // this.resetTextureCache();
  14799. texture.width = width;
  14800. texture.height = height;
  14801. texture.isReady = false;
  14802. texture.generateMipMaps = generateMipMaps;
  14803. texture.samplingMode = samplingMode;
  14804. this.updateTextureSamplingMode(samplingMode, texture);
  14805. this._internalTexturesCache.push(texture);
  14806. return texture;
  14807. };
  14808. /**
  14809. * Update the sampling mode of a given texture
  14810. * @param samplingMode defines the required sampling mode
  14811. * @param texture defines the texture to update
  14812. */
  14813. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14814. var filters = this._getSamplingParameters(samplingMode, texture.generateMipMaps);
  14815. if (texture.isCube) {
  14816. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14817. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14818. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14819. }
  14820. else if (texture.is3D) {
  14821. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14822. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14823. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14824. }
  14825. else {
  14826. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14827. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14828. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14829. }
  14830. texture.samplingMode = samplingMode;
  14831. };
  14832. /**
  14833. * Update the content of a dynamic texture
  14834. * @param texture defines the texture to update
  14835. * @param canvas defines the canvas containing the source
  14836. * @param invertY defines if data must be stored with Y axis inverted
  14837. * @param premulAlpha defines if alpha is stored as premultiplied
  14838. * @param format defines the format of the data
  14839. */
  14840. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14841. if (premulAlpha === void 0) { premulAlpha = false; }
  14842. if (!texture) {
  14843. return;
  14844. }
  14845. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14846. this._unpackFlipY(invertY);
  14847. if (premulAlpha) {
  14848. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  14849. }
  14850. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  14851. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  14852. if (texture.generateMipMaps) {
  14853. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14854. }
  14855. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14856. if (premulAlpha) {
  14857. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  14858. }
  14859. texture.isReady = true;
  14860. };
  14861. /**
  14862. * Update a video texture
  14863. * @param texture defines the texture to update
  14864. * @param video defines the video element to use
  14865. * @param invertY defines if data must be stored with Y axis inverted
  14866. */
  14867. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  14868. if (!texture || texture._isDisabled) {
  14869. return;
  14870. }
  14871. var wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14872. this._unpackFlipY(!invertY); // Video are upside down by default
  14873. try {
  14874. // Testing video texture support
  14875. if (this._videoTextureSupported === undefined) {
  14876. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14877. if (this._gl.getError() !== 0) {
  14878. this._videoTextureSupported = false;
  14879. }
  14880. else {
  14881. this._videoTextureSupported = true;
  14882. }
  14883. }
  14884. // Copy video through the current working canvas if video texture is not supported
  14885. if (!this._videoTextureSupported) {
  14886. if (!texture._workingCanvas) {
  14887. texture._workingCanvas = document.createElement("canvas");
  14888. var context = texture._workingCanvas.getContext("2d");
  14889. if (!context) {
  14890. throw new Error("Unable to get 2d context");
  14891. }
  14892. texture._workingContext = context;
  14893. texture._workingCanvas.width = texture.width;
  14894. texture._workingCanvas.height = texture.height;
  14895. }
  14896. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  14897. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  14898. }
  14899. else {
  14900. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14901. }
  14902. if (texture.generateMipMaps) {
  14903. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14904. }
  14905. if (!wasPreviouslyBound) {
  14906. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14907. }
  14908. // this.resetTextureCache();
  14909. texture.isReady = true;
  14910. }
  14911. catch (ex) {
  14912. // Something unexpected
  14913. // Let's disable the texture
  14914. texture._isDisabled = true;
  14915. }
  14916. };
  14917. /**
  14918. * Updates a depth texture Comparison Mode and Function.
  14919. * If the comparison Function is equal to 0, the mode will be set to none.
  14920. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  14921. * @param texture The texture to set the comparison function for
  14922. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  14923. */
  14924. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  14925. if (this.webGLVersion === 1) {
  14926. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  14927. return;
  14928. }
  14929. var gl = this._gl;
  14930. if (texture.isCube) {
  14931. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14932. if (comparisonFunction === 0) {
  14933. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14934. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14935. }
  14936. else {
  14937. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14938. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14939. }
  14940. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14941. }
  14942. else {
  14943. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14944. if (comparisonFunction === 0) {
  14945. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14946. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14947. }
  14948. else {
  14949. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14950. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14951. }
  14952. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14953. }
  14954. texture._comparisonFunction = comparisonFunction;
  14955. };
  14956. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  14957. var width = size.width || size;
  14958. var height = size.height || size;
  14959. internalTexture.baseWidth = width;
  14960. internalTexture.baseHeight = height;
  14961. internalTexture.width = width;
  14962. internalTexture.height = height;
  14963. internalTexture.isReady = true;
  14964. internalTexture.samples = 1;
  14965. internalTexture.generateMipMaps = false;
  14966. internalTexture._generateDepthBuffer = true;
  14967. internalTexture._generateStencilBuffer = generateStencil;
  14968. internalTexture.samplingMode = bilinearFiltering ? Engine.TEXTURE_BILINEAR_SAMPLINGMODE : Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  14969. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14970. internalTexture._comparisonFunction = comparisonFunction;
  14971. var gl = this._gl;
  14972. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  14973. var samplingParameters = this._getSamplingParameters(internalTexture.samplingMode, false);
  14974. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  14975. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  14976. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14977. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14978. if (comparisonFunction === 0) {
  14979. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14980. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14981. }
  14982. else {
  14983. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14984. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14985. }
  14986. };
  14987. /**
  14988. * Creates a depth stencil texture.
  14989. * This is only available in WebGL 2 or with the depth texture extension available.
  14990. * @param size The size of face edge in the texture.
  14991. * @param options The options defining the texture.
  14992. * @returns The texture
  14993. */
  14994. Engine.prototype.createDepthStencilTexture = function (size, options) {
  14995. if (options.isCube) {
  14996. var width = size.width || size;
  14997. return this._createDepthStencilCubeTexture(width, options);
  14998. }
  14999. else {
  15000. return this._createDepthStencilTexture(size, options);
  15001. }
  15002. };
  15003. /**
  15004. * Creates a depth stencil texture.
  15005. * This is only available in WebGL 2 or with the depth texture extension available.
  15006. * @param size The size of face edge in the texture.
  15007. * @param options The options defining the texture.
  15008. * @returns The texture
  15009. */
  15010. Engine.prototype._createDepthStencilTexture = function (size, options) {
  15011. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  15012. if (!this._caps.depthTextureExtension) {
  15013. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  15014. return internalTexture;
  15015. }
  15016. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15017. var gl = this._gl;
  15018. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  15019. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15020. if (this.webGLVersion > 1) {
  15021. if (internalOptions.generateStencil) {
  15022. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15023. }
  15024. else {
  15025. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15026. }
  15027. }
  15028. else {
  15029. if (internalOptions.generateStencil) {
  15030. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15031. }
  15032. else {
  15033. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15034. }
  15035. }
  15036. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15037. return internalTexture;
  15038. };
  15039. /**
  15040. * Creates a depth stencil cube texture.
  15041. * This is only available in WebGL 2.
  15042. * @param size The size of face edge in the cube texture.
  15043. * @param options The options defining the cube texture.
  15044. * @returns The cube texture
  15045. */
  15046. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  15047. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  15048. internalTexture.isCube = true;
  15049. if (this.webGLVersion === 1) {
  15050. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  15051. return internalTexture;
  15052. }
  15053. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15054. var gl = this._gl;
  15055. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  15056. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15057. // Create the depth/stencil buffer
  15058. for (var face = 0; face < 6; face++) {
  15059. if (internalOptions.generateStencil) {
  15060. 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);
  15061. }
  15062. else {
  15063. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15064. }
  15065. }
  15066. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15067. return internalTexture;
  15068. };
  15069. /**
  15070. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15071. * @param renderTarget The render target to set the frame buffer for
  15072. */
  15073. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15074. // Create the framebuffer
  15075. var internalTexture = renderTarget.getInternalTexture();
  15076. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15077. return;
  15078. }
  15079. var gl = this._gl;
  15080. var depthStencilTexture = renderTarget.depthStencilTexture;
  15081. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15082. if (depthStencilTexture.isCube) {
  15083. if (depthStencilTexture._generateStencilBuffer) {
  15084. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15085. }
  15086. else {
  15087. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15088. }
  15089. }
  15090. else {
  15091. if (depthStencilTexture._generateStencilBuffer) {
  15092. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15093. }
  15094. else {
  15095. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15096. }
  15097. }
  15098. this.bindUnboundFramebuffer(null);
  15099. };
  15100. /**
  15101. * Creates a new render target texture
  15102. * @param size defines the size of the texture
  15103. * @param options defines the options used to create the texture
  15104. * @returns a new render target texture stored in an InternalTexture
  15105. */
  15106. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15107. var fullOptions = new RenderTargetCreationOptions();
  15108. if (options !== undefined && typeof options === "object") {
  15109. fullOptions.generateMipMaps = options.generateMipMaps;
  15110. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15111. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15112. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15113. fullOptions.samplingMode = options.samplingMode === undefined ? Engine.TEXTURE_TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15114. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15115. }
  15116. else {
  15117. fullOptions.generateMipMaps = options;
  15118. fullOptions.generateDepthBuffer = true;
  15119. fullOptions.generateStencilBuffer = false;
  15120. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15121. fullOptions.samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15122. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15123. }
  15124. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15125. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15126. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15127. }
  15128. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15129. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15130. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15131. }
  15132. var gl = this._gl;
  15133. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15134. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15135. var width = size.width || size;
  15136. var height = size.height || size;
  15137. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false);
  15138. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15139. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15140. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15141. }
  15142. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15143. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15144. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15145. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15146. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15147. // Create the framebuffer
  15148. var currentFrameBuffer = this._currentFramebuffer;
  15149. var framebuffer = gl.createFramebuffer();
  15150. this.bindUnboundFramebuffer(framebuffer);
  15151. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15152. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15153. if (fullOptions.generateMipMaps) {
  15154. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15155. }
  15156. // Unbind
  15157. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15158. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15159. this.bindUnboundFramebuffer(currentFrameBuffer);
  15160. texture._framebuffer = framebuffer;
  15161. texture.baseWidth = width;
  15162. texture.baseHeight = height;
  15163. texture.width = width;
  15164. texture.height = height;
  15165. texture.isReady = true;
  15166. texture.samples = 1;
  15167. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15168. texture.samplingMode = fullOptions.samplingMode;
  15169. texture.type = fullOptions.type;
  15170. texture.format = fullOptions.format;
  15171. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15172. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15173. // this.resetTextureCache();
  15174. this._internalTexturesCache.push(texture);
  15175. return texture;
  15176. };
  15177. /**
  15178. * Create a multi render target texture
  15179. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15180. * @param size defines the size of the texture
  15181. * @param options defines the creation options
  15182. * @returns the cube texture as an InternalTexture
  15183. */
  15184. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15185. var generateMipMaps = false;
  15186. var generateDepthBuffer = true;
  15187. var generateStencilBuffer = false;
  15188. var generateDepthTexture = false;
  15189. var textureCount = 1;
  15190. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15191. var defaultSamplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15192. var types = new Array();
  15193. var samplingModes = new Array();
  15194. if (options !== undefined) {
  15195. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15196. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15197. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15198. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15199. textureCount = options.textureCount || 1;
  15200. if (options.types) {
  15201. types = options.types;
  15202. }
  15203. if (options.samplingModes) {
  15204. samplingModes = options.samplingModes;
  15205. }
  15206. }
  15207. var gl = this._gl;
  15208. // Create the framebuffer
  15209. var framebuffer = gl.createFramebuffer();
  15210. this.bindUnboundFramebuffer(framebuffer);
  15211. var width = size.width || size;
  15212. var height = size.height || size;
  15213. var textures = [];
  15214. var attachments = [];
  15215. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15216. for (var i = 0; i < textureCount; i++) {
  15217. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15218. var type = types[i] || defaultType;
  15219. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15220. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15221. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15222. }
  15223. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15224. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15225. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15226. }
  15227. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15228. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15229. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15230. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15231. }
  15232. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15233. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15234. textures.push(texture);
  15235. attachments.push(attachment);
  15236. gl.activeTexture(gl["TEXTURE" + i]);
  15237. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15238. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15239. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15240. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15241. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15242. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15243. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15244. if (generateMipMaps) {
  15245. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15246. }
  15247. // Unbind
  15248. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15249. texture._framebuffer = framebuffer;
  15250. texture._depthStencilBuffer = depthStencilBuffer;
  15251. texture.baseWidth = width;
  15252. texture.baseHeight = height;
  15253. texture.width = width;
  15254. texture.height = height;
  15255. texture.isReady = true;
  15256. texture.samples = 1;
  15257. texture.generateMipMaps = generateMipMaps;
  15258. texture.samplingMode = samplingMode;
  15259. texture.type = type;
  15260. texture._generateDepthBuffer = generateDepthBuffer;
  15261. texture._generateStencilBuffer = generateStencilBuffer;
  15262. texture._attachments = attachments;
  15263. this._internalTexturesCache.push(texture);
  15264. }
  15265. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15266. // Depth texture
  15267. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15268. gl.activeTexture(gl.TEXTURE0);
  15269. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15270. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15271. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15272. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15273. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15274. 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);
  15275. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15276. depthTexture._framebuffer = framebuffer;
  15277. depthTexture.baseWidth = width;
  15278. depthTexture.baseHeight = height;
  15279. depthTexture.width = width;
  15280. depthTexture.height = height;
  15281. depthTexture.isReady = true;
  15282. depthTexture.samples = 1;
  15283. depthTexture.generateMipMaps = generateMipMaps;
  15284. depthTexture.samplingMode = gl.NEAREST;
  15285. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15286. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15287. textures.push(depthTexture);
  15288. this._internalTexturesCache.push(depthTexture);
  15289. }
  15290. gl.drawBuffers(attachments);
  15291. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15292. this.bindUnboundFramebuffer(null);
  15293. this.resetTextureCache();
  15294. return textures;
  15295. };
  15296. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15297. if (samples === void 0) { samples = 1; }
  15298. var depthStencilBuffer = null;
  15299. var gl = this._gl;
  15300. // Create the depth/stencil buffer
  15301. if (generateStencilBuffer) {
  15302. depthStencilBuffer = gl.createRenderbuffer();
  15303. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15304. if (samples > 1) {
  15305. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15306. }
  15307. else {
  15308. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15309. }
  15310. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15311. }
  15312. else if (generateDepthBuffer) {
  15313. depthStencilBuffer = gl.createRenderbuffer();
  15314. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15315. if (samples > 1) {
  15316. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15317. }
  15318. else {
  15319. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15320. }
  15321. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15322. }
  15323. return depthStencilBuffer;
  15324. };
  15325. /**
  15326. * Updates the sample count of a render target texture
  15327. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15328. * @param texture defines the texture to update
  15329. * @param samples defines the sample count to set
  15330. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15331. */
  15332. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15333. if (this.webGLVersion < 2 || !texture) {
  15334. return 1;
  15335. }
  15336. if (texture.samples === samples) {
  15337. return samples;
  15338. }
  15339. var gl = this._gl;
  15340. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15341. // Dispose previous render buffers
  15342. if (texture._depthStencilBuffer) {
  15343. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15344. texture._depthStencilBuffer = null;
  15345. }
  15346. if (texture._MSAAFramebuffer) {
  15347. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15348. texture._MSAAFramebuffer = null;
  15349. }
  15350. if (texture._MSAARenderBuffer) {
  15351. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15352. texture._MSAARenderBuffer = null;
  15353. }
  15354. if (samples > 1) {
  15355. var framebuffer = gl.createFramebuffer();
  15356. if (!framebuffer) {
  15357. throw new Error("Unable to create multi sampled framebuffer");
  15358. }
  15359. texture._MSAAFramebuffer = framebuffer;
  15360. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15361. var colorRenderbuffer = gl.createRenderbuffer();
  15362. if (!colorRenderbuffer) {
  15363. throw new Error("Unable to create multi sampled framebuffer");
  15364. }
  15365. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15366. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15367. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15368. texture._MSAARenderBuffer = colorRenderbuffer;
  15369. }
  15370. else {
  15371. this.bindUnboundFramebuffer(texture._framebuffer);
  15372. }
  15373. texture.samples = samples;
  15374. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15375. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15376. this.bindUnboundFramebuffer(null);
  15377. return samples;
  15378. };
  15379. /**
  15380. * Update the sample count for a given multiple render target texture
  15381. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15382. * @param textures defines the textures to update
  15383. * @param samples defines the sample count to set
  15384. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15385. */
  15386. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15387. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15388. return 1;
  15389. }
  15390. if (textures[0].samples === samples) {
  15391. return samples;
  15392. }
  15393. var gl = this._gl;
  15394. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15395. // Dispose previous render buffers
  15396. if (textures[0]._depthStencilBuffer) {
  15397. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15398. textures[0]._depthStencilBuffer = null;
  15399. }
  15400. if (textures[0]._MSAAFramebuffer) {
  15401. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15402. textures[0]._MSAAFramebuffer = null;
  15403. }
  15404. for (var i = 0; i < textures.length; i++) {
  15405. if (textures[i]._MSAARenderBuffer) {
  15406. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15407. textures[i]._MSAARenderBuffer = null;
  15408. }
  15409. }
  15410. if (samples > 1) {
  15411. var framebuffer = gl.createFramebuffer();
  15412. if (!framebuffer) {
  15413. throw new Error("Unable to create multi sampled framebuffer");
  15414. }
  15415. this.bindUnboundFramebuffer(framebuffer);
  15416. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15417. var attachments = [];
  15418. for (var i = 0; i < textures.length; i++) {
  15419. var texture = textures[i];
  15420. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15421. var colorRenderbuffer = gl.createRenderbuffer();
  15422. if (!colorRenderbuffer) {
  15423. throw new Error("Unable to create multi sampled framebuffer");
  15424. }
  15425. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15426. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15427. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15428. texture._MSAAFramebuffer = framebuffer;
  15429. texture._MSAARenderBuffer = colorRenderbuffer;
  15430. texture.samples = samples;
  15431. texture._depthStencilBuffer = depthStencilBuffer;
  15432. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15433. attachments.push(attachment);
  15434. }
  15435. gl.drawBuffers(attachments);
  15436. }
  15437. else {
  15438. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15439. }
  15440. this.bindUnboundFramebuffer(null);
  15441. return samples;
  15442. };
  15443. /** @hidden */
  15444. Engine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  15445. if (faceIndex === void 0) { faceIndex = 0; }
  15446. if (lod === void 0) { lod = 0; }
  15447. var gl = this._gl;
  15448. var target = gl.TEXTURE_2D;
  15449. if (texture.isCube) {
  15450. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15451. }
  15452. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15453. };
  15454. /** @hidden */
  15455. Engine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  15456. if (faceIndex === void 0) { faceIndex = 0; }
  15457. if (lod === void 0) { lod = 0; }
  15458. var gl = this._gl;
  15459. var textureType = this._getWebGLTextureType(texture.type);
  15460. var format = this._getInternalFormat(texture.format);
  15461. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15462. this._unpackFlipY(texture.invertY);
  15463. var target = gl.TEXTURE_2D;
  15464. if (texture.isCube) {
  15465. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15466. }
  15467. var lodMaxWidth = Math.round(BABYLON.Scalar.Log2(texture.width));
  15468. var lodMaxHeight = Math.round(BABYLON.Scalar.Log2(texture.height));
  15469. var width = Math.pow(2, Math.max(lodMaxWidth - lod, 0));
  15470. var height = Math.pow(2, Math.max(lodMaxHeight - lod, 0));
  15471. gl.texImage2D(target, lod, internalFormat, width, height, 0, format, textureType, imageData);
  15472. };
  15473. /** @hidden */
  15474. Engine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  15475. if (faceIndex === void 0) { faceIndex = 0; }
  15476. if (lod === void 0) { lod = 0; }
  15477. var gl = this._gl;
  15478. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15479. this._bindTextureDirectly(bindTarget, texture, true);
  15480. this._uploadDataToTextureDirectly(texture, imageData, faceIndex, lod);
  15481. this._bindTextureDirectly(bindTarget, null, true);
  15482. };
  15483. /** @hidden */
  15484. Engine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  15485. if (faceIndex === void 0) { faceIndex = 0; }
  15486. if (lod === void 0) { lod = 0; }
  15487. var gl = this._gl;
  15488. var textureType = this._getWebGLTextureType(texture.type);
  15489. var format = this._getInternalFormat(texture.format);
  15490. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15491. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15492. this._bindTextureDirectly(bindTarget, texture, true);
  15493. this._unpackFlipY(texture.invertY);
  15494. var target = gl.TEXTURE_2D;
  15495. if (texture.isCube) {
  15496. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15497. }
  15498. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  15499. this._bindTextureDirectly(bindTarget, null, true);
  15500. };
  15501. /**
  15502. * Creates a new render target cube texture
  15503. * @param size defines the size of the texture
  15504. * @param options defines the options used to create the texture
  15505. * @returns a new render target cube texture stored in an InternalTexture
  15506. */
  15507. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15508. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: Engine.TEXTURE_TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15509. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15510. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15511. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15512. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15513. }
  15514. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15515. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15516. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15517. }
  15518. var gl = this._gl;
  15519. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15520. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15521. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps);
  15522. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15523. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15524. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15525. }
  15526. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15527. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15528. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15529. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15530. for (var face = 0; face < 6; face++) {
  15531. 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);
  15532. }
  15533. // Create the framebuffer
  15534. var framebuffer = gl.createFramebuffer();
  15535. this.bindUnboundFramebuffer(framebuffer);
  15536. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15537. // MipMaps
  15538. if (fullOptions.generateMipMaps) {
  15539. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15540. }
  15541. // Unbind
  15542. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15543. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15544. this.bindUnboundFramebuffer(null);
  15545. texture._framebuffer = framebuffer;
  15546. texture.width = size;
  15547. texture.height = size;
  15548. texture.isReady = true;
  15549. texture.isCube = true;
  15550. texture.samples = 1;
  15551. texture.generateMipMaps = fullOptions.generateMipMaps;
  15552. texture.samplingMode = fullOptions.samplingMode;
  15553. texture.type = fullOptions.type;
  15554. texture.format = fullOptions.format;
  15555. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15556. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15557. this._internalTexturesCache.push(texture);
  15558. return texture;
  15559. };
  15560. /**
  15561. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15562. * @param rootUrl defines the url where the file to load is located
  15563. * @param scene defines the current scene
  15564. * @param lodScale defines scale to apply to the mip map selection
  15565. * @param lodOffset defines offset to apply to the mip map selection
  15566. * @param onLoad defines an optional callback raised when the texture is loaded
  15567. * @param onError defines an optional callback raised if there is an issue to load the texture
  15568. * @param format defines the format of the data
  15569. * @param forcedExtension defines the extension to use to pick the right loader
  15570. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  15571. * @returns the cube texture as an InternalTexture
  15572. */
  15573. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, createPolynomials) {
  15574. var _this = this;
  15575. if (onLoad === void 0) { onLoad = null; }
  15576. if (onError === void 0) { onError = null; }
  15577. if (forcedExtension === void 0) { forcedExtension = null; }
  15578. if (createPolynomials === void 0) { createPolynomials = true; }
  15579. var callback = function (loadData) {
  15580. if (!loadData) {
  15581. if (onLoad) {
  15582. onLoad(null);
  15583. }
  15584. return;
  15585. }
  15586. var texture = loadData.texture;
  15587. if (!createPolynomials) {
  15588. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15589. }
  15590. else if (loadData.info.sphericalPolynomial) {
  15591. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15592. }
  15593. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15594. if (_this._caps.textureLOD) {
  15595. // Do not add extra process if texture lod is supported.
  15596. if (onLoad) {
  15597. onLoad(texture);
  15598. }
  15599. return;
  15600. }
  15601. var mipSlices = 3;
  15602. var gl = _this._gl;
  15603. var width = loadData.width;
  15604. if (!width) {
  15605. return;
  15606. }
  15607. var textures = [];
  15608. for (var i = 0; i < mipSlices; i++) {
  15609. //compute LOD from even spacing in smoothness (matching shader calculation)
  15610. var smoothness = i / (mipSlices - 1);
  15611. var roughness = 1 - smoothness;
  15612. var minLODIndex = lodOffset; // roughness = 0
  15613. var maxLODIndex = BABYLON.Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
  15614. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15615. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15616. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15617. glTextureFromLod.type = texture.type;
  15618. glTextureFromLod.format = texture.format;
  15619. glTextureFromLod.width = Math.pow(2, Math.max(BABYLON.Scalar.Log2(width) - mipmapIndex, 0));
  15620. glTextureFromLod.height = glTextureFromLod.width;
  15621. glTextureFromLod.isCube = true;
  15622. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15623. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15624. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15625. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15626. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15627. if (loadData.isDDS) {
  15628. var info = loadData.info;
  15629. var data = loadData.data;
  15630. _this._unpackFlipY(info.isCompressed);
  15631. BABYLON.DDSTools.UploadDDSLevels(_this, glTextureFromLod, data, info, true, 6, mipmapIndex);
  15632. }
  15633. else {
  15634. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15635. }
  15636. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15637. // Wrap in a base texture for easy binding.
  15638. var lodTexture = new BABYLON.BaseTexture(scene);
  15639. lodTexture.isCube = true;
  15640. lodTexture._texture = glTextureFromLod;
  15641. glTextureFromLod.isReady = true;
  15642. textures.push(lodTexture);
  15643. }
  15644. texture._lodTextureHigh = textures[2];
  15645. texture._lodTextureMid = textures[1];
  15646. texture._lodTextureLow = textures[0];
  15647. if (onLoad) {
  15648. onLoad(texture);
  15649. }
  15650. };
  15651. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  15652. };
  15653. /**
  15654. * Creates a cube texture
  15655. * @param rootUrl defines the url where the files to load is located
  15656. * @param scene defines the current scene
  15657. * @param files defines the list of files to load (1 per face)
  15658. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15659. * @param onLoad defines an optional callback raised when the texture is loaded
  15660. * @param onError defines an optional callback raised if there is an issue to load the texture
  15661. * @param format defines the format of the data
  15662. * @param forcedExtension defines the extension to use to pick the right loader
  15663. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15664. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  15665. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  15666. * @param fallback defines texture to use while falling back when (compressed) texture file not found.
  15667. * @returns the cube texture as an InternalTexture
  15668. */
  15669. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback) {
  15670. var _this = this;
  15671. if (onLoad === void 0) { onLoad = null; }
  15672. if (onError === void 0) { onError = null; }
  15673. if (forcedExtension === void 0) { forcedExtension = null; }
  15674. if (createPolynomials === void 0) { createPolynomials = false; }
  15675. if (lodScale === void 0) { lodScale = 0; }
  15676. if (lodOffset === void 0) { lodOffset = 0; }
  15677. if (fallback === void 0) { fallback = null; }
  15678. var gl = this._gl;
  15679. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15680. texture.isCube = true;
  15681. texture.url = rootUrl;
  15682. texture.generateMipMaps = !noMipmap;
  15683. texture._lodGenerationScale = lodScale;
  15684. texture._lodGenerationOffset = lodOffset;
  15685. if (!this._doNotHandleContextLost) {
  15686. texture._extension = forcedExtension;
  15687. texture._files = files;
  15688. }
  15689. var lastDot = rootUrl.lastIndexOf('.');
  15690. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15691. var loader = null;
  15692. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  15693. var availableLoader = _a[_i];
  15694. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, false, false)) {
  15695. loader = availableLoader;
  15696. break;
  15697. }
  15698. }
  15699. var onInternalError = function (request, exception) {
  15700. if (loader) {
  15701. var fallbackUrl = loader.getFallbackTextureUrl(rootUrl, _this._textureFormatInUse);
  15702. if (fallbackUrl) {
  15703. _this.createCubeTexture(fallbackUrl, scene, files, noMipmap, onLoad, onError, format, extension, createPolynomials, lodScale, lodOffset, texture);
  15704. }
  15705. }
  15706. if (onError && request) {
  15707. onError(request.status + " " + request.statusText, exception);
  15708. }
  15709. };
  15710. if (loader) {
  15711. rootUrl = loader.transformUrl(rootUrl, this._textureFormatInUse);
  15712. var onloaddata = function (data) {
  15713. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15714. loader.loadCubeData(data, texture, createPolynomials, onLoad, onError);
  15715. };
  15716. if (files && files.length === 6) {
  15717. if (loader.supportCascades) {
  15718. this._cascadeLoadFiles(scene, onloaddata, files, onError);
  15719. }
  15720. else if (onError) {
  15721. onError("Textures type does not support cascades.");
  15722. }
  15723. }
  15724. else {
  15725. this._loadFile(rootUrl, onloaddata, undefined, undefined, true, onInternalError);
  15726. }
  15727. }
  15728. else {
  15729. if (!files) {
  15730. throw new Error("Cannot load cubemap because files were not defined");
  15731. }
  15732. this._cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15733. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15734. var height = width;
  15735. _this._prepareWorkingCanvas();
  15736. if (!_this._workingCanvas || !_this._workingContext) {
  15737. return;
  15738. }
  15739. _this._workingCanvas.width = width;
  15740. _this._workingCanvas.height = height;
  15741. var faces = [
  15742. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15743. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15744. ];
  15745. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15746. _this._unpackFlipY(false);
  15747. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15748. for (var index = 0; index < faces.length; index++) {
  15749. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15750. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15751. }
  15752. if (!noMipmap) {
  15753. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15754. }
  15755. _this._setCubeMapTextureParams(!noMipmap);
  15756. texture.width = width;
  15757. texture.height = height;
  15758. texture.isReady = true;
  15759. if (format) {
  15760. texture.format = format;
  15761. }
  15762. texture.onLoadedObservable.notifyObservers(texture);
  15763. texture.onLoadedObservable.clear();
  15764. if (onLoad) {
  15765. onLoad();
  15766. }
  15767. }, files, onError);
  15768. }
  15769. this._internalTexturesCache.push(texture);
  15770. return texture;
  15771. };
  15772. /**
  15773. * @hidden
  15774. */
  15775. Engine.prototype._setCubeMapTextureParams = function (loadMipmap) {
  15776. var gl = this._gl;
  15777. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15778. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15779. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15780. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15781. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15782. // this.resetTextureCache();
  15783. };
  15784. /**
  15785. * Update a raw cube texture
  15786. * @param texture defines the texture to udpdate
  15787. * @param data defines the data to store
  15788. * @param format defines the data format
  15789. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15790. * @param invertY defines if data must be stored with Y axis inverted
  15791. * @param compression defines the compression used (null by default)
  15792. * @param level defines which level of the texture to update
  15793. */
  15794. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15795. if (compression === void 0) { compression = null; }
  15796. if (level === void 0) { level = 0; }
  15797. texture._bufferViewArray = data;
  15798. texture.format = format;
  15799. texture.type = type;
  15800. texture.invertY = invertY;
  15801. texture._compression = compression;
  15802. var gl = this._gl;
  15803. var textureType = this._getWebGLTextureType(type);
  15804. var internalFormat = this._getInternalFormat(format);
  15805. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15806. var needConversion = false;
  15807. if (internalFormat === gl.RGB) {
  15808. internalFormat = gl.RGBA;
  15809. needConversion = true;
  15810. }
  15811. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15812. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15813. if (texture.width % 4 !== 0) {
  15814. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15815. }
  15816. // Data are known to be in +X +Y +Z -X -Y -Z
  15817. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15818. var faceData = data[faceIndex];
  15819. if (compression) {
  15820. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15821. }
  15822. else {
  15823. if (needConversion) {
  15824. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15825. }
  15826. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15827. }
  15828. }
  15829. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15830. if (isPot && texture.generateMipMaps && level === 0) {
  15831. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15832. }
  15833. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15834. // this.resetTextureCache();
  15835. texture.isReady = true;
  15836. };
  15837. /**
  15838. * Creates a new raw cube texture
  15839. * @param data defines the array of data to use to create each face
  15840. * @param size defines the size of the textures
  15841. * @param format defines the format of the data
  15842. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15843. * @param generateMipMaps defines if the engine should generate the mip levels
  15844. * @param invertY defines if data must be stored with Y axis inverted
  15845. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15846. * @param compression defines the compression used (null by default)
  15847. * @returns the cube texture as an InternalTexture
  15848. */
  15849. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  15850. if (compression === void 0) { compression = null; }
  15851. var gl = this._gl;
  15852. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  15853. texture.isCube = true;
  15854. texture.format = format;
  15855. texture.type = type;
  15856. if (!this._doNotHandleContextLost) {
  15857. texture._bufferViewArray = data;
  15858. }
  15859. var textureType = this._getWebGLTextureType(type);
  15860. var internalFormat = this._getInternalFormat(format);
  15861. if (internalFormat === gl.RGB) {
  15862. internalFormat = gl.RGBA;
  15863. }
  15864. // Mipmap generation needs a sized internal format that is both color-renderable and texture-filterable
  15865. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  15866. generateMipMaps = false;
  15867. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15868. BABYLON.Tools.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  15869. }
  15870. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  15871. generateMipMaps = false;
  15872. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15873. BABYLON.Tools.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  15874. }
  15875. else if (textureType === gl.FLOAT && !this._caps.textureFloatRender) {
  15876. generateMipMaps = false;
  15877. BABYLON.Tools.Warn("Render to float textures is not supported. Mipmap generation forced to false.");
  15878. }
  15879. else if (textureType === gl.HALF_FLOAT && !this._caps.colorBufferFloat) {
  15880. generateMipMaps = false;
  15881. BABYLON.Tools.Warn("Render to half float textures is not supported. Mipmap generation forced to false.");
  15882. }
  15883. var width = size;
  15884. var height = width;
  15885. texture.width = width;
  15886. texture.height = height;
  15887. // Double check on POT to generate Mips.
  15888. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15889. if (!isPot) {
  15890. generateMipMaps = false;
  15891. }
  15892. // Upload data if needed. The texture won't be ready until then.
  15893. if (data) {
  15894. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  15895. }
  15896. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15897. // Filters
  15898. if (data && generateMipMaps) {
  15899. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15900. }
  15901. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15902. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15903. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15904. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15905. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15906. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15907. texture.generateMipMaps = generateMipMaps;
  15908. return texture;
  15909. };
  15910. /**
  15911. * Creates a new raw cube texture from a specified url
  15912. * @param url defines the url where the data is located
  15913. * @param scene defines the current scene
  15914. * @param size defines the size of the textures
  15915. * @param format defines the format of the data
  15916. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15917. * @param noMipmap defines if the engine should avoid generating the mip levels
  15918. * @param callback defines a callback used to extract texture data from loaded data
  15919. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  15920. * @param onLoad defines a callback called when texture is loaded
  15921. * @param onError defines a callback called if there is an error
  15922. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15923. * @param invertY defines if data must be stored with Y axis inverted
  15924. * @returns the cube texture as an InternalTexture
  15925. */
  15926. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  15927. var _this = this;
  15928. if (onLoad === void 0) { onLoad = null; }
  15929. if (onError === void 0) { onError = null; }
  15930. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  15931. if (invertY === void 0) { invertY = false; }
  15932. var gl = this._gl;
  15933. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  15934. scene._addPendingData(texture);
  15935. texture.url = url;
  15936. this._internalTexturesCache.push(texture);
  15937. var onerror = function (request, exception) {
  15938. scene._removePendingData(texture);
  15939. if (onError && request) {
  15940. onError(request.status + " " + request.statusText, exception);
  15941. }
  15942. };
  15943. var internalCallback = function (data) {
  15944. var width = texture.width;
  15945. var faceDataArrays = callback(data);
  15946. if (!faceDataArrays) {
  15947. return;
  15948. }
  15949. if (mipmapGenerator) {
  15950. var textureType = _this._getWebGLTextureType(type);
  15951. var internalFormat = _this._getInternalFormat(format);
  15952. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  15953. var needConversion = false;
  15954. if (internalFormat === gl.RGB) {
  15955. internalFormat = gl.RGBA;
  15956. needConversion = true;
  15957. }
  15958. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15959. _this._unpackFlipY(false);
  15960. var mipData = mipmapGenerator(faceDataArrays);
  15961. for (var level = 0; level < mipData.length; level++) {
  15962. var mipSize = width >> level;
  15963. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15964. var mipFaceData = mipData[level][faceIndex];
  15965. if (needConversion) {
  15966. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  15967. }
  15968. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  15969. }
  15970. }
  15971. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15972. }
  15973. else {
  15974. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  15975. }
  15976. texture.isReady = true;
  15977. // this.resetTextureCache();
  15978. scene._removePendingData(texture);
  15979. if (onLoad) {
  15980. onLoad();
  15981. }
  15982. };
  15983. this._loadFile(url, function (data) {
  15984. internalCallback(data);
  15985. }, undefined, scene.database, true, onerror);
  15986. return texture;
  15987. };
  15988. ;
  15989. /**
  15990. * Update a raw 3D texture
  15991. * @param texture defines the texture to update
  15992. * @param data defines the data to store
  15993. * @param format defines the data format
  15994. * @param invertY defines if data must be stored with Y axis inverted
  15995. * @param compression defines the used compression (can be null)
  15996. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  15997. */
  15998. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {
  15999. if (compression === void 0) { compression = null; }
  16000. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16001. var internalType = this._getWebGLTextureType(textureType);
  16002. var internalFormat = this._getInternalFormat(format);
  16003. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  16004. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16005. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16006. if (!this._doNotHandleContextLost) {
  16007. texture._bufferView = data;
  16008. texture.format = format;
  16009. texture.invertY = invertY;
  16010. texture._compression = compression;
  16011. }
  16012. if (texture.width % 4 !== 0) {
  16013. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  16014. }
  16015. if (compression && data) {
  16016. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  16017. }
  16018. else {
  16019. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  16020. }
  16021. if (texture.generateMipMaps) {
  16022. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16023. }
  16024. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16025. // this.resetTextureCache();
  16026. texture.isReady = true;
  16027. };
  16028. /**
  16029. * Creates a new raw 3D texture
  16030. * @param data defines the data used to create the texture
  16031. * @param width defines the width of the texture
  16032. * @param height defines the height of the texture
  16033. * @param depth defines the depth of the texture
  16034. * @param format defines the format of the texture
  16035. * @param generateMipMaps defines if the engine must generate mip levels
  16036. * @param invertY defines if data must be stored with Y axis inverted
  16037. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16038. * @param compression defines the compressed used (can be null)
  16039. * @param textureType defines the compressed used (can be null)
  16040. * @returns a new raw 3D texture (stored in an InternalTexture)
  16041. */
  16042. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
  16043. if (compression === void 0) { compression = null; }
  16044. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16045. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  16046. texture.baseWidth = width;
  16047. texture.baseHeight = height;
  16048. texture.baseDepth = depth;
  16049. texture.width = width;
  16050. texture.height = height;
  16051. texture.depth = depth;
  16052. texture.format = format;
  16053. texture.type = textureType;
  16054. texture.generateMipMaps = generateMipMaps;
  16055. texture.samplingMode = samplingMode;
  16056. texture.is3D = true;
  16057. if (!this._doNotHandleContextLost) {
  16058. texture._bufferView = data;
  16059. }
  16060. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  16061. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16062. // Filters
  16063. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  16064. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  16065. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  16066. if (generateMipMaps) {
  16067. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16068. }
  16069. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16070. this._internalTexturesCache.push(texture);
  16071. return texture;
  16072. };
  16073. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  16074. var gl = this._gl;
  16075. if (!gl) {
  16076. return;
  16077. }
  16078. var filters = this._getSamplingParameters(samplingMode, !noMipmap);
  16079. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16080. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16081. if (!noMipmap && !isCompressed) {
  16082. gl.generateMipmap(gl.TEXTURE_2D);
  16083. }
  16084. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16085. // this.resetTextureCache();
  16086. if (scene) {
  16087. scene._removePendingData(texture);
  16088. }
  16089. texture.onLoadedObservable.notifyObservers(texture);
  16090. texture.onLoadedObservable.clear();
  16091. };
  16092. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16093. var _this = this;
  16094. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  16095. var maxTextureSize = this.getCaps().maxTextureSize;
  16096. var potWidth = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, maxTextureSize) : width);
  16097. var potHeight = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, maxTextureSize) : height);
  16098. var gl = this._gl;
  16099. if (!gl) {
  16100. return;
  16101. }
  16102. if (!texture._webGLTexture) {
  16103. // this.resetTextureCache();
  16104. if (scene) {
  16105. scene._removePendingData(texture);
  16106. }
  16107. return;
  16108. }
  16109. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16110. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16111. texture.baseWidth = width;
  16112. texture.baseHeight = height;
  16113. texture.width = potWidth;
  16114. texture.height = potHeight;
  16115. texture.isReady = true;
  16116. if (processFunction(potWidth, potHeight, function () {
  16117. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16118. })) {
  16119. // Returning as texture needs extra async steps
  16120. return;
  16121. }
  16122. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16123. };
  16124. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16125. // Create new RGBA data container.
  16126. var rgbaData;
  16127. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16128. rgbaData = new Float32Array(width * height * 4);
  16129. }
  16130. else {
  16131. rgbaData = new Uint32Array(width * height * 4);
  16132. }
  16133. // Convert each pixel.
  16134. for (var x = 0; x < width; x++) {
  16135. for (var y = 0; y < height; y++) {
  16136. var index = (y * width + x) * 3;
  16137. var newIndex = (y * width + x) * 4;
  16138. // Map Old Value to new value.
  16139. rgbaData[newIndex + 0] = rgbData[index + 0];
  16140. rgbaData[newIndex + 1] = rgbData[index + 1];
  16141. rgbaData[newIndex + 2] = rgbData[index + 2];
  16142. // Add fully opaque alpha channel.
  16143. rgbaData[newIndex + 3] = 1;
  16144. }
  16145. }
  16146. return rgbaData;
  16147. };
  16148. /** @hidden */
  16149. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16150. var gl = this._gl;
  16151. if (texture._framebuffer) {
  16152. gl.deleteFramebuffer(texture._framebuffer);
  16153. texture._framebuffer = null;
  16154. }
  16155. if (texture._depthStencilBuffer) {
  16156. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16157. texture._depthStencilBuffer = null;
  16158. }
  16159. if (texture._MSAAFramebuffer) {
  16160. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16161. texture._MSAAFramebuffer = null;
  16162. }
  16163. if (texture._MSAARenderBuffer) {
  16164. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16165. texture._MSAARenderBuffer = null;
  16166. }
  16167. };
  16168. /** @hidden */
  16169. Engine.prototype._releaseTexture = function (texture) {
  16170. var gl = this._gl;
  16171. this._releaseFramebufferObjects(texture);
  16172. gl.deleteTexture(texture._webGLTexture);
  16173. // Unbind channels
  16174. this.unbindAllTextures();
  16175. var index = this._internalTexturesCache.indexOf(texture);
  16176. if (index !== -1) {
  16177. this._internalTexturesCache.splice(index, 1);
  16178. }
  16179. // Integrated fixed lod samplers.
  16180. if (texture._lodTextureHigh) {
  16181. texture._lodTextureHigh.dispose();
  16182. }
  16183. if (texture._lodTextureMid) {
  16184. texture._lodTextureMid.dispose();
  16185. }
  16186. if (texture._lodTextureLow) {
  16187. texture._lodTextureLow.dispose();
  16188. }
  16189. // Set output texture of post process to null if the texture has been released/disposed
  16190. this.scenes.forEach(function (scene) {
  16191. scene.postProcesses.forEach(function (postProcess) {
  16192. if (postProcess._outputTexture == texture) {
  16193. postProcess._outputTexture = null;
  16194. }
  16195. });
  16196. scene.cameras.forEach(function (camera) {
  16197. camera._postProcesses.forEach(function (postProcess) {
  16198. if (postProcess) {
  16199. if (postProcess._outputTexture == texture) {
  16200. postProcess._outputTexture = null;
  16201. }
  16202. }
  16203. });
  16204. });
  16205. });
  16206. };
  16207. Engine.prototype.setProgram = function (program) {
  16208. if (this._currentProgram !== program) {
  16209. this._gl.useProgram(program);
  16210. this._currentProgram = program;
  16211. }
  16212. };
  16213. /**
  16214. * Binds an effect to the webGL context
  16215. * @param effect defines the effect to bind
  16216. */
  16217. Engine.prototype.bindSamplers = function (effect) {
  16218. this.setProgram(effect.getProgram());
  16219. var samplers = effect.getSamplers();
  16220. for (var index = 0; index < samplers.length; index++) {
  16221. var uniform = effect.getUniform(samplers[index]);
  16222. if (uniform) {
  16223. this._boundUniforms[index] = uniform;
  16224. }
  16225. }
  16226. this._currentEffect = null;
  16227. };
  16228. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16229. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16230. return;
  16231. }
  16232. // Remove
  16233. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16234. // Bind last to it
  16235. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16236. // Bind to dummy
  16237. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16238. };
  16239. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16240. if (!internalTexture) {
  16241. return -1;
  16242. }
  16243. internalTexture._initialSlot = channel;
  16244. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16245. if (channel !== internalTexture._designatedSlot) {
  16246. this._textureCollisions.addCount(1, false);
  16247. }
  16248. }
  16249. else {
  16250. if (channel !== internalTexture._designatedSlot) {
  16251. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16252. return internalTexture._designatedSlot;
  16253. }
  16254. else {
  16255. // No slot for this texture, let's pick a new one (if we find a free slot)
  16256. if (this._nextFreeTextureSlots.length) {
  16257. return this._nextFreeTextureSlots[0];
  16258. }
  16259. // We need to recycle the oldest bound texture, sorry.
  16260. this._textureCollisions.addCount(1, false);
  16261. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16262. }
  16263. }
  16264. }
  16265. return channel;
  16266. };
  16267. Engine.prototype._linkTrackers = function (previous, next) {
  16268. previous.next = next;
  16269. next.previous = previous;
  16270. };
  16271. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16272. var currentSlot = internalTexture._designatedSlot;
  16273. if (currentSlot === -1) {
  16274. return -1;
  16275. }
  16276. internalTexture._designatedSlot = -1;
  16277. if (this.disableTextureBindingOptimization) {
  16278. return -1;
  16279. }
  16280. // Remove from bound list
  16281. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16282. // Free the slot
  16283. this._boundTexturesCache[currentSlot] = null;
  16284. this._nextFreeTextureSlots.push(currentSlot);
  16285. return currentSlot;
  16286. };
  16287. Engine.prototype._activateCurrentTexture = function () {
  16288. if (this._currentTextureChannel !== this._activeChannel) {
  16289. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16290. this._currentTextureChannel = this._activeChannel;
  16291. }
  16292. };
  16293. /** @hidden */
  16294. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16295. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16296. if (force === void 0) { force = false; }
  16297. var wasPreviouslyBound = false;
  16298. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16299. this._activeChannel = texture._designatedSlot;
  16300. }
  16301. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16302. var isTextureForRendering = texture && texture._initialSlot > -1;
  16303. if (currentTextureBound !== texture || force) {
  16304. if (currentTextureBound) {
  16305. this._removeDesignatedSlot(currentTextureBound);
  16306. }
  16307. this._activateCurrentTexture();
  16308. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16309. this._boundTexturesCache[this._activeChannel] = texture;
  16310. if (texture) {
  16311. if (!this.disableTextureBindingOptimization) {
  16312. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16313. if (slotIndex > -1) {
  16314. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16315. }
  16316. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16317. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16318. }
  16319. texture._designatedSlot = this._activeChannel;
  16320. }
  16321. }
  16322. else if (forTextureDataUpdate) {
  16323. wasPreviouslyBound = true;
  16324. this._activateCurrentTexture();
  16325. }
  16326. if (isTextureForRendering && !forTextureDataUpdate) {
  16327. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16328. }
  16329. return wasPreviouslyBound;
  16330. };
  16331. /** @hidden */
  16332. Engine.prototype._bindTexture = function (channel, texture) {
  16333. if (channel < 0) {
  16334. return;
  16335. }
  16336. if (texture) {
  16337. channel = this._getCorrectTextureChannel(channel, texture);
  16338. }
  16339. this._activeChannel = channel;
  16340. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16341. };
  16342. /**
  16343. * Sets a texture to the webGL context from a postprocess
  16344. * @param channel defines the channel to use
  16345. * @param postProcess defines the source postprocess
  16346. */
  16347. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16348. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16349. };
  16350. /**
  16351. * Binds the output of the passed in post process to the texture channel specified
  16352. * @param channel The channel the texture should be bound to
  16353. * @param postProcess The post process which's output should be bound
  16354. */
  16355. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16356. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16357. };
  16358. /**
  16359. * Unbind all textures from the webGL context
  16360. */
  16361. Engine.prototype.unbindAllTextures = function () {
  16362. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16363. this._activeChannel = channel;
  16364. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16365. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16366. if (this.webGLVersion > 1) {
  16367. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16368. }
  16369. }
  16370. };
  16371. /**
  16372. * Sets a texture to the according uniform.
  16373. * @param channel The texture channel
  16374. * @param uniform The uniform to set
  16375. * @param texture The texture to apply
  16376. */
  16377. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16378. if (channel < 0) {
  16379. return;
  16380. }
  16381. if (uniform) {
  16382. this._boundUniforms[channel] = uniform;
  16383. }
  16384. this._setTexture(channel, texture);
  16385. };
  16386. /**
  16387. * Sets a depth stencil texture from a render target to the according uniform.
  16388. * @param channel The texture channel
  16389. * @param uniform The uniform to set
  16390. * @param texture The render target texture containing the depth stencil texture to apply
  16391. */
  16392. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16393. if (channel < 0) {
  16394. return;
  16395. }
  16396. if (uniform) {
  16397. this._boundUniforms[channel] = uniform;
  16398. }
  16399. if (!texture || !texture.depthStencilTexture) {
  16400. this._setTexture(channel, null);
  16401. }
  16402. else {
  16403. this._setTexture(channel, texture, false, true);
  16404. }
  16405. };
  16406. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16407. var uniform = this._boundUniforms[sourceSlot];
  16408. if (uniform._currentState === destination) {
  16409. return;
  16410. }
  16411. this._gl.uniform1i(uniform, destination);
  16412. uniform._currentState = destination;
  16413. };
  16414. Engine.prototype._getTextureWrapMode = function (mode) {
  16415. switch (mode) {
  16416. case Engine.TEXTURE_WRAP_ADDRESSMODE:
  16417. return this._gl.REPEAT;
  16418. case Engine.TEXTURE_CLAMP_ADDRESSMODE:
  16419. return this._gl.CLAMP_TO_EDGE;
  16420. case Engine.TEXTURE_MIRROR_ADDRESSMODE:
  16421. return this._gl.MIRRORED_REPEAT;
  16422. }
  16423. return this._gl.REPEAT;
  16424. };
  16425. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16426. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16427. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16428. // Not ready?
  16429. if (!texture) {
  16430. if (this._boundTexturesCache[channel] != null) {
  16431. this._activeChannel = channel;
  16432. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16433. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16434. if (this.webGLVersion > 1) {
  16435. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16436. }
  16437. }
  16438. return false;
  16439. }
  16440. // Video
  16441. if (texture.video) {
  16442. this._activeChannel = channel;
  16443. texture.update();
  16444. }
  16445. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16446. texture.delayLoad();
  16447. return false;
  16448. }
  16449. var internalTexture;
  16450. if (depthStencilTexture) {
  16451. internalTexture = texture.depthStencilTexture;
  16452. }
  16453. else if (texture.isReady()) {
  16454. internalTexture = texture.getInternalTexture();
  16455. }
  16456. else if (texture.isCube) {
  16457. internalTexture = this.emptyCubeTexture;
  16458. }
  16459. else if (texture.is3D) {
  16460. internalTexture = this.emptyTexture3D;
  16461. }
  16462. else {
  16463. internalTexture = this.emptyTexture;
  16464. }
  16465. if (!isPartOfTextureArray) {
  16466. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16467. }
  16468. var needToBind = true;
  16469. if (this._boundTexturesCache[channel] === internalTexture) {
  16470. this._moveBoundTextureOnTop(internalTexture);
  16471. if (!isPartOfTextureArray) {
  16472. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16473. }
  16474. needToBind = false;
  16475. }
  16476. this._activeChannel = channel;
  16477. if (internalTexture && internalTexture.is3D) {
  16478. if (needToBind) {
  16479. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16480. }
  16481. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16482. internalTexture._cachedWrapU = texture.wrapU;
  16483. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16484. }
  16485. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16486. internalTexture._cachedWrapV = texture.wrapV;
  16487. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16488. }
  16489. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16490. internalTexture._cachedWrapR = texture.wrapR;
  16491. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16492. }
  16493. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16494. }
  16495. else if (internalTexture && internalTexture.isCube) {
  16496. if (needToBind) {
  16497. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16498. }
  16499. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16500. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16501. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16502. var textureWrapMode = (texture.coordinatesMode !== Engine.TEXTURE_CUBIC_MODE && texture.coordinatesMode !== Engine.TEXTURE_SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16503. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16504. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16505. }
  16506. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16507. }
  16508. else {
  16509. if (needToBind) {
  16510. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16511. }
  16512. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16513. internalTexture._cachedWrapU = texture.wrapU;
  16514. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16515. }
  16516. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16517. internalTexture._cachedWrapV = texture.wrapV;
  16518. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16519. }
  16520. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16521. }
  16522. return true;
  16523. };
  16524. /**
  16525. * Sets an array of texture to the webGL context
  16526. * @param channel defines the channel where the texture array must be set
  16527. * @param uniform defines the associated uniform location
  16528. * @param textures defines the array of textures to bind
  16529. */
  16530. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16531. if (channel < 0 || !uniform) {
  16532. return;
  16533. }
  16534. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16535. this._textureUnits = new Int32Array(textures.length);
  16536. }
  16537. for (var i = 0; i < textures.length; i++) {
  16538. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16539. }
  16540. this._gl.uniform1iv(uniform, this._textureUnits);
  16541. for (var index = 0; index < textures.length; index++) {
  16542. this._setTexture(this._textureUnits[index], textures[index], true);
  16543. }
  16544. };
  16545. /** @hidden */
  16546. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16547. var internalTexture = texture.getInternalTexture();
  16548. if (!internalTexture) {
  16549. return;
  16550. }
  16551. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16552. var value = texture.anisotropicFilteringLevel;
  16553. if (internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST
  16554. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR
  16555. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR) {
  16556. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16557. }
  16558. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16559. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16560. internalTexture._cachedAnisotropicFilteringLevel = value;
  16561. }
  16562. };
  16563. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16564. this._bindTextureDirectly(target, texture, true, true);
  16565. this._gl.texParameterf(target, parameter, value);
  16566. };
  16567. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16568. if (texture) {
  16569. this._bindTextureDirectly(target, texture, true, true);
  16570. }
  16571. this._gl.texParameteri(target, parameter, value);
  16572. };
  16573. /**
  16574. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16575. * @param x defines the x coordinate of the rectangle where pixels must be read
  16576. * @param y defines the y coordinate of the rectangle where pixels must be read
  16577. * @param width defines the width of the rectangle where pixels must be read
  16578. * @param height defines the height of the rectangle where pixels must be read
  16579. * @returns a Uint8Array containing RGBA colors
  16580. */
  16581. Engine.prototype.readPixels = function (x, y, width, height) {
  16582. var data = new Uint8Array(height * width * 4);
  16583. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16584. return data;
  16585. };
  16586. /**
  16587. * Add an externaly attached data from its key.
  16588. * This method call will fail and return false, if such key already exists.
  16589. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16590. * @param key the unique key that identifies the data
  16591. * @param data the data object to associate to the key for this Engine instance
  16592. * @return true if no such key were already present and the data was added successfully, false otherwise
  16593. */
  16594. Engine.prototype.addExternalData = function (key, data) {
  16595. if (!this._externalData) {
  16596. this._externalData = new BABYLON.StringDictionary();
  16597. }
  16598. return this._externalData.add(key, data);
  16599. };
  16600. /**
  16601. * Get an externaly attached data from its key
  16602. * @param key the unique key that identifies the data
  16603. * @return the associated data, if present (can be null), or undefined if not present
  16604. */
  16605. Engine.prototype.getExternalData = function (key) {
  16606. if (!this._externalData) {
  16607. this._externalData = new BABYLON.StringDictionary();
  16608. }
  16609. return this._externalData.get(key);
  16610. };
  16611. /**
  16612. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16613. * @param key the unique key that identifies the data
  16614. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16615. * @return the associated data, can be null if the factory returned null.
  16616. */
  16617. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16618. if (!this._externalData) {
  16619. this._externalData = new BABYLON.StringDictionary();
  16620. }
  16621. return this._externalData.getOrAddWithFactory(key, factory);
  16622. };
  16623. /**
  16624. * Remove an externaly attached data from the Engine instance
  16625. * @param key the unique key that identifies the data
  16626. * @return true if the data was successfully removed, false if it doesn't exist
  16627. */
  16628. Engine.prototype.removeExternalData = function (key) {
  16629. if (!this._externalData) {
  16630. this._externalData = new BABYLON.StringDictionary();
  16631. }
  16632. return this._externalData.remove(key);
  16633. };
  16634. /**
  16635. * Unbind all vertex attributes from the webGL context
  16636. */
  16637. Engine.prototype.unbindAllAttributes = function () {
  16638. if (this._mustWipeVertexAttributes) {
  16639. this._mustWipeVertexAttributes = false;
  16640. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16641. this._gl.disableVertexAttribArray(i);
  16642. this._vertexAttribArraysEnabled[i] = false;
  16643. this._currentBufferPointers[i].active = false;
  16644. }
  16645. return;
  16646. }
  16647. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16648. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16649. continue;
  16650. }
  16651. this._gl.disableVertexAttribArray(i);
  16652. this._vertexAttribArraysEnabled[i] = false;
  16653. this._currentBufferPointers[i].active = false;
  16654. }
  16655. };
  16656. /**
  16657. * 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
  16658. */
  16659. Engine.prototype.releaseEffects = function () {
  16660. for (var name in this._compiledEffects) {
  16661. this._deleteProgram(this._compiledEffects[name]._program);
  16662. }
  16663. this._compiledEffects = {};
  16664. };
  16665. /**
  16666. * Dispose and release all associated resources
  16667. */
  16668. Engine.prototype.dispose = function () {
  16669. this.hideLoadingUI();
  16670. this.stopRenderLoop();
  16671. // Release postProcesses
  16672. while (this.postProcesses.length) {
  16673. this.postProcesses[0].dispose();
  16674. }
  16675. // Empty texture
  16676. if (this._emptyTexture) {
  16677. this._releaseTexture(this._emptyTexture);
  16678. this._emptyTexture = null;
  16679. }
  16680. if (this._emptyCubeTexture) {
  16681. this._releaseTexture(this._emptyCubeTexture);
  16682. this._emptyCubeTexture = null;
  16683. }
  16684. // Rescale PP
  16685. if (this._rescalePostProcess) {
  16686. this._rescalePostProcess.dispose();
  16687. }
  16688. // Release scenes
  16689. while (this.scenes.length) {
  16690. this.scenes[0].dispose();
  16691. }
  16692. // Release audio engine
  16693. if (Engine.audioEngine) {
  16694. Engine.audioEngine.dispose();
  16695. }
  16696. // Release effects
  16697. this.releaseEffects();
  16698. // Unbind
  16699. this.unbindAllAttributes();
  16700. this._boundUniforms = [];
  16701. if (this._dummyFramebuffer) {
  16702. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16703. }
  16704. //WebVR
  16705. this.disableVR();
  16706. // Events
  16707. if (BABYLON.Tools.IsWindowObjectExist()) {
  16708. window.removeEventListener("blur", this._onBlur);
  16709. window.removeEventListener("focus", this._onFocus);
  16710. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16711. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16712. if (this._renderingCanvas) {
  16713. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16714. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16715. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16716. if (!this._doNotHandleContextLost) {
  16717. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16718. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16719. }
  16720. }
  16721. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16722. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16723. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16724. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16725. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16726. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16727. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16728. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16729. if (this._onVrDisplayConnect) {
  16730. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16731. if (this._onVrDisplayDisconnect) {
  16732. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16733. }
  16734. if (this._onVrDisplayPresentChange) {
  16735. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16736. }
  16737. this._onVrDisplayConnect = null;
  16738. this._onVrDisplayDisconnect = null;
  16739. }
  16740. }
  16741. // Remove from Instances
  16742. var index = Engine.Instances.indexOf(this);
  16743. if (index >= 0) {
  16744. Engine.Instances.splice(index, 1);
  16745. }
  16746. this._workingCanvas = null;
  16747. this._workingContext = null;
  16748. this._currentBufferPointers = [];
  16749. this._renderingCanvas = null;
  16750. this._currentProgram = null;
  16751. this._bindedRenderFunction = null;
  16752. this.onResizeObservable.clear();
  16753. this.onCanvasBlurObservable.clear();
  16754. this.onCanvasFocusObservable.clear();
  16755. this.onCanvasPointerOutObservable.clear();
  16756. this.onBeginFrameObservable.clear();
  16757. this.onEndFrameObservable.clear();
  16758. BABYLON.Effect.ResetCache();
  16759. // Abort active requests
  16760. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16761. var request = _a[_i];
  16762. request.abort();
  16763. }
  16764. };
  16765. // Loading screen
  16766. /**
  16767. * Display the loading screen
  16768. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16769. */
  16770. Engine.prototype.displayLoadingUI = function () {
  16771. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16772. return;
  16773. }
  16774. var loadingScreen = this.loadingScreen;
  16775. if (loadingScreen) {
  16776. loadingScreen.displayLoadingUI();
  16777. }
  16778. };
  16779. /**
  16780. * Hide the loading screen
  16781. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16782. */
  16783. Engine.prototype.hideLoadingUI = function () {
  16784. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16785. return;
  16786. }
  16787. var loadingScreen = this.loadingScreen;
  16788. if (loadingScreen) {
  16789. loadingScreen.hideLoadingUI();
  16790. }
  16791. };
  16792. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16793. /**
  16794. * Gets the current loading screen object
  16795. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16796. */
  16797. get: function () {
  16798. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16799. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16800. return this._loadingScreen;
  16801. },
  16802. /**
  16803. * Sets the current loading screen object
  16804. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16805. */
  16806. set: function (loadingScreen) {
  16807. this._loadingScreen = loadingScreen;
  16808. },
  16809. enumerable: true,
  16810. configurable: true
  16811. });
  16812. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16813. /**
  16814. * Sets the current loading screen text
  16815. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16816. */
  16817. set: function (text) {
  16818. this.loadingScreen.loadingUIText = text;
  16819. },
  16820. enumerable: true,
  16821. configurable: true
  16822. });
  16823. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16824. /**
  16825. * Sets the current loading screen background color
  16826. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16827. */
  16828. set: function (color) {
  16829. this.loadingScreen.loadingUIBackgroundColor = color;
  16830. },
  16831. enumerable: true,
  16832. configurable: true
  16833. });
  16834. /**
  16835. * Attach a new callback raised when context lost event is fired
  16836. * @param callback defines the callback to call
  16837. */
  16838. Engine.prototype.attachContextLostEvent = function (callback) {
  16839. if (this._renderingCanvas) {
  16840. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  16841. }
  16842. };
  16843. /**
  16844. * Attach a new callback raised when context restored event is fired
  16845. * @param callback defines the callback to call
  16846. */
  16847. Engine.prototype.attachContextRestoredEvent = function (callback) {
  16848. if (this._renderingCanvas) {
  16849. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  16850. }
  16851. };
  16852. /**
  16853. * Gets the source code of the vertex shader associated with a specific webGL program
  16854. * @param program defines the program to use
  16855. * @returns a string containing the source code of the vertex shader associated with the program
  16856. */
  16857. Engine.prototype.getVertexShaderSource = function (program) {
  16858. var shaders = this._gl.getAttachedShaders(program);
  16859. if (!shaders) {
  16860. return null;
  16861. }
  16862. return this._gl.getShaderSource(shaders[0]);
  16863. };
  16864. /**
  16865. * Gets the source code of the fragment shader associated with a specific webGL program
  16866. * @param program defines the program to use
  16867. * @returns a string containing the source code of the fragment shader associated with the program
  16868. */
  16869. Engine.prototype.getFragmentShaderSource = function (program) {
  16870. var shaders = this._gl.getAttachedShaders(program);
  16871. if (!shaders) {
  16872. return null;
  16873. }
  16874. return this._gl.getShaderSource(shaders[1]);
  16875. };
  16876. /**
  16877. * Get the current error code of the webGL context
  16878. * @returns the error code
  16879. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  16880. */
  16881. Engine.prototype.getError = function () {
  16882. return this._gl.getError();
  16883. };
  16884. // FPS
  16885. /**
  16886. * Gets the current framerate
  16887. * @returns a number representing the framerate
  16888. */
  16889. Engine.prototype.getFps = function () {
  16890. return this._fps;
  16891. };
  16892. /**
  16893. * Gets the time spent between current and previous frame
  16894. * @returns a number representing the delta time in ms
  16895. */
  16896. Engine.prototype.getDeltaTime = function () {
  16897. return this._deltaTime;
  16898. };
  16899. Engine.prototype._measureFps = function () {
  16900. this._performanceMonitor.sampleFrame();
  16901. this._fps = this._performanceMonitor.averageFPS;
  16902. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  16903. };
  16904. /** @hidden */
  16905. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, level) {
  16906. if (faceIndex === void 0) { faceIndex = -1; }
  16907. if (level === void 0) { level = 0; }
  16908. var gl = this._gl;
  16909. if (!this._dummyFramebuffer) {
  16910. var dummy = gl.createFramebuffer();
  16911. if (!dummy) {
  16912. throw new Error("Unable to create dummy framebuffer");
  16913. }
  16914. this._dummyFramebuffer = dummy;
  16915. }
  16916. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  16917. if (faceIndex > -1) {
  16918. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
  16919. }
  16920. else {
  16921. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
  16922. }
  16923. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  16924. var buffer;
  16925. switch (readType) {
  16926. case gl.UNSIGNED_BYTE:
  16927. buffer = new Uint8Array(4 * width * height);
  16928. readType = gl.UNSIGNED_BYTE;
  16929. break;
  16930. default:
  16931. buffer = new Float32Array(4 * width * height);
  16932. readType = gl.FLOAT;
  16933. break;
  16934. }
  16935. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  16936. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  16937. return buffer;
  16938. };
  16939. Engine.prototype._canRenderToFloatFramebuffer = function () {
  16940. if (this._webGLVersion > 1) {
  16941. return this._caps.colorBufferFloat;
  16942. }
  16943. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  16944. };
  16945. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  16946. if (this._webGLVersion > 1) {
  16947. return this._caps.colorBufferFloat;
  16948. }
  16949. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  16950. };
  16951. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  16952. Engine.prototype._canRenderToFramebuffer = function (type) {
  16953. var gl = this._gl;
  16954. //clear existing errors
  16955. while (gl.getError() !== gl.NO_ERROR) { }
  16956. var successful = true;
  16957. var texture = gl.createTexture();
  16958. gl.bindTexture(gl.TEXTURE_2D, texture);
  16959. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  16960. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16961. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16962. var fb = gl.createFramebuffer();
  16963. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  16964. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  16965. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  16966. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  16967. successful = successful && (gl.getError() === gl.NO_ERROR);
  16968. //try render by clearing frame buffer's color buffer
  16969. if (successful) {
  16970. gl.clear(gl.COLOR_BUFFER_BIT);
  16971. successful = successful && (gl.getError() === gl.NO_ERROR);
  16972. }
  16973. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  16974. if (successful) {
  16975. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  16976. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16977. var readFormat = gl.RGBA;
  16978. var readType = gl.UNSIGNED_BYTE;
  16979. var buffer = new Uint8Array(4);
  16980. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  16981. successful = successful && (gl.getError() === gl.NO_ERROR);
  16982. }
  16983. //clean up
  16984. gl.deleteTexture(texture);
  16985. gl.deleteFramebuffer(fb);
  16986. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16987. //clear accumulated errors
  16988. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  16989. return successful;
  16990. };
  16991. /** @hidden */
  16992. Engine.prototype._getWebGLTextureType = function (type) {
  16993. if (this._webGLVersion === 1) {
  16994. switch (type) {
  16995. case Engine.TEXTURETYPE_FLOAT:
  16996. return this._gl.FLOAT;
  16997. case Engine.TEXTURETYPE_HALF_FLOAT:
  16998. return this._gl.HALF_FLOAT_OES;
  16999. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17000. return this._gl.UNSIGNED_BYTE;
  17001. }
  17002. return this._gl.UNSIGNED_BYTE;
  17003. }
  17004. switch (type) {
  17005. case Engine.TEXTURETYPE_BYTE:
  17006. return this._gl.BYTE;
  17007. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17008. return this._gl.UNSIGNED_BYTE;
  17009. case Engine.TEXTURETYPE_SHORT:
  17010. return this._gl.SHORT;
  17011. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  17012. return this._gl.UNSIGNED_SHORT;
  17013. case Engine.TEXTURETYPE_INT:
  17014. return this._gl.INT;
  17015. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  17016. return this._gl.UNSIGNED_INT;
  17017. case Engine.TEXTURETYPE_FLOAT:
  17018. return this._gl.FLOAT;
  17019. case Engine.TEXTURETYPE_HALF_FLOAT:
  17020. return this._gl.HALF_FLOAT;
  17021. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  17022. return this._gl.UNSIGNED_SHORT_4_4_4_4;
  17023. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  17024. return this._gl.UNSIGNED_SHORT_5_5_5_1;
  17025. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  17026. return this._gl.UNSIGNED_SHORT_5_6_5;
  17027. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  17028. return this._gl.UNSIGNED_INT_2_10_10_10_REV;
  17029. case Engine.TEXTURETYPE_UNSIGNED_INT_24_8:
  17030. return this._gl.UNSIGNED_INT_24_8;
  17031. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  17032. return this._gl.UNSIGNED_INT_10F_11F_11F_REV;
  17033. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  17034. return this._gl.UNSIGNED_INT_5_9_9_9_REV;
  17035. case Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV:
  17036. return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV;
  17037. }
  17038. return this._gl.UNSIGNED_BYTE;
  17039. };
  17040. ;
  17041. Engine.prototype._getInternalFormat = function (format) {
  17042. var internalFormat = this._gl.RGBA;
  17043. switch (format) {
  17044. case Engine.TEXTUREFORMAT_ALPHA:
  17045. internalFormat = this._gl.ALPHA;
  17046. break;
  17047. case Engine.TEXTUREFORMAT_LUMINANCE:
  17048. internalFormat = this._gl.LUMINANCE;
  17049. break;
  17050. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17051. internalFormat = this._gl.LUMINANCE_ALPHA;
  17052. break;
  17053. case Engine.TEXTUREFORMAT_RED:
  17054. internalFormat = this._gl.RED;
  17055. break;
  17056. case Engine.TEXTUREFORMAT_RG:
  17057. internalFormat = this._gl.RG;
  17058. break;
  17059. case Engine.TEXTUREFORMAT_RGB:
  17060. internalFormat = this._gl.RGB;
  17061. break;
  17062. case Engine.TEXTUREFORMAT_RGBA:
  17063. internalFormat = this._gl.RGBA;
  17064. break;
  17065. }
  17066. if (this._webGLVersion > 1) {
  17067. switch (format) {
  17068. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17069. internalFormat = this._gl.RED_INTEGER;
  17070. break;
  17071. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17072. internalFormat = this._gl.RG_INTEGER;
  17073. break;
  17074. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17075. internalFormat = this._gl.RGB_INTEGER;
  17076. break;
  17077. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17078. internalFormat = this._gl.RGBA_INTEGER;
  17079. break;
  17080. }
  17081. }
  17082. return internalFormat;
  17083. };
  17084. /** @hidden */
  17085. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  17086. if (this._webGLVersion === 1) {
  17087. if (format !== undefined) {
  17088. switch (format) {
  17089. case Engine.TEXTUREFORMAT_ALPHA:
  17090. return this._gl.ALPHA;
  17091. case Engine.TEXTUREFORMAT_LUMINANCE:
  17092. return this._gl.LUMINANCE;
  17093. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17094. return this._gl.LUMINANCE_ALPHA;
  17095. }
  17096. }
  17097. return this._gl.RGBA;
  17098. }
  17099. switch (type) {
  17100. case Engine.TEXTURETYPE_BYTE:
  17101. switch (format) {
  17102. case Engine.TEXTUREFORMAT_RED:
  17103. return this._gl.R8_SNORM;
  17104. case Engine.TEXTUREFORMAT_RG:
  17105. return this._gl.RG8_SNORM;
  17106. case Engine.TEXTUREFORMAT_RGB:
  17107. return this._gl.RGB8_SNORM;
  17108. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17109. return this._gl.R8I;
  17110. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17111. return this._gl.RG8I;
  17112. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17113. return this._gl.RGB8I;
  17114. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17115. return this._gl.RGBA8I;
  17116. default:
  17117. return this._gl.RGBA8_SNORM;
  17118. }
  17119. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17120. switch (format) {
  17121. case Engine.TEXTUREFORMAT_RED:
  17122. return this._gl.R8;
  17123. case Engine.TEXTUREFORMAT_RG:
  17124. return this._gl.RG8;
  17125. case Engine.TEXTUREFORMAT_RGB:
  17126. return this._gl.RGB8; // By default. Other possibilities are RGB565, SRGB8.
  17127. case Engine.TEXTUREFORMAT_RGBA:
  17128. return this._gl.RGBA8; // By default. Other possibilities are RGB5_A1, RGBA4, SRGB8_ALPHA8.
  17129. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17130. return this._gl.R8UI;
  17131. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17132. return this._gl.RG8UI;
  17133. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17134. return this._gl.RGB8UI;
  17135. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17136. return this._gl.RGBA8UI;
  17137. default:
  17138. return this._gl.RGBA8;
  17139. }
  17140. case Engine.TEXTURETYPE_SHORT:
  17141. switch (format) {
  17142. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17143. return this._gl.R16I;
  17144. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17145. return this._gl.RG16I;
  17146. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17147. return this._gl.RGB16I;
  17148. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17149. return this._gl.RGBA16I;
  17150. default:
  17151. return this._gl.RGBA16I;
  17152. }
  17153. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  17154. switch (format) {
  17155. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17156. return this._gl.R16UI;
  17157. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17158. return this._gl.RG16UI;
  17159. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17160. return this._gl.RGB16UI;
  17161. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17162. return this._gl.RGBA16UI;
  17163. default:
  17164. return this._gl.RGBA16UI;
  17165. }
  17166. case Engine.TEXTURETYPE_INT:
  17167. switch (format) {
  17168. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17169. return this._gl.R32I;
  17170. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17171. return this._gl.RG32I;
  17172. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17173. return this._gl.RGB32I;
  17174. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17175. return this._gl.RGBA32I;
  17176. default:
  17177. return this._gl.RGBA32I;
  17178. }
  17179. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  17180. switch (format) {
  17181. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17182. return this._gl.R32UI;
  17183. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17184. return this._gl.RG32UI;
  17185. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17186. return this._gl.RGB32UI;
  17187. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17188. return this._gl.RGBA32UI;
  17189. default:
  17190. return this._gl.RGBA32UI;
  17191. }
  17192. case Engine.TEXTURETYPE_FLOAT:
  17193. switch (format) {
  17194. case Engine.TEXTUREFORMAT_RED:
  17195. return this._gl.R32F; // By default. Other possibility is R16F.
  17196. case Engine.TEXTUREFORMAT_RG:
  17197. return this._gl.RG32F; // By default. Other possibility is RG16F.
  17198. case Engine.TEXTUREFORMAT_RGB:
  17199. return this._gl.RGB32F; // By default. Other possibilities are RGB16F, R11F_G11F_B10F, RGB9_E5.
  17200. case Engine.TEXTUREFORMAT_RGBA:
  17201. return this._gl.RGBA32F; // By default. Other possibility is RGBA16F.
  17202. default:
  17203. return this._gl.RGBA32F;
  17204. }
  17205. case Engine.TEXTURETYPE_HALF_FLOAT:
  17206. switch (format) {
  17207. case Engine.TEXTUREFORMAT_RED:
  17208. return this._gl.R16F;
  17209. case Engine.TEXTUREFORMAT_RG:
  17210. return this._gl.RG16F;
  17211. case Engine.TEXTUREFORMAT_RGB:
  17212. return this._gl.RGB16F; // By default. Other possibilities are R11F_G11F_B10F, RGB9_E5.
  17213. case Engine.TEXTUREFORMAT_RGBA:
  17214. return this._gl.RGBA16F;
  17215. default:
  17216. return this._gl.RGBA16F;
  17217. }
  17218. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  17219. return this._gl.RGB565;
  17220. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  17221. return this._gl.R11F_G11F_B10F;
  17222. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  17223. return this._gl.RGB9_E5;
  17224. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  17225. return this._gl.RGBA4;
  17226. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  17227. return this._gl.RGB5_A1;
  17228. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  17229. switch (format) {
  17230. case Engine.TEXTUREFORMAT_RGBA:
  17231. return this._gl.RGB10_A2; // By default. Other possibility is RGB5_A1.
  17232. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17233. return this._gl.RGB10_A2UI;
  17234. default:
  17235. return this._gl.RGB10_A2;
  17236. }
  17237. }
  17238. return this._gl.RGBA8;
  17239. };
  17240. ;
  17241. /** @hidden */
  17242. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  17243. if (type === Engine.TEXTURETYPE_FLOAT) {
  17244. return this._gl.RGBA32F;
  17245. }
  17246. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17247. return this._gl.RGBA16F;
  17248. }
  17249. return this._gl.RGBA8;
  17250. };
  17251. ;
  17252. /** @hidden */
  17253. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17254. var _this = this;
  17255. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17256. this._activeRequests.push(request);
  17257. request.onCompleteObservable.add(function (request) {
  17258. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17259. });
  17260. return request;
  17261. };
  17262. /** @hidden */
  17263. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17264. var _this = this;
  17265. return new Promise(function (resolve, reject) {
  17266. _this._loadFile(url, function (data) {
  17267. resolve(data);
  17268. }, undefined, database, useArrayBuffer, function (request, exception) {
  17269. reject(exception);
  17270. });
  17271. });
  17272. };
  17273. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17274. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17275. var onload = function (data) {
  17276. loadedFiles[index] = data;
  17277. loadedFiles._internalCount++;
  17278. if (loadedFiles._internalCount === 6) {
  17279. onfinish(loadedFiles);
  17280. }
  17281. };
  17282. var onerror = function (request, exception) {
  17283. if (onErrorCallBack && request) {
  17284. onErrorCallBack(request.status + " " + request.statusText, exception);
  17285. }
  17286. };
  17287. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17288. };
  17289. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17290. if (onError === void 0) { onError = null; }
  17291. var loadedFiles = [];
  17292. loadedFiles._internalCount = 0;
  17293. for (var index = 0; index < 6; index++) {
  17294. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17295. }
  17296. };
  17297. // Statics
  17298. /**
  17299. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17300. * @returns true if the engine can be created
  17301. * @ignorenaming
  17302. */
  17303. Engine.isSupported = function () {
  17304. try {
  17305. var tempcanvas = document.createElement("canvas");
  17306. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17307. return gl != null && !!window.WebGLRenderingContext;
  17308. }
  17309. catch (e) {
  17310. return false;
  17311. }
  17312. };
  17313. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17314. Engine.ExceptionList = [
  17315. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17316. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17317. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17318. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17319. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17320. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17321. ];
  17322. /** Gets the list of created engines */
  17323. Engine.Instances = new Array();
  17324. /**
  17325. * Hidden
  17326. */
  17327. Engine._TextureLoaders = [];
  17328. // Const statics
  17329. /** Defines that alpha blending is disabled */
  17330. Engine.ALPHA_DISABLE = 0;
  17331. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  17332. Engine.ALPHA_ADD = 1;
  17333. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  17334. Engine.ALPHA_COMBINE = 2;
  17335. /** Defines that alpha blending to DEST - SRC * DEST */
  17336. Engine.ALPHA_SUBTRACT = 3;
  17337. /** Defines that alpha blending to SRC * DEST */
  17338. Engine.ALPHA_MULTIPLY = 4;
  17339. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  17340. Engine.ALPHA_MAXIMIZED = 5;
  17341. /** Defines that alpha blending to SRC + DEST */
  17342. Engine.ALPHA_ONEONE = 6;
  17343. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  17344. Engine.ALPHA_PREMULTIPLIED = 7;
  17345. /**
  17346. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  17347. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  17348. */
  17349. Engine.ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17350. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  17351. Engine.ALPHA_INTERPOLATE = 9;
  17352. /**
  17353. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  17354. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  17355. */
  17356. Engine.ALPHA_SCREENMODE = 10;
  17357. /** Defines that the ressource is not delayed*/
  17358. Engine.DELAYLOADSTATE_NONE = 0;
  17359. /** Defines that the ressource was successfully delay loaded */
  17360. Engine.DELAYLOADSTATE_LOADED = 1;
  17361. /** Defines that the ressource is currently delay loading */
  17362. Engine.DELAYLOADSTATE_LOADING = 2;
  17363. /** Defines that the ressource is delayed and has not started loading */
  17364. Engine.DELAYLOADSTATE_NOTLOADED = 4;
  17365. // Depht or Stencil test Constants.
  17366. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  17367. Engine.NEVER = 0x0200;
  17368. /** 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 */
  17369. Engine.ALWAYS = 0x0207;
  17370. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  17371. Engine.LESS = 0x0201;
  17372. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  17373. Engine.EQUAL = 0x0202;
  17374. /** 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 */
  17375. Engine.LEQUAL = 0x0203;
  17376. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  17377. Engine.GREATER = 0x0204;
  17378. /** 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 */
  17379. Engine.GEQUAL = 0x0206;
  17380. /** 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 */
  17381. Engine.NOTEQUAL = 0x0205;
  17382. // Stencil Actions Constants.
  17383. /** Passed to stencilOperation to specify that stencil value must be kept */
  17384. Engine.KEEP = 0x1E00;
  17385. /** Passed to stencilOperation to specify that stencil value must be replaced */
  17386. Engine.REPLACE = 0x1E01;
  17387. /** Passed to stencilOperation to specify that stencil value must be incremented */
  17388. Engine.INCR = 0x1E02;
  17389. /** Passed to stencilOperation to specify that stencil value must be decremented */
  17390. Engine.DECR = 0x1E03;
  17391. /** Passed to stencilOperation to specify that stencil value must be inverted */
  17392. Engine.INVERT = 0x150A;
  17393. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  17394. Engine.INCR_WRAP = 0x8507;
  17395. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  17396. Engine.DECR_WRAP = 0x8508;
  17397. /** Texture is not repeating outside of 0..1 UVs */
  17398. Engine.TEXTURE_CLAMP_ADDRESSMODE = 0;
  17399. /** Texture is repeating outside of 0..1 UVs */
  17400. Engine.TEXTURE_WRAP_ADDRESSMODE = 1;
  17401. /** Texture is repeating and mirrored */
  17402. Engine.TEXTURE_MIRROR_ADDRESSMODE = 2;
  17403. /** ALPHA */
  17404. Engine.TEXTUREFORMAT_ALPHA = 0;
  17405. /** LUMINANCE */
  17406. Engine.TEXTUREFORMAT_LUMINANCE = 1;
  17407. /** LUMINANCE_ALPHA */
  17408. Engine.TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17409. /** RGB */
  17410. Engine.TEXTUREFORMAT_RGB = 4;
  17411. /** RGBA */
  17412. Engine.TEXTUREFORMAT_RGBA = 5;
  17413. /** RED */
  17414. Engine.TEXTUREFORMAT_RED = 6;
  17415. /** RED (2nd reference) */
  17416. Engine.TEXTUREFORMAT_R = 6;
  17417. /** RG */
  17418. Engine.TEXTUREFORMAT_RG = 7;
  17419. /** RED_INTEGER */
  17420. Engine.TEXTUREFORMAT_RED_INTEGER = 8;
  17421. /** RED_INTEGER (2nd reference) */
  17422. Engine.TEXTUREFORMAT_R_INTEGER = 8;
  17423. /** RG_INTEGER */
  17424. Engine.TEXTUREFORMAT_RG_INTEGER = 9;
  17425. /** RGB_INTEGER */
  17426. Engine.TEXTUREFORMAT_RGB_INTEGER = 10;
  17427. /** RGBA_INTEGER */
  17428. Engine.TEXTUREFORMAT_RGBA_INTEGER = 11;
  17429. /** UNSIGNED_BYTE */
  17430. Engine.TEXTURETYPE_UNSIGNED_BYTE = 0;
  17431. /** UNSIGNED_BYTE (2nd reference) */
  17432. Engine.TEXTURETYPE_UNSIGNED_INT = 0;
  17433. /** FLOAT */
  17434. Engine.TEXTURETYPE_FLOAT = 1;
  17435. /** HALF_FLOAT */
  17436. Engine.TEXTURETYPE_HALF_FLOAT = 2;
  17437. /** BYTE */
  17438. Engine.TEXTURETYPE_BYTE = 3;
  17439. /** SHORT */
  17440. Engine.TEXTURETYPE_SHORT = 4;
  17441. /** UNSIGNED_SHORT */
  17442. Engine.TEXTURETYPE_UNSIGNED_SHORT = 5;
  17443. /** INT */
  17444. Engine.TEXTURETYPE_INT = 6;
  17445. /** UNSIGNED_INT */
  17446. Engine.TEXTURETYPE_UNSIGNED_INTEGER = 7;
  17447. /** UNSIGNED_SHORT_4_4_4_4 */
  17448. Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 = 8;
  17449. /** UNSIGNED_SHORT_5_5_5_1 */
  17450. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 = 9;
  17451. /** UNSIGNED_SHORT_5_6_5 */
  17452. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5 = 10;
  17453. /** UNSIGNED_INT_2_10_10_10_REV */
  17454. Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV = 11;
  17455. /** UNSIGNED_INT_24_8 */
  17456. Engine.TEXTURETYPE_UNSIGNED_INT_24_8 = 12;
  17457. /** UNSIGNED_INT_10F_11F_11F_REV */
  17458. Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV = 13;
  17459. /** UNSIGNED_INT_5_9_9_9_REV */
  17460. Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV = 14;
  17461. /** FLOAT_32_UNSIGNED_INT_24_8_REV */
  17462. Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV = 15;
  17463. /** nearest is mag = nearest and min = nearest and mip = linear */
  17464. Engine.TEXTURE_NEAREST_SAMPLINGMODE = 1;
  17465. /** Bilinear is mag = linear and min = linear and mip = nearest */
  17466. Engine.TEXTURE_BILINEAR_SAMPLINGMODE = 2;
  17467. /** Trilinear is mag = linear and min = linear and mip = linear */
  17468. Engine.TEXTURE_TRILINEAR_SAMPLINGMODE = 3;
  17469. /** nearest is mag = nearest and min = nearest and mip = linear */
  17470. Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR = 1;
  17471. /** Bilinear is mag = linear and min = linear and mip = nearest */
  17472. Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST = 2;
  17473. /** Trilinear is mag = linear and min = linear and mip = linear */
  17474. Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR = 3;
  17475. /** mag = nearest and min = nearest and mip = nearest */
  17476. Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST = 4;
  17477. /** mag = nearest and min = linear and mip = nearest */
  17478. Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST = 5;
  17479. /** mag = nearest and min = linear and mip = linear */
  17480. Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR = 6;
  17481. /** mag = nearest and min = linear and mip = none */
  17482. Engine.TEXTURE_NEAREST_LINEAR = 7;
  17483. /** mag = nearest and min = nearest and mip = none */
  17484. Engine.TEXTURE_NEAREST_NEAREST = 8;
  17485. /** mag = linear and min = nearest and mip = nearest */
  17486. Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST = 9;
  17487. /** mag = linear and min = nearest and mip = linear */
  17488. Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR = 10;
  17489. /** mag = linear and min = linear and mip = none */
  17490. Engine.TEXTURE_LINEAR_LINEAR = 11;
  17491. /** mag = linear and min = nearest and mip = none */
  17492. Engine.TEXTURE_LINEAR_NEAREST = 12;
  17493. /** Explicit coordinates mode */
  17494. Engine.TEXTURE_EXPLICIT_MODE = 0;
  17495. /** Spherical coordinates mode */
  17496. Engine.TEXTURE_SPHERICAL_MODE = 1;
  17497. /** Planar coordinates mode */
  17498. Engine.TEXTURE_PLANAR_MODE = 2;
  17499. /** Cubic coordinates mode */
  17500. Engine.TEXTURE_CUBIC_MODE = 3;
  17501. /** Projection coordinates mode */
  17502. Engine.TEXTURE_PROJECTION_MODE = 4;
  17503. /** Skybox coordinates mode */
  17504. Engine.TEXTURE_SKYBOX_MODE = 5;
  17505. /** Inverse Cubic coordinates mode */
  17506. Engine.TEXTURE_INVCUBIC_MODE = 6;
  17507. /** Equirectangular coordinates mode */
  17508. Engine.TEXTURE_EQUIRECTANGULAR_MODE = 7;
  17509. /** Equirectangular Fixed coordinates mode */
  17510. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE = 8;
  17511. /** Equirectangular Fixed Mirrored coordinates mode */
  17512. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  17513. // Texture rescaling mode
  17514. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  17515. Engine.SCALEMODE_FLOOR = 1;
  17516. /** Defines that texture rescaling will look for the nearest power of 2 size */
  17517. Engine.SCALEMODE_NEAREST = 2;
  17518. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  17519. Engine.SCALEMODE_CEILING = 3;
  17520. // Updatable statics so stick with vars here
  17521. /**
  17522. * Gets or sets the epsilon value used by collision engine
  17523. */
  17524. Engine.CollisionsEpsilon = 0.001;
  17525. /**
  17526. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17527. */
  17528. Engine.CodeRepository = "src/";
  17529. /**
  17530. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17531. */
  17532. Engine.ShadersRepository = "src/Shaders/";
  17533. return Engine;
  17534. }());
  17535. BABYLON.Engine = Engine;
  17536. })(BABYLON || (BABYLON = {}));
  17537. //# sourceMappingURL=babylon.engine.js.map
  17538. var BABYLON;
  17539. (function (BABYLON) {
  17540. /**
  17541. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17542. */
  17543. var Node = /** @class */ (function () {
  17544. /**
  17545. * Creates a new Node
  17546. * @param {string} name - the name and id to be given to this node
  17547. * @param {BABYLON.Scene} the scene this node will be added to
  17548. */
  17549. function Node(name, scene) {
  17550. if (scene === void 0) { scene = null; }
  17551. /**
  17552. * Gets or sets a string used to store user defined state for the node
  17553. */
  17554. this.state = "";
  17555. /**
  17556. * Gets or sets an object used to store user defined information for the node
  17557. */
  17558. this.metadata = null;
  17559. /**
  17560. * Gets or sets a boolean used to define if the node must be serialized
  17561. */
  17562. this.doNotSerialize = false;
  17563. /** @hidden */
  17564. this._isDisposed = false;
  17565. /**
  17566. * Gets a list of Animations associated with the node
  17567. */
  17568. this.animations = new Array();
  17569. this._ranges = {};
  17570. this._isEnabled = true;
  17571. this._isReady = true;
  17572. /** @hidden */
  17573. this._currentRenderId = -1;
  17574. this._parentRenderId = -1;
  17575. this._childRenderId = -1;
  17576. this._animationPropertiesOverride = null;
  17577. /**
  17578. * An event triggered when the mesh is disposed
  17579. */
  17580. this.onDisposeObservable = new BABYLON.Observable();
  17581. // Behaviors
  17582. this._behaviors = new Array();
  17583. this.name = name;
  17584. this.id = name;
  17585. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17586. this.uniqueId = this._scene.getUniqueId();
  17587. this._initCache();
  17588. this._scene.rootNodes.push(this);
  17589. }
  17590. /**
  17591. * Add a new node constructor
  17592. * @param type defines the type name of the node to construct
  17593. * @param constructorFunc defines the constructor function
  17594. */
  17595. Node.AddNodeConstructor = function (type, constructorFunc) {
  17596. this._NodeConstructors[type] = constructorFunc;
  17597. };
  17598. /**
  17599. * Returns a node constructor based on type name
  17600. * @param type defines the type name
  17601. * @param name defines the new node name
  17602. * @param scene defines the hosting scene
  17603. * @param options defines optional options to transmit to constructors
  17604. * @returns the new constructor or null
  17605. */
  17606. Node.Construct = function (type, name, scene, options) {
  17607. var constructorFunc = this._NodeConstructors[type];
  17608. if (!constructorFunc) {
  17609. return null;
  17610. }
  17611. return constructorFunc(name, scene, options);
  17612. };
  17613. /**
  17614. * Gets a boolean indicating if the node has been disposed
  17615. * @returns true if the node was disposed
  17616. */
  17617. Node.prototype.isDisposed = function () {
  17618. return this._isDisposed;
  17619. };
  17620. Object.defineProperty(Node.prototype, "parent", {
  17621. get: function () {
  17622. return this._parentNode;
  17623. },
  17624. /**
  17625. * Gets or sets the parent of the node
  17626. */
  17627. set: function (parent) {
  17628. if (this._parentNode === parent) {
  17629. return;
  17630. }
  17631. var previousParentNode = this._parentNode;
  17632. // Remove self from list of children of parent
  17633. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17634. var index = this._parentNode._children.indexOf(this);
  17635. if (index !== -1) {
  17636. this._parentNode._children.splice(index, 1);
  17637. }
  17638. if (!parent) {
  17639. // Need to add this node to the rootNodes
  17640. this._scene.rootNodes.push(this);
  17641. }
  17642. }
  17643. // Store new parent
  17644. this._parentNode = parent;
  17645. // Add as child to new parent
  17646. if (this._parentNode) {
  17647. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17648. this._parentNode._children = new Array();
  17649. }
  17650. this._parentNode._children.push(this);
  17651. if (!previousParentNode) {
  17652. // Need to remove from rootNodes
  17653. var rootNodeIndex = this._scene.rootNodes.indexOf(this);
  17654. if (rootNodeIndex > -1) {
  17655. this._scene.rootNodes.splice(rootNodeIndex, 1);
  17656. }
  17657. }
  17658. }
  17659. },
  17660. enumerable: true,
  17661. configurable: true
  17662. });
  17663. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17664. /**
  17665. * Gets or sets the animation properties override
  17666. */
  17667. get: function () {
  17668. if (!this._animationPropertiesOverride) {
  17669. return this._scene.animationPropertiesOverride;
  17670. }
  17671. return this._animationPropertiesOverride;
  17672. },
  17673. set: function (value) {
  17674. this._animationPropertiesOverride = value;
  17675. },
  17676. enumerable: true,
  17677. configurable: true
  17678. });
  17679. /**
  17680. * Gets a string idenfifying the name of the class
  17681. * @returns "Node" string
  17682. */
  17683. Node.prototype.getClassName = function () {
  17684. return "Node";
  17685. };
  17686. Object.defineProperty(Node.prototype, "onDispose", {
  17687. /**
  17688. * Sets a callback that will be raised when the node will be disposed
  17689. */
  17690. set: function (callback) {
  17691. if (this._onDisposeObserver) {
  17692. this.onDisposeObservable.remove(this._onDisposeObserver);
  17693. }
  17694. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17695. },
  17696. enumerable: true,
  17697. configurable: true
  17698. });
  17699. /**
  17700. * Gets the scene of the node
  17701. * @returns a {BABYLON.Scene}
  17702. */
  17703. Node.prototype.getScene = function () {
  17704. return this._scene;
  17705. };
  17706. /**
  17707. * Gets the engine of the node
  17708. * @returns a {BABYLON.Engine}
  17709. */
  17710. Node.prototype.getEngine = function () {
  17711. return this._scene.getEngine();
  17712. };
  17713. /**
  17714. * Attach a behavior to the node
  17715. * @see http://doc.babylonjs.com/features/behaviour
  17716. * @param behavior defines the behavior to attach
  17717. * @returns the current Node
  17718. */
  17719. Node.prototype.addBehavior = function (behavior) {
  17720. var _this = this;
  17721. var index = this._behaviors.indexOf(behavior);
  17722. if (index !== -1) {
  17723. return this;
  17724. }
  17725. behavior.init();
  17726. if (this._scene.isLoading) {
  17727. // We defer the attach when the scene will be loaded
  17728. this._scene.onDataLoadedObservable.addOnce(function () {
  17729. behavior.attach(_this);
  17730. });
  17731. }
  17732. else {
  17733. behavior.attach(this);
  17734. }
  17735. this._behaviors.push(behavior);
  17736. return this;
  17737. };
  17738. /**
  17739. * Remove an attached behavior
  17740. * @see http://doc.babylonjs.com/features/behaviour
  17741. * @param behavior defines the behavior to attach
  17742. * @returns the current Node
  17743. */
  17744. Node.prototype.removeBehavior = function (behavior) {
  17745. var index = this._behaviors.indexOf(behavior);
  17746. if (index === -1) {
  17747. return this;
  17748. }
  17749. this._behaviors[index].detach();
  17750. this._behaviors.splice(index, 1);
  17751. return this;
  17752. };
  17753. Object.defineProperty(Node.prototype, "behaviors", {
  17754. /**
  17755. * Gets the list of attached behaviors
  17756. * @see http://doc.babylonjs.com/features/behaviour
  17757. */
  17758. get: function () {
  17759. return this._behaviors;
  17760. },
  17761. enumerable: true,
  17762. configurable: true
  17763. });
  17764. /**
  17765. * Gets an attached behavior by name
  17766. * @param name defines the name of the behavior to look for
  17767. * @see http://doc.babylonjs.com/features/behaviour
  17768. * @returns null if behavior was not found else the requested behavior
  17769. */
  17770. Node.prototype.getBehaviorByName = function (name) {
  17771. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17772. var behavior = _a[_i];
  17773. if (behavior.name === name) {
  17774. return behavior;
  17775. }
  17776. }
  17777. return null;
  17778. };
  17779. /**
  17780. * Returns the world matrix of the node
  17781. * @returns a matrix containing the node's world matrix
  17782. */
  17783. Node.prototype.getWorldMatrix = function () {
  17784. return BABYLON.Matrix.Identity();
  17785. };
  17786. /** @hidden */
  17787. Node.prototype._getWorldMatrixDeterminant = function () {
  17788. return 1;
  17789. };
  17790. // override it in derived class if you add new variables to the cache
  17791. // and call the parent class method
  17792. /** @hidden */
  17793. Node.prototype._initCache = function () {
  17794. this._cache = {};
  17795. this._cache.parent = undefined;
  17796. };
  17797. /** @hidden */
  17798. Node.prototype.updateCache = function (force) {
  17799. if (!force && this.isSynchronized())
  17800. return;
  17801. this._cache.parent = this.parent;
  17802. this._updateCache();
  17803. };
  17804. // override it in derived class if you add new variables to the cache
  17805. // and call the parent class method if !ignoreParentClass
  17806. /** @hidden */
  17807. Node.prototype._updateCache = function (ignoreParentClass) {
  17808. };
  17809. // override it in derived class if you add new variables to the cache
  17810. /** @hidden */
  17811. Node.prototype._isSynchronized = function () {
  17812. return true;
  17813. };
  17814. /** @hidden */
  17815. Node.prototype._markSyncedWithParent = function () {
  17816. if (this.parent) {
  17817. this._parentRenderId = this.parent._childRenderId;
  17818. }
  17819. };
  17820. /** @hidden */
  17821. Node.prototype.isSynchronizedWithParent = function () {
  17822. if (!this.parent) {
  17823. return true;
  17824. }
  17825. if (this._parentRenderId !== this.parent._childRenderId) {
  17826. return false;
  17827. }
  17828. return this.parent.isSynchronized();
  17829. };
  17830. /** @hidden */
  17831. Node.prototype.isSynchronized = function (updateCache) {
  17832. var check = this.hasNewParent();
  17833. check = check || !this.isSynchronizedWithParent();
  17834. check = check || !this._isSynchronized();
  17835. if (updateCache)
  17836. this.updateCache(true);
  17837. return !check;
  17838. };
  17839. /** @hidden */
  17840. Node.prototype.hasNewParent = function () {
  17841. if (this._cache.parent === this.parent)
  17842. return false;
  17843. this._cache.parent = this.parent;
  17844. return true;
  17845. };
  17846. /**
  17847. * Is this node ready to be used/rendered
  17848. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17849. * @return true if the node is ready
  17850. */
  17851. Node.prototype.isReady = function (completeCheck) {
  17852. if (completeCheck === void 0) { completeCheck = false; }
  17853. return this._isReady;
  17854. };
  17855. /**
  17856. * Is this node enabled?
  17857. * 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
  17858. * @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
  17859. * @return whether this node (and its parent) is enabled
  17860. */
  17861. Node.prototype.isEnabled = function (checkAncestors) {
  17862. if (checkAncestors === void 0) { checkAncestors = true; }
  17863. if (checkAncestors === false) {
  17864. return this._isEnabled;
  17865. }
  17866. if (this._isEnabled === false) {
  17867. return false;
  17868. }
  17869. if (this.parent !== undefined && this.parent !== null) {
  17870. return this.parent.isEnabled(checkAncestors);
  17871. }
  17872. return true;
  17873. };
  17874. /**
  17875. * Set the enabled state of this node
  17876. * @param value defines the new enabled state
  17877. */
  17878. Node.prototype.setEnabled = function (value) {
  17879. this._isEnabled = value;
  17880. };
  17881. /**
  17882. * Is this node a descendant of the given node?
  17883. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  17884. * @param ancestor defines the parent node to inspect
  17885. * @returns a boolean indicating if this node is a descendant of the given node
  17886. */
  17887. Node.prototype.isDescendantOf = function (ancestor) {
  17888. if (this.parent) {
  17889. if (this.parent === ancestor) {
  17890. return true;
  17891. }
  17892. return this.parent.isDescendantOf(ancestor);
  17893. }
  17894. return false;
  17895. };
  17896. /** @hidden */
  17897. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  17898. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  17899. if (!this._children) {
  17900. return;
  17901. }
  17902. for (var index = 0; index < this._children.length; index++) {
  17903. var item = this._children[index];
  17904. if (!predicate || predicate(item)) {
  17905. results.push(item);
  17906. }
  17907. if (!directDescendantsOnly) {
  17908. item._getDescendants(results, false, predicate);
  17909. }
  17910. }
  17911. };
  17912. /**
  17913. * Will return all nodes that have this node as ascendant
  17914. * @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
  17915. * @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
  17916. * @return all children nodes of all types
  17917. */
  17918. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  17919. var results = new Array();
  17920. this._getDescendants(results, directDescendantsOnly, predicate);
  17921. return results;
  17922. };
  17923. /**
  17924. * Get all child-meshes of this node
  17925. * @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
  17926. * @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
  17927. * @returns an array of {BABYLON.AbstractMesh}
  17928. */
  17929. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  17930. var results = [];
  17931. this._getDescendants(results, directDescendantsOnly, function (node) {
  17932. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  17933. });
  17934. return results;
  17935. };
  17936. /**
  17937. * Get all child-transformNodes of this node
  17938. * @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
  17939. * @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
  17940. * @returns an array of {BABYLON.TransformNode}
  17941. */
  17942. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  17943. var results = [];
  17944. this._getDescendants(results, directDescendantsOnly, function (node) {
  17945. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  17946. });
  17947. return results;
  17948. };
  17949. /**
  17950. * Get all direct children of this node
  17951. * @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
  17952. * @returns an array of {BABYLON.Node}
  17953. */
  17954. Node.prototype.getChildren = function (predicate) {
  17955. if (!predicate) {
  17956. return this._children;
  17957. }
  17958. return this.getDescendants(true, predicate);
  17959. };
  17960. /** @hidden */
  17961. Node.prototype._setReady = function (state) {
  17962. if (state === this._isReady) {
  17963. return;
  17964. }
  17965. if (!state) {
  17966. this._isReady = false;
  17967. return;
  17968. }
  17969. if (this.onReady) {
  17970. this.onReady(this);
  17971. }
  17972. this._isReady = true;
  17973. };
  17974. /**
  17975. * Get an animation by name
  17976. * @param name defines the name of the animation to look for
  17977. * @returns null if not found else the requested animation
  17978. */
  17979. Node.prototype.getAnimationByName = function (name) {
  17980. for (var i = 0; i < this.animations.length; i++) {
  17981. var animation = this.animations[i];
  17982. if (animation.name === name) {
  17983. return animation;
  17984. }
  17985. }
  17986. return null;
  17987. };
  17988. /**
  17989. * Creates an animation range for this node
  17990. * @param name defines the name of the range
  17991. * @param from defines the starting key
  17992. * @param to defines the end key
  17993. */
  17994. Node.prototype.createAnimationRange = function (name, from, to) {
  17995. // check name not already in use
  17996. if (!this._ranges[name]) {
  17997. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  17998. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17999. if (this.animations[i]) {
  18000. this.animations[i].createRange(name, from, to);
  18001. }
  18002. }
  18003. }
  18004. };
  18005. /**
  18006. * Delete a specific animation range
  18007. * @param name defines the name of the range to delete
  18008. * @param deleteFrames defines if animation frames from the range must be deleted as well
  18009. */
  18010. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  18011. if (deleteFrames === void 0) { deleteFrames = true; }
  18012. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18013. if (this.animations[i]) {
  18014. this.animations[i].deleteRange(name, deleteFrames);
  18015. }
  18016. }
  18017. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  18018. };
  18019. /**
  18020. * Get an animation range by name
  18021. * @param name defines the name of the animation range to look for
  18022. * @returns null if not found else the requested animation range
  18023. */
  18024. Node.prototype.getAnimationRange = function (name) {
  18025. return this._ranges[name];
  18026. };
  18027. /**
  18028. * Will start the animation sequence
  18029. * @param name defines the range frames for animation sequence
  18030. * @param loop defines if the animation should loop (false by default)
  18031. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  18032. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  18033. * @returns the object created for this animation. If range does not exist, it will return null
  18034. */
  18035. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  18036. var range = this.getAnimationRange(name);
  18037. if (!range) {
  18038. return null;
  18039. }
  18040. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  18041. };
  18042. /**
  18043. * Serialize animation ranges into a JSON compatible object
  18044. * @returns serialization object
  18045. */
  18046. Node.prototype.serializeAnimationRanges = function () {
  18047. var serializationRanges = [];
  18048. for (var name in this._ranges) {
  18049. var localRange = this._ranges[name];
  18050. if (!localRange) {
  18051. continue;
  18052. }
  18053. var range = {};
  18054. range.name = name;
  18055. range.from = localRange.from;
  18056. range.to = localRange.to;
  18057. serializationRanges.push(range);
  18058. }
  18059. return serializationRanges;
  18060. };
  18061. /**
  18062. * Computes the world matrix of the node
  18063. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  18064. * @returns the world matrix
  18065. */
  18066. Node.prototype.computeWorldMatrix = function (force) {
  18067. return BABYLON.Matrix.Identity();
  18068. };
  18069. /**
  18070. * Releases resources associated with this node.
  18071. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18072. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18073. */
  18074. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18075. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18076. if (!doNotRecurse) {
  18077. var nodes = this.getDescendants(true);
  18078. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  18079. var node = nodes_1[_i];
  18080. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  18081. }
  18082. }
  18083. else {
  18084. var transformNodes = this.getChildTransformNodes(true);
  18085. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  18086. var transformNode = transformNodes_1[_a];
  18087. transformNode.parent = null;
  18088. transformNode.computeWorldMatrix(true);
  18089. }
  18090. }
  18091. if (!this.parent) {
  18092. var rootNodeIndex = this._scene.rootNodes.indexOf(this);
  18093. if (rootNodeIndex > -1) {
  18094. this._scene.rootNodes.splice(rootNodeIndex, 1);
  18095. }
  18096. }
  18097. else {
  18098. this.parent = null;
  18099. }
  18100. // Callback
  18101. this.onDisposeObservable.notifyObservers(this);
  18102. this.onDisposeObservable.clear();
  18103. // Behaviors
  18104. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  18105. var behavior = _c[_b];
  18106. behavior.detach();
  18107. }
  18108. this._behaviors = [];
  18109. this._isDisposed = true;
  18110. };
  18111. /**
  18112. * Parse animation range data from a serialization object and store them into a given node
  18113. * @param node defines where to store the animation ranges
  18114. * @param parsedNode defines the serialization object to read data from
  18115. * @param scene defines the hosting scene
  18116. */
  18117. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  18118. if (parsedNode.ranges) {
  18119. for (var index = 0; index < parsedNode.ranges.length; index++) {
  18120. var data = parsedNode.ranges[index];
  18121. node.createAnimationRange(data.name, data.from, data.to);
  18122. }
  18123. }
  18124. };
  18125. Node._NodeConstructors = {};
  18126. __decorate([
  18127. BABYLON.serialize()
  18128. ], Node.prototype, "name", void 0);
  18129. __decorate([
  18130. BABYLON.serialize()
  18131. ], Node.prototype, "id", void 0);
  18132. __decorate([
  18133. BABYLON.serialize()
  18134. ], Node.prototype, "uniqueId", void 0);
  18135. __decorate([
  18136. BABYLON.serialize()
  18137. ], Node.prototype, "state", void 0);
  18138. __decorate([
  18139. BABYLON.serialize()
  18140. ], Node.prototype, "metadata", void 0);
  18141. return Node;
  18142. }());
  18143. BABYLON.Node = Node;
  18144. })(BABYLON || (BABYLON = {}));
  18145. //# sourceMappingURL=babylon.node.js.map
  18146. var BABYLON;
  18147. (function (BABYLON) {
  18148. // This matrix is used as a value to reset the bounding box.
  18149. var _identityMatrix = BABYLON.Matrix.Identity();
  18150. var _tempRadiusVector = new BABYLON.Vector3(0, 0, 0);
  18151. var BoundingSphere = /** @class */ (function () {
  18152. /**
  18153. * Creates a new bounding sphere
  18154. * @param min defines the minimum vector (in local space)
  18155. * @param max defines the maximum vector (in local space)
  18156. */
  18157. function BoundingSphere(min, max) {
  18158. this.center = BABYLON.Vector3.Zero();
  18159. this.centerWorld = BABYLON.Vector3.Zero();
  18160. this.reConstruct(min, max);
  18161. }
  18162. /**
  18163. * Recreates the entire bounding sphere from scratch
  18164. * @param min defines the new minimum vector (in local space)
  18165. * @param max defines the new maximum vector (in local space)
  18166. */
  18167. BoundingSphere.prototype.reConstruct = function (min, max) {
  18168. this.minimum = min.clone();
  18169. this.maximum = max.clone();
  18170. var distance = BABYLON.Vector3.Distance(min, max);
  18171. BABYLON.Vector3.LerpToRef(min, max, 0.5, this.center);
  18172. this.radius = distance * 0.5;
  18173. this.centerWorld.set(0, 0, 0);
  18174. this._update(_identityMatrix);
  18175. };
  18176. /**
  18177. * Scale the current bounding sphere by applying a scale factor
  18178. * @param factor defines the scale factor to apply
  18179. * @returns the current bounding box
  18180. */
  18181. BoundingSphere.prototype.scale = function (factor) {
  18182. var newRadius = this.radius * factor;
  18183. _tempRadiusVector.set(newRadius, newRadius, newRadius);
  18184. var min = this.center.subtract(_tempRadiusVector);
  18185. var max = this.center.add(_tempRadiusVector);
  18186. this.reConstruct(min, max);
  18187. return this;
  18188. };
  18189. // Methods
  18190. /** @hidden */
  18191. BoundingSphere.prototype._update = function (world) {
  18192. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  18193. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, _tempRadiusVector);
  18194. this.radiusWorld = Math.max(Math.abs(_tempRadiusVector.x), Math.abs(_tempRadiusVector.y), Math.abs(_tempRadiusVector.z)) * this.radius;
  18195. };
  18196. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  18197. for (var i = 0; i < 6; i++) {
  18198. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  18199. return false;
  18200. }
  18201. return true;
  18202. };
  18203. BoundingSphere.prototype.intersectsPoint = function (point) {
  18204. var x = this.centerWorld.x - point.x;
  18205. var y = this.centerWorld.y - point.y;
  18206. var z = this.centerWorld.z - point.z;
  18207. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18208. if (this.radiusWorld < distance)
  18209. return false;
  18210. return true;
  18211. };
  18212. // Statics
  18213. BoundingSphere.Intersects = function (sphere0, sphere1) {
  18214. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  18215. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  18216. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  18217. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18218. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  18219. return false;
  18220. return true;
  18221. };
  18222. return BoundingSphere;
  18223. }());
  18224. BABYLON.BoundingSphere = BoundingSphere;
  18225. })(BABYLON || (BABYLON = {}));
  18226. //# sourceMappingURL=babylon.boundingSphere.js.map
  18227. var BABYLON;
  18228. (function (BABYLON) {
  18229. var BoundingBox = /** @class */ (function () {
  18230. /**
  18231. * Creates a new bounding box
  18232. * @param min defines the minimum vector (in local space)
  18233. * @param max defines the maximum vector (in local space)
  18234. */
  18235. function BoundingBox(min, max) {
  18236. this.vectorsWorld = new Array();
  18237. this.reConstruct(min, max);
  18238. }
  18239. // Methods
  18240. /**
  18241. * Recreates the entire bounding box from scratch
  18242. * @param min defines the new minimum vector (in local space)
  18243. * @param max defines the new maximum vector (in local space)
  18244. */
  18245. BoundingBox.prototype.reConstruct = function (min, max) {
  18246. this.minimum = min.clone();
  18247. this.maximum = max.clone();
  18248. // Bounding vectors
  18249. this.vectors = [
  18250. this.minimum.clone(),
  18251. this.maximum.clone(),
  18252. this.minimum.clone(),
  18253. this.minimum.clone(),
  18254. this.minimum.clone(),
  18255. this.maximum.clone(),
  18256. this.maximum.clone(),
  18257. this.maximum.clone()
  18258. ];
  18259. this.vectors[2].x = this.maximum.x;
  18260. this.vectors[3].y = this.maximum.y;
  18261. this.vectors[4].z = this.maximum.z;
  18262. this.vectors[5].z = this.minimum.z;
  18263. this.vectors[6].x = this.minimum.x;
  18264. this.vectors[7].y = this.minimum.y;
  18265. // OBB
  18266. this.center = this.maximum.add(this.minimum).scale(0.5);
  18267. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  18268. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  18269. // World
  18270. for (var index = 0; index < this.vectors.length; index++) {
  18271. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  18272. }
  18273. this.minimumWorld = BABYLON.Vector3.Zero();
  18274. this.maximumWorld = BABYLON.Vector3.Zero();
  18275. this.centerWorld = BABYLON.Vector3.Zero();
  18276. this.extendSizeWorld = BABYLON.Vector3.Zero();
  18277. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  18278. };
  18279. /**
  18280. * Scale the current bounding box by applying a scale factor
  18281. * @param factor defines the scale factor to apply
  18282. * @returns the current bounding box
  18283. */
  18284. BoundingBox.prototype.scale = function (factor) {
  18285. var diff = this.maximum.subtract(this.minimum);
  18286. var distance = diff.length() * factor;
  18287. diff.normalize();
  18288. var newRadius = diff.scale(distance / 2);
  18289. var min = this.center.subtract(newRadius);
  18290. var max = this.center.add(newRadius);
  18291. this.reConstruct(min, max);
  18292. return this;
  18293. };
  18294. BoundingBox.prototype.getWorldMatrix = function () {
  18295. return this._worldMatrix;
  18296. };
  18297. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  18298. this._worldMatrix.copyFrom(matrix);
  18299. return this;
  18300. };
  18301. /** @hidden */
  18302. BoundingBox.prototype._update = function (world) {
  18303. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  18304. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  18305. for (var index = 0; index < this.vectors.length; index++) {
  18306. var v = this.vectorsWorld[index];
  18307. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  18308. if (v.x < this.minimumWorld.x)
  18309. this.minimumWorld.x = v.x;
  18310. if (v.y < this.minimumWorld.y)
  18311. this.minimumWorld.y = v.y;
  18312. if (v.z < this.minimumWorld.z)
  18313. this.minimumWorld.z = v.z;
  18314. if (v.x > this.maximumWorld.x)
  18315. this.maximumWorld.x = v.x;
  18316. if (v.y > this.maximumWorld.y)
  18317. this.maximumWorld.y = v.y;
  18318. if (v.z > this.maximumWorld.z)
  18319. this.maximumWorld.z = v.z;
  18320. }
  18321. // Extend
  18322. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  18323. this.extendSizeWorld.scaleInPlace(0.5);
  18324. // OBB
  18325. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  18326. this.centerWorld.scaleInPlace(0.5);
  18327. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  18328. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  18329. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  18330. this._worldMatrix = world;
  18331. };
  18332. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  18333. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  18334. };
  18335. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18336. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  18337. };
  18338. BoundingBox.prototype.intersectsPoint = function (point) {
  18339. var delta = -BABYLON.Epsilon;
  18340. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  18341. return false;
  18342. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  18343. return false;
  18344. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  18345. return false;
  18346. return true;
  18347. };
  18348. BoundingBox.prototype.intersectsSphere = function (sphere) {
  18349. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  18350. };
  18351. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  18352. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  18353. return false;
  18354. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  18355. return false;
  18356. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  18357. return false;
  18358. return true;
  18359. };
  18360. // Statics
  18361. BoundingBox.Intersects = function (box0, box1) {
  18362. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18363. return false;
  18364. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18365. return false;
  18366. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18367. return false;
  18368. return true;
  18369. };
  18370. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18371. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18372. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18373. return (num <= (sphereRadius * sphereRadius));
  18374. };
  18375. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18376. for (var p = 0; p < 6; p++) {
  18377. for (var i = 0; i < 8; i++) {
  18378. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18379. return false;
  18380. }
  18381. }
  18382. }
  18383. return true;
  18384. };
  18385. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18386. for (var p = 0; p < 6; p++) {
  18387. var inCount = 8;
  18388. for (var i = 0; i < 8; i++) {
  18389. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18390. --inCount;
  18391. }
  18392. else {
  18393. break;
  18394. }
  18395. }
  18396. if (inCount === 0)
  18397. return false;
  18398. }
  18399. return true;
  18400. };
  18401. return BoundingBox;
  18402. }());
  18403. BABYLON.BoundingBox = BoundingBox;
  18404. })(BABYLON || (BABYLON = {}));
  18405. //# sourceMappingURL=babylon.boundingBox.js.map
  18406. var BABYLON;
  18407. (function (BABYLON) {
  18408. var computeBoxExtents = function (axis, box) {
  18409. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18410. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18411. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18412. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18413. var r = r0 + r1 + r2;
  18414. return {
  18415. min: p - r,
  18416. max: p + r
  18417. };
  18418. };
  18419. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18420. var axisOverlap = function (axis, box0, box1) {
  18421. var result0 = computeBoxExtents(axis, box0);
  18422. var result1 = computeBoxExtents(axis, box1);
  18423. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18424. };
  18425. var BoundingInfo = /** @class */ (function () {
  18426. function BoundingInfo(minimum, maximum) {
  18427. this.minimum = minimum;
  18428. this.maximum = maximum;
  18429. this._isLocked = false;
  18430. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18431. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18432. }
  18433. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18434. get: function () {
  18435. return this._isLocked;
  18436. },
  18437. set: function (value) {
  18438. this._isLocked = value;
  18439. },
  18440. enumerable: true,
  18441. configurable: true
  18442. });
  18443. // Methods
  18444. BoundingInfo.prototype.update = function (world) {
  18445. if (this._isLocked) {
  18446. return;
  18447. }
  18448. this.boundingBox._update(world);
  18449. this.boundingSphere._update(world);
  18450. };
  18451. /**
  18452. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18453. * @param center New center of the bounding info
  18454. * @param extend New extend of the bounding info
  18455. */
  18456. BoundingInfo.prototype.centerOn = function (center, extend) {
  18457. this.minimum = center.subtract(extend);
  18458. this.maximum = center.add(extend);
  18459. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18460. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18461. return this;
  18462. };
  18463. /**
  18464. * Scale the current bounding info by applying a scale factor
  18465. * @param factor defines the scale factor to apply
  18466. * @returns the current bounding info
  18467. */
  18468. BoundingInfo.prototype.scale = function (factor) {
  18469. this.boundingBox.scale(factor);
  18470. this.boundingSphere.scale(factor);
  18471. return this;
  18472. };
  18473. /**
  18474. * Returns `true` if the bounding info is within the frustum defined by the passed array of planes.
  18475. * @param frustumPlanes defines the frustum to test
  18476. * @param strategy defines the strategy to use for the culling (default is BABYLON.Scene.CULLINGSTRATEGY_STANDARD)
  18477. * @returns true if the bounding info is in the frustum planes
  18478. */
  18479. BoundingInfo.prototype.isInFrustum = function (frustumPlanes, strategy) {
  18480. if (strategy === void 0) { strategy = BABYLON.AbstractMesh.CULLINGSTRATEGY_STANDARD; }
  18481. if (!this.boundingSphere.isInFrustum(frustumPlanes)) {
  18482. return false;
  18483. }
  18484. if (strategy === BABYLON.AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY) {
  18485. return true;
  18486. }
  18487. return this.boundingBox.isInFrustum(frustumPlanes);
  18488. };
  18489. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18490. /**
  18491. * Gets the world distance between the min and max points of the bounding box
  18492. */
  18493. get: function () {
  18494. var boundingBox = this.boundingBox;
  18495. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18496. return size.length();
  18497. },
  18498. enumerable: true,
  18499. configurable: true
  18500. });
  18501. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18502. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18503. };
  18504. /** @hidden */
  18505. BoundingInfo.prototype._checkCollision = function (collider) {
  18506. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18507. };
  18508. BoundingInfo.prototype.intersectsPoint = function (point) {
  18509. if (!this.boundingSphere.centerWorld) {
  18510. return false;
  18511. }
  18512. if (!this.boundingSphere.intersectsPoint(point)) {
  18513. return false;
  18514. }
  18515. if (!this.boundingBox.intersectsPoint(point)) {
  18516. return false;
  18517. }
  18518. return true;
  18519. };
  18520. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18521. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18522. return false;
  18523. }
  18524. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18525. return false;
  18526. }
  18527. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18528. return false;
  18529. }
  18530. if (!precise) {
  18531. return true;
  18532. }
  18533. var box0 = this.boundingBox;
  18534. var box1 = boundingInfo.boundingBox;
  18535. if (!axisOverlap(box0.directions[0], box0, box1))
  18536. return false;
  18537. if (!axisOverlap(box0.directions[1], box0, box1))
  18538. return false;
  18539. if (!axisOverlap(box0.directions[2], box0, box1))
  18540. return false;
  18541. if (!axisOverlap(box1.directions[0], box0, box1))
  18542. return false;
  18543. if (!axisOverlap(box1.directions[1], box0, box1))
  18544. return false;
  18545. if (!axisOverlap(box1.directions[2], box0, box1))
  18546. return false;
  18547. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18548. return false;
  18549. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18550. return false;
  18551. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18552. return false;
  18553. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18554. return false;
  18555. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18556. return false;
  18557. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18558. return false;
  18559. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18560. return false;
  18561. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18562. return false;
  18563. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18564. return false;
  18565. return true;
  18566. };
  18567. return BoundingInfo;
  18568. }());
  18569. BABYLON.BoundingInfo = BoundingInfo;
  18570. })(BABYLON || (BABYLON = {}));
  18571. //# sourceMappingURL=babylon.boundingInfo.js.map
  18572. var BABYLON;
  18573. (function (BABYLON) {
  18574. var TransformNode = /** @class */ (function (_super) {
  18575. __extends(TransformNode, _super);
  18576. function TransformNode(name, scene, isPure) {
  18577. if (scene === void 0) { scene = null; }
  18578. if (isPure === void 0) { isPure = true; }
  18579. var _this = _super.call(this, name, scene) || this;
  18580. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18581. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18582. _this._up = new BABYLON.Vector3(0, 1, 0);
  18583. _this._right = new BABYLON.Vector3(1, 0, 0);
  18584. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18585. // Properties
  18586. _this._rotation = BABYLON.Vector3.Zero();
  18587. _this._scaling = BABYLON.Vector3.One();
  18588. _this._isDirty = false;
  18589. /**
  18590. * Set the billboard mode. Default is 0.
  18591. *
  18592. * | Value | Type | Description |
  18593. * | --- | --- | --- |
  18594. * | 0 | BILLBOARDMODE_NONE | |
  18595. * | 1 | BILLBOARDMODE_X | |
  18596. * | 2 | BILLBOARDMODE_Y | |
  18597. * | 4 | BILLBOARDMODE_Z | |
  18598. * | 7 | BILLBOARDMODE_ALL | |
  18599. *
  18600. */
  18601. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18602. _this.scalingDeterminant = 1;
  18603. _this.infiniteDistance = false;
  18604. /**
  18605. * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
  18606. * By default the system will update normals to compensate
  18607. */
  18608. _this.ignoreNonUniformScaling = false;
  18609. _this.position = BABYLON.Vector3.Zero();
  18610. _this._localWorld = BABYLON.Matrix.Zero();
  18611. /** @hidden */
  18612. _this._worldMatrix = BABYLON.Matrix.Zero();
  18613. /** @hidden */
  18614. _this._worldMatrixDeterminant = 0;
  18615. _this._absolutePosition = BABYLON.Vector3.Zero();
  18616. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18617. _this._postMultiplyPivotMatrix = false;
  18618. _this._isWorldMatrixFrozen = false;
  18619. /**
  18620. * An event triggered after the world matrix is updated
  18621. */
  18622. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18623. _this._nonUniformScaling = false;
  18624. if (isPure) {
  18625. _this.getScene().addTransformNode(_this);
  18626. }
  18627. return _this;
  18628. }
  18629. /**
  18630. * Gets a string identifying the name of the class
  18631. * @returns "TransformNode" string
  18632. */
  18633. TransformNode.prototype.getClassName = function () {
  18634. return "TransformNode";
  18635. };
  18636. Object.defineProperty(TransformNode.prototype, "rotation", {
  18637. /**
  18638. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  18639. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  18640. * Default : (0.0, 0.0, 0.0)
  18641. */
  18642. get: function () {
  18643. return this._rotation;
  18644. },
  18645. set: function (newRotation) {
  18646. this._rotation = newRotation;
  18647. },
  18648. enumerable: true,
  18649. configurable: true
  18650. });
  18651. Object.defineProperty(TransformNode.prototype, "scaling", {
  18652. /**
  18653. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18654. * Default : (1.0, 1.0, 1.0)
  18655. */
  18656. get: function () {
  18657. return this._scaling;
  18658. },
  18659. /**
  18660. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18661. * Default : (1.0, 1.0, 1.0)
  18662. */
  18663. set: function (newScaling) {
  18664. this._scaling = newScaling;
  18665. },
  18666. enumerable: true,
  18667. configurable: true
  18668. });
  18669. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18670. /**
  18671. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  18672. * It's null by default.
  18673. * 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)
  18674. */
  18675. get: function () {
  18676. return this._rotationQuaternion;
  18677. },
  18678. set: function (quaternion) {
  18679. this._rotationQuaternion = quaternion;
  18680. //reset the rotation vector.
  18681. if (quaternion && this.rotation.length()) {
  18682. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18683. }
  18684. },
  18685. enumerable: true,
  18686. configurable: true
  18687. });
  18688. Object.defineProperty(TransformNode.prototype, "forward", {
  18689. /**
  18690. * The forward direction of that transform in world space.
  18691. */
  18692. get: function () {
  18693. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18694. },
  18695. enumerable: true,
  18696. configurable: true
  18697. });
  18698. Object.defineProperty(TransformNode.prototype, "up", {
  18699. /**
  18700. * The up direction of that transform in world space.
  18701. */
  18702. get: function () {
  18703. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18704. },
  18705. enumerable: true,
  18706. configurable: true
  18707. });
  18708. Object.defineProperty(TransformNode.prototype, "right", {
  18709. /**
  18710. * The right direction of that transform in world space.
  18711. */
  18712. get: function () {
  18713. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18714. },
  18715. enumerable: true,
  18716. configurable: true
  18717. });
  18718. /**
  18719. * Returns the latest update of the World matrix
  18720. * Returns a Matrix.
  18721. */
  18722. TransformNode.prototype.getWorldMatrix = function () {
  18723. if (this._currentRenderId !== this.getScene().getRenderId()) {
  18724. this.computeWorldMatrix();
  18725. }
  18726. return this._worldMatrix;
  18727. };
  18728. /** @hidden */
  18729. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  18730. return this._worldMatrixDeterminant;
  18731. };
  18732. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  18733. /**
  18734. * Returns directly the latest state of the mesh World matrix.
  18735. * A Matrix is returned.
  18736. */
  18737. get: function () {
  18738. return this._worldMatrix;
  18739. },
  18740. enumerable: true,
  18741. configurable: true
  18742. });
  18743. /**
  18744. * Copies the parameter passed Matrix into the mesh Pose matrix.
  18745. * Returns the TransformNode.
  18746. */
  18747. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18748. this._poseMatrix.copyFrom(matrix);
  18749. return this;
  18750. };
  18751. /**
  18752. * Returns the mesh Pose matrix.
  18753. * Returned object : Matrix
  18754. */
  18755. TransformNode.prototype.getPoseMatrix = function () {
  18756. return this._poseMatrix;
  18757. };
  18758. /** @hidden */
  18759. TransformNode.prototype._isSynchronized = function () {
  18760. if (this._isDirty) {
  18761. return false;
  18762. }
  18763. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18764. return false;
  18765. if (this._cache.pivotMatrixUpdated) {
  18766. return false;
  18767. }
  18768. if (this.infiniteDistance) {
  18769. return false;
  18770. }
  18771. if (!this._cache.position.equals(this.position))
  18772. return false;
  18773. if (this._rotationQuaternion) {
  18774. if (!this._cache.rotationQuaternion.equals(this._rotationQuaternion))
  18775. return false;
  18776. }
  18777. if (!this._cache.rotation.equals(this.rotation))
  18778. return false;
  18779. if (!this._cache.scaling.equals(this.scaling))
  18780. return false;
  18781. return true;
  18782. };
  18783. /** @hidden */
  18784. TransformNode.prototype._initCache = function () {
  18785. _super.prototype._initCache.call(this);
  18786. this._cache.localMatrixUpdated = false;
  18787. this._cache.position = BABYLON.Vector3.Zero();
  18788. this._cache.scaling = BABYLON.Vector3.Zero();
  18789. this._cache.rotation = BABYLON.Vector3.Zero();
  18790. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18791. this._cache.billboardMode = -1;
  18792. };
  18793. TransformNode.prototype.markAsDirty = function (property) {
  18794. if (property === "rotation") {
  18795. this.rotationQuaternion = null;
  18796. }
  18797. this._currentRenderId = Number.MAX_VALUE;
  18798. this._isDirty = true;
  18799. return this;
  18800. };
  18801. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18802. /**
  18803. * Returns the current mesh absolute position.
  18804. * Returns a Vector3.
  18805. */
  18806. get: function () {
  18807. return this._absolutePosition;
  18808. },
  18809. enumerable: true,
  18810. configurable: true
  18811. });
  18812. /**
  18813. * Sets a new matrix to apply before all other transformation
  18814. * @param matrix defines the transform matrix
  18815. * @returns the current TransformNode
  18816. */
  18817. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18818. return this.setPivotMatrix(matrix, false);
  18819. };
  18820. /**
  18821. * Sets a new pivot matrix to the current node
  18822. * @param matrix defines the new pivot matrix to use
  18823. * @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
  18824. * @returns the current TransformNode
  18825. */
  18826. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18827. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18828. this._pivotMatrix = matrix.clone();
  18829. this._cache.pivotMatrixUpdated = true;
  18830. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18831. if (this._postMultiplyPivotMatrix) {
  18832. if (!this._pivotMatrixInverse) {
  18833. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18834. }
  18835. else {
  18836. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18837. }
  18838. }
  18839. return this;
  18840. };
  18841. /**
  18842. * Returns the mesh pivot matrix.
  18843. * Default : Identity.
  18844. * A Matrix is returned.
  18845. */
  18846. TransformNode.prototype.getPivotMatrix = function () {
  18847. return this._pivotMatrix;
  18848. };
  18849. /**
  18850. * Prevents the World matrix to be computed any longer.
  18851. * Returns the TransformNode.
  18852. */
  18853. TransformNode.prototype.freezeWorldMatrix = function () {
  18854. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18855. this.computeWorldMatrix(true);
  18856. this._isWorldMatrixFrozen = true;
  18857. return this;
  18858. };
  18859. /**
  18860. * Allows back the World matrix computation.
  18861. * Returns the TransformNode.
  18862. */
  18863. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18864. this._isWorldMatrixFrozen = false;
  18865. this.computeWorldMatrix(true);
  18866. return this;
  18867. };
  18868. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18869. /**
  18870. * True if the World matrix has been frozen.
  18871. * Returns a boolean.
  18872. */
  18873. get: function () {
  18874. return this._isWorldMatrixFrozen;
  18875. },
  18876. enumerable: true,
  18877. configurable: true
  18878. });
  18879. /**
  18880. * Retuns the mesh absolute position in the World.
  18881. * Returns a Vector3.
  18882. */
  18883. TransformNode.prototype.getAbsolutePosition = function () {
  18884. this.computeWorldMatrix();
  18885. return this._absolutePosition;
  18886. };
  18887. /**
  18888. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18889. * Returns the TransformNode.
  18890. */
  18891. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18892. if (!absolutePosition) {
  18893. return this;
  18894. }
  18895. var absolutePositionX;
  18896. var absolutePositionY;
  18897. var absolutePositionZ;
  18898. if (absolutePosition.x === undefined) {
  18899. if (arguments.length < 3) {
  18900. return this;
  18901. }
  18902. absolutePositionX = arguments[0];
  18903. absolutePositionY = arguments[1];
  18904. absolutePositionZ = arguments[2];
  18905. }
  18906. else {
  18907. absolutePositionX = absolutePosition.x;
  18908. absolutePositionY = absolutePosition.y;
  18909. absolutePositionZ = absolutePosition.z;
  18910. }
  18911. if (this.parent) {
  18912. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18913. invertParentWorldMatrix.invert();
  18914. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18915. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18916. }
  18917. else {
  18918. this.position.x = absolutePositionX;
  18919. this.position.y = absolutePositionY;
  18920. this.position.z = absolutePositionZ;
  18921. }
  18922. return this;
  18923. };
  18924. /**
  18925. * Sets the mesh position in its local space.
  18926. * Returns the TransformNode.
  18927. */
  18928. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18929. this.computeWorldMatrix();
  18930. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18931. return this;
  18932. };
  18933. /**
  18934. * Returns the mesh position in the local space from the current World matrix values.
  18935. * Returns a new Vector3.
  18936. */
  18937. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18938. this.computeWorldMatrix();
  18939. var invLocalWorldMatrix = this._localWorld.clone();
  18940. invLocalWorldMatrix.invert();
  18941. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  18942. };
  18943. /**
  18944. * Translates the mesh along the passed Vector3 in its local space.
  18945. * Returns the TransformNode.
  18946. */
  18947. TransformNode.prototype.locallyTranslate = function (vector3) {
  18948. this.computeWorldMatrix(true);
  18949. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  18950. return this;
  18951. };
  18952. /**
  18953. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  18954. * @param targetPoint the position (must be in same space as current mesh) to look at
  18955. * @param yawCor optional yaw (y-axis) correction in radians
  18956. * @param pitchCor optional pitch (x-axis) correction in radians
  18957. * @param rollCor optional roll (z-axis) correction in radians
  18958. * @param space the choosen space of the target
  18959. * @returns the TransformNode.
  18960. */
  18961. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  18962. if (yawCor === void 0) { yawCor = 0; }
  18963. if (pitchCor === void 0) { pitchCor = 0; }
  18964. if (rollCor === void 0) { rollCor = 0; }
  18965. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18966. var dv = TransformNode._lookAtVectorCache;
  18967. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  18968. targetPoint.subtractToRef(pos, dv);
  18969. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  18970. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  18971. var pitch = Math.atan2(dv.y, len);
  18972. if (this.rotationQuaternion) {
  18973. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  18974. }
  18975. else {
  18976. this.rotation.x = pitch + pitchCor;
  18977. this.rotation.y = yaw + yawCor;
  18978. this.rotation.z = rollCor;
  18979. }
  18980. return this;
  18981. };
  18982. /**
  18983. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  18984. * This Vector3 is expressed in the World space.
  18985. */
  18986. TransformNode.prototype.getDirection = function (localAxis) {
  18987. var result = BABYLON.Vector3.Zero();
  18988. this.getDirectionToRef(localAxis, result);
  18989. return result;
  18990. };
  18991. /**
  18992. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  18993. * localAxis is expressed in the mesh local space.
  18994. * result is computed in the Wordl space from the mesh World matrix.
  18995. * Returns the TransformNode.
  18996. */
  18997. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  18998. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18999. return this;
  19000. };
  19001. /**
  19002. * Sets a new pivot point to the current node
  19003. * @param point defines the new pivot point to use
  19004. * @param space defines if the point is in world or local space (local by default)
  19005. * @returns the current TransformNode
  19006. */
  19007. TransformNode.prototype.setPivotPoint = function (point, space) {
  19008. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  19009. if (this.getScene().getRenderId() == 0) {
  19010. this.computeWorldMatrix(true);
  19011. }
  19012. var wm = this.getWorldMatrix();
  19013. if (space == BABYLON.Space.WORLD) {
  19014. var tmat = BABYLON.Tmp.Matrix[0];
  19015. wm.invertToRef(tmat);
  19016. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  19017. }
  19018. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  19019. };
  19020. /**
  19021. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  19022. */
  19023. TransformNode.prototype.getPivotPoint = function () {
  19024. var point = BABYLON.Vector3.Zero();
  19025. this.getPivotPointToRef(point);
  19026. return point;
  19027. };
  19028. /**
  19029. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  19030. * Returns the TransformNode.
  19031. */
  19032. TransformNode.prototype.getPivotPointToRef = function (result) {
  19033. result.x = -this._pivotMatrix.m[12];
  19034. result.y = -this._pivotMatrix.m[13];
  19035. result.z = -this._pivotMatrix.m[14];
  19036. return this;
  19037. };
  19038. /**
  19039. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  19040. */
  19041. TransformNode.prototype.getAbsolutePivotPoint = function () {
  19042. var point = BABYLON.Vector3.Zero();
  19043. this.getAbsolutePivotPointToRef(point);
  19044. return point;
  19045. };
  19046. /**
  19047. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  19048. * Returns the TransformNode.
  19049. */
  19050. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  19051. result.x = this._pivotMatrix.m[12];
  19052. result.y = this._pivotMatrix.m[13];
  19053. result.z = this._pivotMatrix.m[14];
  19054. this.getPivotPointToRef(result);
  19055. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  19056. return this;
  19057. };
  19058. /**
  19059. * Defines the passed node as the parent of the current node.
  19060. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  19061. * Returns the TransformNode.
  19062. */
  19063. TransformNode.prototype.setParent = function (node) {
  19064. if (!node && !this.parent) {
  19065. return this;
  19066. }
  19067. if (!node) {
  19068. var rotation = BABYLON.Tmp.Quaternion[0];
  19069. var position = BABYLON.Tmp.Vector3[0];
  19070. var scale = BABYLON.Tmp.Vector3[1];
  19071. if (this.parent && this.parent.computeWorldMatrix) {
  19072. this.parent.computeWorldMatrix(true);
  19073. }
  19074. this.computeWorldMatrix(true);
  19075. this.getWorldMatrix().decompose(scale, rotation, position);
  19076. if (this.rotationQuaternion) {
  19077. this.rotationQuaternion.copyFrom(rotation);
  19078. }
  19079. else {
  19080. rotation.toEulerAnglesToRef(this.rotation);
  19081. }
  19082. this.scaling.x = scale.x;
  19083. this.scaling.y = scale.y;
  19084. this.scaling.z = scale.z;
  19085. this.position.x = position.x;
  19086. this.position.y = position.y;
  19087. this.position.z = position.z;
  19088. }
  19089. else {
  19090. var rotation = BABYLON.Tmp.Quaternion[0];
  19091. var position = BABYLON.Tmp.Vector3[0];
  19092. var scale = BABYLON.Tmp.Vector3[1];
  19093. var diffMatrix = BABYLON.Tmp.Matrix[0];
  19094. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  19095. this.computeWorldMatrix(true);
  19096. node.computeWorldMatrix(true);
  19097. node.getWorldMatrix().invertToRef(invParentMatrix);
  19098. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  19099. diffMatrix.decompose(scale, rotation, position);
  19100. if (this.rotationQuaternion) {
  19101. this.rotationQuaternion.copyFrom(rotation);
  19102. }
  19103. else {
  19104. rotation.toEulerAnglesToRef(this.rotation);
  19105. }
  19106. this.position.x = position.x;
  19107. this.position.y = position.y;
  19108. this.position.z = position.z;
  19109. this.scaling.x = scale.x;
  19110. this.scaling.y = scale.y;
  19111. this.scaling.z = scale.z;
  19112. }
  19113. this.parent = node;
  19114. return this;
  19115. };
  19116. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  19117. get: function () {
  19118. return this._nonUniformScaling;
  19119. },
  19120. enumerable: true,
  19121. configurable: true
  19122. });
  19123. /** @hidden */
  19124. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  19125. if (this._nonUniformScaling === value) {
  19126. return false;
  19127. }
  19128. this._nonUniformScaling = value;
  19129. return true;
  19130. };
  19131. /**
  19132. * Attach the current TransformNode to another TransformNode associated with a bone
  19133. * @param bone Bone affecting the TransformNode
  19134. * @param affectedTransformNode TransformNode associated with the bone
  19135. */
  19136. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  19137. this._transformToBoneReferal = affectedTransformNode;
  19138. this.parent = bone;
  19139. if (bone.getWorldMatrix().determinant() < 0) {
  19140. this.scalingDeterminant *= -1;
  19141. }
  19142. return this;
  19143. };
  19144. TransformNode.prototype.detachFromBone = function () {
  19145. if (!this.parent) {
  19146. return this;
  19147. }
  19148. if (this.parent.getWorldMatrix().determinant() < 0) {
  19149. this.scalingDeterminant *= -1;
  19150. }
  19151. this._transformToBoneReferal = null;
  19152. this.parent = null;
  19153. return this;
  19154. };
  19155. /**
  19156. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  19157. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19158. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19159. * The passed axis is also normalized.
  19160. * Returns the TransformNode.
  19161. */
  19162. TransformNode.prototype.rotate = function (axis, amount, space) {
  19163. axis.normalize();
  19164. if (!this.rotationQuaternion) {
  19165. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19166. this.rotation = BABYLON.Vector3.Zero();
  19167. }
  19168. var rotationQuaternion;
  19169. if (!space || space === BABYLON.Space.LOCAL) {
  19170. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19171. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  19172. }
  19173. else {
  19174. if (this.parent) {
  19175. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  19176. invertParentWorldMatrix.invert();
  19177. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  19178. }
  19179. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19180. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19181. }
  19182. return this;
  19183. };
  19184. /**
  19185. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  19186. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19187. * The passed axis is also normalized.
  19188. * Returns the TransformNode.
  19189. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  19190. */
  19191. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  19192. axis.normalize();
  19193. if (!this.rotationQuaternion) {
  19194. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19195. this.rotation.copyFromFloats(0, 0, 0);
  19196. }
  19197. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  19198. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  19199. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  19200. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  19201. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  19202. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  19203. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  19204. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  19205. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19206. return this;
  19207. };
  19208. /**
  19209. * Translates the mesh along the axis vector for the passed distance in the given space.
  19210. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19211. * Returns the TransformNode.
  19212. */
  19213. TransformNode.prototype.translate = function (axis, distance, space) {
  19214. var displacementVector = axis.scale(distance);
  19215. if (!space || space === BABYLON.Space.LOCAL) {
  19216. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  19217. this.setPositionWithLocalVector(tempV3);
  19218. }
  19219. else {
  19220. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  19221. }
  19222. return this;
  19223. };
  19224. /**
  19225. * Adds a rotation step to the mesh current rotation.
  19226. * x, y, z are Euler angles expressed in radians.
  19227. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  19228. * This means this rotation is made in the mesh local space only.
  19229. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  19230. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  19231. * ```javascript
  19232. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  19233. * ```
  19234. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  19235. * 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.
  19236. * Returns the TransformNode.
  19237. */
  19238. TransformNode.prototype.addRotation = function (x, y, z) {
  19239. var rotationQuaternion;
  19240. if (this.rotationQuaternion) {
  19241. rotationQuaternion = this.rotationQuaternion;
  19242. }
  19243. else {
  19244. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  19245. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  19246. }
  19247. var accumulation = BABYLON.Tmp.Quaternion[0];
  19248. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  19249. rotationQuaternion.multiplyInPlace(accumulation);
  19250. if (!this.rotationQuaternion) {
  19251. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  19252. }
  19253. return this;
  19254. };
  19255. /**
  19256. * Computes the mesh World matrix and returns it.
  19257. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  19258. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  19259. * If the parameter `force`is set to `true`, the actual computation is done.
  19260. * Returns the mesh World Matrix.
  19261. */
  19262. TransformNode.prototype.computeWorldMatrix = function (force) {
  19263. if (this._isWorldMatrixFrozen) {
  19264. return this._worldMatrix;
  19265. }
  19266. if (!force && this.isSynchronized(true)) {
  19267. this._currentRenderId = this.getScene().getRenderId();
  19268. return this._worldMatrix;
  19269. }
  19270. this._cache.position.copyFrom(this.position);
  19271. this._cache.scaling.copyFrom(this.scaling);
  19272. this._cache.pivotMatrixUpdated = false;
  19273. this._cache.billboardMode = this.billboardMode;
  19274. this._currentRenderId = this.getScene().getRenderId();
  19275. this._childRenderId = this.getScene().getRenderId();
  19276. this._isDirty = false;
  19277. // Scaling
  19278. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  19279. // Rotation
  19280. //rotate, if quaternion is set and rotation was used
  19281. if (this.rotationQuaternion) {
  19282. var len = this.rotation.length();
  19283. if (len) {
  19284. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  19285. this.rotation.copyFromFloats(0, 0, 0);
  19286. }
  19287. }
  19288. if (this.rotationQuaternion) {
  19289. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  19290. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  19291. }
  19292. else {
  19293. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  19294. this._cache.rotation.copyFrom(this.rotation);
  19295. }
  19296. // Translation
  19297. var camera = this.getScene().activeCamera;
  19298. if (this.infiniteDistance && !this.parent && camera) {
  19299. var cameraWorldMatrix = camera.getWorldMatrix();
  19300. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  19301. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  19302. }
  19303. else {
  19304. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  19305. }
  19306. // Composing transformations
  19307. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  19308. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19309. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  19310. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  19311. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  19312. // Need to decompose each rotation here
  19313. var currentPosition = BABYLON.Tmp.Vector3[3];
  19314. if (this.parent && this.parent.getWorldMatrix) {
  19315. if (this._transformToBoneReferal) {
  19316. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19317. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  19318. }
  19319. else {
  19320. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  19321. }
  19322. }
  19323. else {
  19324. currentPosition.copyFrom(this.position);
  19325. }
  19326. currentPosition.subtractInPlace(camera.globalPosition);
  19327. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  19328. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  19329. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  19330. }
  19331. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  19332. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  19333. }
  19334. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  19335. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  19336. }
  19337. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  19338. }
  19339. else {
  19340. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  19341. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  19342. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  19343. }
  19344. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  19345. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19346. }
  19347. // Post multiply inverse of pivotMatrix
  19348. if (this._postMultiplyPivotMatrix) {
  19349. BABYLON.Tmp.Matrix[5].multiplyToRef(this._pivotMatrixInverse, BABYLON.Tmp.Matrix[5]);
  19350. }
  19351. // Local world
  19352. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  19353. // Parent
  19354. if (this.parent && this.parent.getWorldMatrix) {
  19355. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19356. if (this._transformToBoneReferal) {
  19357. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19358. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  19359. }
  19360. else {
  19361. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  19362. }
  19363. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  19364. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  19365. this._worldMatrix.copyFrom(this._localWorld);
  19366. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19367. }
  19368. else {
  19369. if (this._transformToBoneReferal) {
  19370. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19371. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19372. }
  19373. else {
  19374. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19375. }
  19376. }
  19377. this._markSyncedWithParent();
  19378. }
  19379. else {
  19380. this._worldMatrix.copyFrom(this._localWorld);
  19381. }
  19382. // Normal matrix
  19383. if (!this.ignoreNonUniformScaling) {
  19384. if (this.scaling.isNonUniform) {
  19385. this._updateNonUniformScalingState(true);
  19386. }
  19387. else if (this.parent && this.parent._nonUniformScaling) {
  19388. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19389. }
  19390. else {
  19391. this._updateNonUniformScalingState(false);
  19392. }
  19393. }
  19394. else {
  19395. this._updateNonUniformScalingState(false);
  19396. }
  19397. this._afterComputeWorldMatrix();
  19398. // Absolute position
  19399. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19400. // Callbacks
  19401. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19402. if (!this._poseMatrix) {
  19403. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19404. }
  19405. // Cache the determinant
  19406. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19407. return this._worldMatrix;
  19408. };
  19409. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19410. };
  19411. /**
  19412. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19413. * @param func: callback function to add
  19414. *
  19415. * Returns the TransformNode.
  19416. */
  19417. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19418. this.onAfterWorldMatrixUpdateObservable.add(func);
  19419. return this;
  19420. };
  19421. /**
  19422. * Removes a registered callback function.
  19423. * Returns the TransformNode.
  19424. */
  19425. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19426. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19427. return this;
  19428. };
  19429. /**
  19430. * Clone the current transform node
  19431. * Returns the new transform node
  19432. * @param name Name of the new clone
  19433. * @param newParent New parent for the clone
  19434. * @param doNotCloneChildren Do not clone children hierarchy
  19435. */
  19436. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19437. var _this = this;
  19438. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19439. result.name = name;
  19440. result.id = name;
  19441. if (newParent) {
  19442. result.parent = newParent;
  19443. }
  19444. if (!doNotCloneChildren) {
  19445. // Children
  19446. var directDescendants = this.getDescendants(true);
  19447. for (var index = 0; index < directDescendants.length; index++) {
  19448. var child = directDescendants[index];
  19449. if (child.clone) {
  19450. child.clone(name + "." + child.name, result);
  19451. }
  19452. }
  19453. }
  19454. return result;
  19455. };
  19456. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19457. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19458. serializationObject.type = this.getClassName();
  19459. // Parent
  19460. if (this.parent) {
  19461. serializationObject.parentId = this.parent.id;
  19462. }
  19463. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19464. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19465. }
  19466. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19467. serializationObject.isEnabled = this.isEnabled();
  19468. // Parent
  19469. if (this.parent) {
  19470. serializationObject.parentId = this.parent.id;
  19471. }
  19472. return serializationObject;
  19473. };
  19474. // Statics
  19475. /**
  19476. * Returns a new TransformNode object parsed from the source provided.
  19477. * The parameter `parsedMesh` is the source.
  19478. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19479. */
  19480. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19481. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19482. if (BABYLON.Tags) {
  19483. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19484. }
  19485. if (parsedTransformNode.localMatrix) {
  19486. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19487. }
  19488. else if (parsedTransformNode.pivotMatrix) {
  19489. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19490. }
  19491. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19492. // Parent
  19493. if (parsedTransformNode.parentId) {
  19494. transformNode._waitingParentId = parsedTransformNode.parentId;
  19495. }
  19496. return transformNode;
  19497. };
  19498. /**
  19499. * Releases resources associated with this transform node.
  19500. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19501. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19502. */
  19503. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19504. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19505. // Animations
  19506. this.getScene().stopAnimation(this);
  19507. // Remove from scene
  19508. this.getScene().removeTransformNode(this);
  19509. this.onAfterWorldMatrixUpdateObservable.clear();
  19510. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19511. };
  19512. // Statics
  19513. TransformNode.BILLBOARDMODE_NONE = 0;
  19514. TransformNode.BILLBOARDMODE_X = 1;
  19515. TransformNode.BILLBOARDMODE_Y = 2;
  19516. TransformNode.BILLBOARDMODE_Z = 4;
  19517. TransformNode.BILLBOARDMODE_ALL = 7;
  19518. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19519. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19520. __decorate([
  19521. BABYLON.serializeAsVector3()
  19522. ], TransformNode.prototype, "_rotation", void 0);
  19523. __decorate([
  19524. BABYLON.serializeAsQuaternion()
  19525. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19526. __decorate([
  19527. BABYLON.serializeAsVector3()
  19528. ], TransformNode.prototype, "_scaling", void 0);
  19529. __decorate([
  19530. BABYLON.serialize()
  19531. ], TransformNode.prototype, "billboardMode", void 0);
  19532. __decorate([
  19533. BABYLON.serialize()
  19534. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19535. __decorate([
  19536. BABYLON.serialize()
  19537. ], TransformNode.prototype, "infiniteDistance", void 0);
  19538. __decorate([
  19539. BABYLON.serialize()
  19540. ], TransformNode.prototype, "ignoreNonUniformScaling", void 0);
  19541. __decorate([
  19542. BABYLON.serializeAsVector3()
  19543. ], TransformNode.prototype, "position", void 0);
  19544. return TransformNode;
  19545. }(BABYLON.Node));
  19546. BABYLON.TransformNode = TransformNode;
  19547. })(BABYLON || (BABYLON = {}));
  19548. //# sourceMappingURL=babylon.transformNode.js.map
  19549. var BABYLON;
  19550. (function (BABYLON) {
  19551. /**
  19552. * Class used to store all common mesh properties
  19553. */
  19554. var AbstractMesh = /** @class */ (function (_super) {
  19555. __extends(AbstractMesh, _super);
  19556. // Constructor
  19557. /**
  19558. * Creates a new AbstractMesh
  19559. * @param name defines the name of the mesh
  19560. * @param scene defines the hosting scene
  19561. */
  19562. function AbstractMesh(name, scene) {
  19563. if (scene === void 0) { scene = null; }
  19564. var _this = _super.call(this, name, scene, false) || this;
  19565. _this._facetNb = 0; // facet number
  19566. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19567. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19568. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19569. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19570. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19571. _this._subDiv = {
  19572. max: 1,
  19573. X: 1,
  19574. Y: 1,
  19575. Z: 1
  19576. };
  19577. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19578. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19579. /** Gets ot sets the culling strategy to use to find visible meshes */
  19580. _this.cullingStrategy = AbstractMesh.CULLINGSTRATEGY_STANDARD;
  19581. // Events
  19582. /**
  19583. * An event triggered when this mesh collides with another one
  19584. */
  19585. _this.onCollideObservable = new BABYLON.Observable();
  19586. /**
  19587. * An event triggered when the collision's position changes
  19588. */
  19589. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19590. /**
  19591. * An event triggered when material is changed
  19592. */
  19593. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19594. // Properties
  19595. /**
  19596. * Gets or sets the orientation for POV movement & rotation
  19597. */
  19598. _this.definedFacingForward = true;
  19599. /**
  19600. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19601. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19602. * * 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.
  19603. * @see http://doc.babylonjs.com/features/occlusionquery
  19604. */
  19605. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19606. /**
  19607. * 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:
  19608. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19609. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19610. * * 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.
  19611. * @see http://doc.babylonjs.com/features/occlusionquery
  19612. */
  19613. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19614. /**
  19615. * 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.
  19616. * The default value is -1 which means don't break the query and wait till the result
  19617. * @see http://doc.babylonjs.com/features/occlusionquery
  19618. */
  19619. _this.occlusionRetryCount = -1;
  19620. /** @hidden */
  19621. _this._occlusionInternalRetryCounter = 0;
  19622. /** @hidden */
  19623. _this._isOccluded = false;
  19624. /** @hidden */
  19625. _this._isOcclusionQueryInProgress = false;
  19626. _this._visibility = 1.0;
  19627. /** Gets or sets the alpha index used to sort transparent meshes
  19628. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19629. */
  19630. _this.alphaIndex = Number.MAX_VALUE;
  19631. /**
  19632. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19633. */
  19634. _this.isVisible = true;
  19635. /**
  19636. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19637. */
  19638. _this.isPickable = true;
  19639. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19640. _this.showSubMeshesBoundingBox = false;
  19641. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19642. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19643. */
  19644. _this.isBlocker = false;
  19645. /**
  19646. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19647. */
  19648. _this.enablePointerMoveEvents = false;
  19649. /**
  19650. * Specifies the rendering group id for this mesh (0 by default)
  19651. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19652. */
  19653. _this.renderingGroupId = 0;
  19654. _this._receiveShadows = false;
  19655. /** Defines color to use when rendering outline */
  19656. _this.outlineColor = BABYLON.Color3.Red();
  19657. /** Define width to use when rendering outline */
  19658. _this.outlineWidth = 0.02;
  19659. /** Defines color to use when rendering overlay */
  19660. _this.overlayColor = BABYLON.Color3.Red();
  19661. /** Defines alpha to use when rendering overlay */
  19662. _this.overlayAlpha = 0.5;
  19663. _this._hasVertexAlpha = false;
  19664. _this._useVertexColors = true;
  19665. _this._computeBonesUsingShaders = true;
  19666. _this._numBoneInfluencers = 4;
  19667. _this._applyFog = true;
  19668. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19669. _this.useOctreeForRenderingSelection = true;
  19670. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19671. _this.useOctreeForPicking = true;
  19672. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19673. _this.useOctreeForCollisions = true;
  19674. _this._layerMask = 0x0FFFFFFF;
  19675. /**
  19676. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19677. */
  19678. _this.alwaysSelectAsActiveMesh = false;
  19679. /**
  19680. * Gets or sets the current action manager
  19681. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19682. */
  19683. _this.actionManager = null;
  19684. /**
  19685. * Gets or sets impostor used for physic simulation
  19686. * @see http://doc.babylonjs.com/features/physics_engine
  19687. */
  19688. _this.physicsImpostor = null;
  19689. // Collisions
  19690. _this._checkCollisions = false;
  19691. _this._collisionMask = -1;
  19692. _this._collisionGroup = -1;
  19693. /**
  19694. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19695. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19696. */
  19697. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19698. /**
  19699. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19700. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19701. */
  19702. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19703. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19704. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19705. // Edges
  19706. /**
  19707. * Defines edge width used when edgesRenderer is enabled
  19708. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19709. */
  19710. _this.edgesWidth = 1;
  19711. /**
  19712. * Defines edge color used when edgesRenderer is enabled
  19713. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19714. */
  19715. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19716. // Cache
  19717. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19718. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19719. /** @hidden */
  19720. _this._renderId = 0;
  19721. /** @hidden */
  19722. _this._intersectionsInProgress = new Array();
  19723. /** @hidden */
  19724. _this._unIndexed = false;
  19725. /** @hidden */
  19726. _this._lightSources = new Array();
  19727. /**
  19728. * An event triggered when the mesh is rebuilt.
  19729. */
  19730. _this.onRebuildObservable = new BABYLON.Observable();
  19731. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19732. if (collidedMesh === void 0) { collidedMesh = null; }
  19733. //TODO move this to the collision coordinator!
  19734. if (_this.getScene().workerCollisions)
  19735. newPosition.multiplyInPlace(_this._collider._radius);
  19736. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19737. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19738. _this.position.addInPlace(_this._diffPositionForCollisions);
  19739. }
  19740. if (collidedMesh) {
  19741. _this.onCollideObservable.notifyObservers(collidedMesh);
  19742. }
  19743. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19744. };
  19745. _this.getScene().addMesh(_this);
  19746. _this._resyncLightSources();
  19747. return _this;
  19748. }
  19749. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19750. /**
  19751. * No billboard
  19752. */
  19753. get: function () {
  19754. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19755. },
  19756. enumerable: true,
  19757. configurable: true
  19758. });
  19759. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19760. /** Billboard on X axis */
  19761. get: function () {
  19762. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19763. },
  19764. enumerable: true,
  19765. configurable: true
  19766. });
  19767. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19768. /** Billboard on Y axis */
  19769. get: function () {
  19770. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19771. },
  19772. enumerable: true,
  19773. configurable: true
  19774. });
  19775. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19776. /** Billboard on Z axis */
  19777. get: function () {
  19778. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19779. },
  19780. enumerable: true,
  19781. configurable: true
  19782. });
  19783. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19784. /** Billboard on all axes */
  19785. get: function () {
  19786. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19787. },
  19788. enumerable: true,
  19789. configurable: true
  19790. });
  19791. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19792. /**
  19793. * Gets the number of facets in the mesh
  19794. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19795. */
  19796. get: function () {
  19797. return this._facetNb;
  19798. },
  19799. enumerable: true,
  19800. configurable: true
  19801. });
  19802. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19803. /**
  19804. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  19805. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19806. */
  19807. get: function () {
  19808. return this._partitioningSubdivisions;
  19809. },
  19810. set: function (nb) {
  19811. this._partitioningSubdivisions = nb;
  19812. },
  19813. enumerable: true,
  19814. configurable: true
  19815. });
  19816. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19817. /**
  19818. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19819. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  19820. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19821. */
  19822. get: function () {
  19823. return this._partitioningBBoxRatio;
  19824. },
  19825. set: function (ratio) {
  19826. this._partitioningBBoxRatio = ratio;
  19827. },
  19828. enumerable: true,
  19829. configurable: true
  19830. });
  19831. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19832. /**
  19833. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  19834. * Works only for updatable meshes.
  19835. * Doesn't work with multi-materials
  19836. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19837. */
  19838. get: function () {
  19839. return this._facetDepthSort;
  19840. },
  19841. set: function (sort) {
  19842. this._facetDepthSort = sort;
  19843. },
  19844. enumerable: true,
  19845. configurable: true
  19846. });
  19847. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19848. /**
  19849. * The location (Vector3) where the facet depth sort must be computed from.
  19850. * By default, the active camera position.
  19851. * Used only when facet depth sort is enabled
  19852. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19853. */
  19854. get: function () {
  19855. return this._facetDepthSortFrom;
  19856. },
  19857. set: function (location) {
  19858. this._facetDepthSortFrom = location;
  19859. },
  19860. enumerable: true,
  19861. configurable: true
  19862. });
  19863. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19864. /**
  19865. * gets a boolean indicating if facetData is enabled
  19866. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19867. */
  19868. get: function () {
  19869. return this._facetDataEnabled;
  19870. },
  19871. enumerable: true,
  19872. configurable: true
  19873. });
  19874. /** @hidden */
  19875. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19876. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19877. return false;
  19878. }
  19879. this._markSubMeshesAsMiscDirty();
  19880. return true;
  19881. };
  19882. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19883. /** Set a function to call when this mesh collides with another one */
  19884. set: function (callback) {
  19885. if (this._onCollideObserver) {
  19886. this.onCollideObservable.remove(this._onCollideObserver);
  19887. }
  19888. this._onCollideObserver = this.onCollideObservable.add(callback);
  19889. },
  19890. enumerable: true,
  19891. configurable: true
  19892. });
  19893. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19894. /** Set a function to call when the collision's position changes */
  19895. set: function (callback) {
  19896. if (this._onCollisionPositionChangeObserver) {
  19897. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19898. }
  19899. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19900. },
  19901. enumerable: true,
  19902. configurable: true
  19903. });
  19904. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19905. /**
  19906. * 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
  19907. * @see http://doc.babylonjs.com/features/occlusionquery
  19908. */
  19909. get: function () {
  19910. return this._isOccluded;
  19911. },
  19912. set: function (value) {
  19913. this._isOccluded = value;
  19914. },
  19915. enumerable: true,
  19916. configurable: true
  19917. });
  19918. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19919. /**
  19920. * Flag to check the progress status of the query
  19921. * @see http://doc.babylonjs.com/features/occlusionquery
  19922. */
  19923. get: function () {
  19924. return this._isOcclusionQueryInProgress;
  19925. },
  19926. enumerable: true,
  19927. configurable: true
  19928. });
  19929. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  19930. /**
  19931. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19932. */
  19933. get: function () {
  19934. return this._visibility;
  19935. },
  19936. /**
  19937. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19938. */
  19939. set: function (value) {
  19940. if (this._visibility === value) {
  19941. return;
  19942. }
  19943. this._visibility = value;
  19944. this._markSubMeshesAsMiscDirty();
  19945. },
  19946. enumerable: true,
  19947. configurable: true
  19948. });
  19949. Object.defineProperty(AbstractMesh.prototype, "material", {
  19950. /** Gets or sets current material */
  19951. get: function () {
  19952. return this._material;
  19953. },
  19954. set: function (value) {
  19955. if (this._material === value) {
  19956. return;
  19957. }
  19958. this._material = value;
  19959. if (this.onMaterialChangedObservable.hasObservers) {
  19960. this.onMaterialChangedObservable.notifyObservers(this);
  19961. }
  19962. if (!this.subMeshes) {
  19963. return;
  19964. }
  19965. this._unBindEffect();
  19966. },
  19967. enumerable: true,
  19968. configurable: true
  19969. });
  19970. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  19971. /**
  19972. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  19973. * @see http://doc.babylonjs.com/babylon101/shadows
  19974. */
  19975. get: function () {
  19976. return this._receiveShadows;
  19977. },
  19978. set: function (value) {
  19979. if (this._receiveShadows === value) {
  19980. return;
  19981. }
  19982. this._receiveShadows = value;
  19983. this._markSubMeshesAsLightDirty();
  19984. },
  19985. enumerable: true,
  19986. configurable: true
  19987. });
  19988. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  19989. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  19990. get: function () {
  19991. return this._hasVertexAlpha;
  19992. },
  19993. set: function (value) {
  19994. if (this._hasVertexAlpha === value) {
  19995. return;
  19996. }
  19997. this._hasVertexAlpha = value;
  19998. this._markSubMeshesAsAttributesDirty();
  19999. this._markSubMeshesAsMiscDirty();
  20000. },
  20001. enumerable: true,
  20002. configurable: true
  20003. });
  20004. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  20005. /** 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) */
  20006. get: function () {
  20007. return this._useVertexColors;
  20008. },
  20009. set: function (value) {
  20010. if (this._useVertexColors === value) {
  20011. return;
  20012. }
  20013. this._useVertexColors = value;
  20014. this._markSubMeshesAsAttributesDirty();
  20015. },
  20016. enumerable: true,
  20017. configurable: true
  20018. });
  20019. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  20020. /**
  20021. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  20022. */
  20023. get: function () {
  20024. return this._computeBonesUsingShaders;
  20025. },
  20026. set: function (value) {
  20027. if (this._computeBonesUsingShaders === value) {
  20028. return;
  20029. }
  20030. this._computeBonesUsingShaders = value;
  20031. this._markSubMeshesAsAttributesDirty();
  20032. },
  20033. enumerable: true,
  20034. configurable: true
  20035. });
  20036. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  20037. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  20038. get: function () {
  20039. return this._numBoneInfluencers;
  20040. },
  20041. set: function (value) {
  20042. if (this._numBoneInfluencers === value) {
  20043. return;
  20044. }
  20045. this._numBoneInfluencers = value;
  20046. this._markSubMeshesAsAttributesDirty();
  20047. },
  20048. enumerable: true,
  20049. configurable: true
  20050. });
  20051. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  20052. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  20053. get: function () {
  20054. return this._applyFog;
  20055. },
  20056. set: function (value) {
  20057. if (this._applyFog === value) {
  20058. return;
  20059. }
  20060. this._applyFog = value;
  20061. this._markSubMeshesAsMiscDirty();
  20062. },
  20063. enumerable: true,
  20064. configurable: true
  20065. });
  20066. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  20067. /**
  20068. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  20069. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  20070. */
  20071. get: function () {
  20072. return this._layerMask;
  20073. },
  20074. set: function (value) {
  20075. if (value === this._layerMask) {
  20076. return;
  20077. }
  20078. this._layerMask = value;
  20079. this._resyncLightSources();
  20080. },
  20081. enumerable: true,
  20082. configurable: true
  20083. });
  20084. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  20085. /**
  20086. * Gets or sets a collision mask used to mask collisions (default is -1).
  20087. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20088. */
  20089. get: function () {
  20090. return this._collisionMask;
  20091. },
  20092. set: function (mask) {
  20093. this._collisionMask = !isNaN(mask) ? mask : -1;
  20094. },
  20095. enumerable: true,
  20096. configurable: true
  20097. });
  20098. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  20099. /**
  20100. * Gets or sets the current collision group mask (-1 by default).
  20101. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20102. */
  20103. get: function () {
  20104. return this._collisionGroup;
  20105. },
  20106. set: function (mask) {
  20107. this._collisionGroup = !isNaN(mask) ? mask : -1;
  20108. },
  20109. enumerable: true,
  20110. configurable: true
  20111. });
  20112. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  20113. /** @hidden */
  20114. get: function () {
  20115. return null;
  20116. },
  20117. enumerable: true,
  20118. configurable: true
  20119. });
  20120. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  20121. get: function () {
  20122. return this._skeleton;
  20123. },
  20124. /**
  20125. * Gets or sets a skeleton to apply skining transformations
  20126. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  20127. */
  20128. set: function (value) {
  20129. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  20130. this._skeleton._unregisterMeshWithPoseMatrix(this);
  20131. }
  20132. if (value && value.needInitialSkinMatrix) {
  20133. value._registerMeshWithPoseMatrix(this);
  20134. }
  20135. this._skeleton = value;
  20136. if (!this._skeleton) {
  20137. this._bonesTransformMatrices = null;
  20138. }
  20139. this._markSubMeshesAsAttributesDirty();
  20140. },
  20141. enumerable: true,
  20142. configurable: true
  20143. });
  20144. /**
  20145. * Returns the string "AbstractMesh"
  20146. * @returns "AbstractMesh"
  20147. */
  20148. AbstractMesh.prototype.getClassName = function () {
  20149. return "AbstractMesh";
  20150. };
  20151. /**
  20152. * Gets a string representation of the current mesh
  20153. * @param fullDetails defines a boolean indicating if full details must be included
  20154. * @returns a string representation of the current mesh
  20155. */
  20156. AbstractMesh.prototype.toString = function (fullDetails) {
  20157. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  20158. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  20159. if (this._skeleton) {
  20160. ret += ", skeleton: " + this._skeleton.name;
  20161. }
  20162. if (fullDetails) {
  20163. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  20164. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  20165. }
  20166. return ret;
  20167. };
  20168. /** @hidden */
  20169. AbstractMesh.prototype._rebuild = function () {
  20170. this.onRebuildObservable.notifyObservers(this);
  20171. if (this._occlusionQuery) {
  20172. this._occlusionQuery = null;
  20173. }
  20174. if (!this.subMeshes) {
  20175. return;
  20176. }
  20177. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20178. var subMesh = _a[_i];
  20179. subMesh._rebuild();
  20180. }
  20181. };
  20182. /** @hidden */
  20183. AbstractMesh.prototype._resyncLightSources = function () {
  20184. this._lightSources.length = 0;
  20185. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  20186. var light = _a[_i];
  20187. if (!light.isEnabled()) {
  20188. continue;
  20189. }
  20190. if (light.canAffectMesh(this)) {
  20191. this._lightSources.push(light);
  20192. }
  20193. }
  20194. this._markSubMeshesAsLightDirty();
  20195. };
  20196. /** @hidden */
  20197. AbstractMesh.prototype._resyncLighSource = function (light) {
  20198. var isIn = light.isEnabled() && light.canAffectMesh(this);
  20199. var index = this._lightSources.indexOf(light);
  20200. if (index === -1) {
  20201. if (!isIn) {
  20202. return;
  20203. }
  20204. this._lightSources.push(light);
  20205. }
  20206. else {
  20207. if (isIn) {
  20208. return;
  20209. }
  20210. this._lightSources.splice(index, 1);
  20211. }
  20212. this._markSubMeshesAsLightDirty();
  20213. };
  20214. /** @hidden */
  20215. AbstractMesh.prototype._unBindEffect = function () {
  20216. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20217. var subMesh = _a[_i];
  20218. subMesh.setEffect(null);
  20219. }
  20220. };
  20221. /** @hidden */
  20222. AbstractMesh.prototype._removeLightSource = function (light) {
  20223. var index = this._lightSources.indexOf(light);
  20224. if (index === -1) {
  20225. return;
  20226. }
  20227. this._lightSources.splice(index, 1);
  20228. this._markSubMeshesAsLightDirty();
  20229. };
  20230. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  20231. if (!this.subMeshes) {
  20232. return;
  20233. }
  20234. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20235. var subMesh = _a[_i];
  20236. if (subMesh._materialDefines) {
  20237. func(subMesh._materialDefines);
  20238. }
  20239. }
  20240. };
  20241. /** @hidden */
  20242. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  20243. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  20244. };
  20245. /** @hidden */
  20246. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  20247. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  20248. };
  20249. /** @hidden */
  20250. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  20251. if (!this.subMeshes) {
  20252. return;
  20253. }
  20254. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20255. var subMesh = _a[_i];
  20256. var material = subMesh.getMaterial();
  20257. if (material) {
  20258. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  20259. }
  20260. }
  20261. };
  20262. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  20263. /**
  20264. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  20265. */
  20266. get: function () {
  20267. return this._scaling;
  20268. },
  20269. set: function (newScaling) {
  20270. this._scaling = newScaling;
  20271. if (this.physicsImpostor) {
  20272. this.physicsImpostor.forceUpdate();
  20273. }
  20274. },
  20275. enumerable: true,
  20276. configurable: true
  20277. });
  20278. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  20279. // Methods
  20280. /**
  20281. * Returns true if the mesh is blocked. Implemented by child classes
  20282. */
  20283. get: function () {
  20284. return false;
  20285. },
  20286. enumerable: true,
  20287. configurable: true
  20288. });
  20289. /**
  20290. * Returns the mesh itself by default. Implemented by child classes
  20291. * @param camera defines the camera to use to pick the right LOD level
  20292. * @returns the currentAbstractMesh
  20293. */
  20294. AbstractMesh.prototype.getLOD = function (camera) {
  20295. return this;
  20296. };
  20297. /**
  20298. * Returns 0 by default. Implemented by child classes
  20299. * @returns an integer
  20300. */
  20301. AbstractMesh.prototype.getTotalVertices = function () {
  20302. return 0;
  20303. };
  20304. /**
  20305. * Returns null by default. Implemented by child classes
  20306. * @returns null
  20307. */
  20308. AbstractMesh.prototype.getIndices = function () {
  20309. return null;
  20310. };
  20311. /**
  20312. * Returns the array of the requested vertex data kind. Implemented by child classes
  20313. * @param kind defines the vertex data kind to use
  20314. * @returns null
  20315. */
  20316. AbstractMesh.prototype.getVerticesData = function (kind) {
  20317. return null;
  20318. };
  20319. /**
  20320. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20321. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20322. * Note that a new underlying VertexBuffer object is created each call.
  20323. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20324. * @param kind defines vertex data kind:
  20325. * * BABYLON.VertexBuffer.PositionKind
  20326. * * BABYLON.VertexBuffer.UVKind
  20327. * * BABYLON.VertexBuffer.UV2Kind
  20328. * * BABYLON.VertexBuffer.UV3Kind
  20329. * * BABYLON.VertexBuffer.UV4Kind
  20330. * * BABYLON.VertexBuffer.UV5Kind
  20331. * * BABYLON.VertexBuffer.UV6Kind
  20332. * * BABYLON.VertexBuffer.ColorKind
  20333. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20334. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20335. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20336. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20337. * @param data defines the data source
  20338. * @param updatable defines if the data must be flagged as updatable (or static)
  20339. * @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
  20340. * @returns the current mesh
  20341. */
  20342. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20343. return this;
  20344. };
  20345. /**
  20346. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20347. * If the mesh has no geometry, it is simply returned as it is.
  20348. * @param kind defines vertex data kind:
  20349. * * BABYLON.VertexBuffer.PositionKind
  20350. * * BABYLON.VertexBuffer.UVKind
  20351. * * BABYLON.VertexBuffer.UV2Kind
  20352. * * BABYLON.VertexBuffer.UV3Kind
  20353. * * BABYLON.VertexBuffer.UV4Kind
  20354. * * BABYLON.VertexBuffer.UV5Kind
  20355. * * BABYLON.VertexBuffer.UV6Kind
  20356. * * BABYLON.VertexBuffer.ColorKind
  20357. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20358. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20359. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20360. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20361. * @param data defines the data source
  20362. * @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
  20363. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20364. * @returns the current mesh
  20365. */
  20366. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20367. return this;
  20368. };
  20369. /**
  20370. * Sets the mesh indices,
  20371. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20372. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20373. * @param totalVertices Defines the total number of vertices
  20374. * @returns the current mesh
  20375. */
  20376. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20377. return this;
  20378. };
  20379. /**
  20380. * Gets a boolean indicating if specific vertex data is present
  20381. * @param kind defines the vertex data kind to use
  20382. * @returns true is data kind is present
  20383. */
  20384. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20385. return false;
  20386. };
  20387. /**
  20388. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20389. * @returns a BoundingInfo
  20390. */
  20391. AbstractMesh.prototype.getBoundingInfo = function () {
  20392. if (this._masterMesh) {
  20393. return this._masterMesh.getBoundingInfo();
  20394. }
  20395. if (!this._boundingInfo) {
  20396. // this._boundingInfo is being created here
  20397. this._updateBoundingInfo();
  20398. }
  20399. // cannot be null.
  20400. return this._boundingInfo;
  20401. };
  20402. /**
  20403. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20404. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20405. * @returns the current mesh
  20406. */
  20407. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20408. if (includeDescendants === void 0) { includeDescendants = true; }
  20409. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20410. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20411. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20412. if (maxDimension === 0) {
  20413. return this;
  20414. }
  20415. var scale = 1 / maxDimension;
  20416. this.scaling.scaleInPlace(scale);
  20417. return this;
  20418. };
  20419. /**
  20420. * Overwrite the current bounding info
  20421. * @param boundingInfo defines the new bounding info
  20422. * @returns the current mesh
  20423. */
  20424. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20425. this._boundingInfo = boundingInfo;
  20426. return this;
  20427. };
  20428. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20429. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20430. get: function () {
  20431. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20432. },
  20433. enumerable: true,
  20434. configurable: true
  20435. });
  20436. /** @hidden */
  20437. AbstractMesh.prototype._preActivate = function () {
  20438. };
  20439. /** @hidden */
  20440. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20441. };
  20442. /** @hidden */
  20443. AbstractMesh.prototype._activate = function (renderId) {
  20444. this._renderId = renderId;
  20445. };
  20446. /**
  20447. * Gets the current world matrix
  20448. * @returns a Matrix
  20449. */
  20450. AbstractMesh.prototype.getWorldMatrix = function () {
  20451. if (this._masterMesh) {
  20452. return this._masterMesh.getWorldMatrix();
  20453. }
  20454. return _super.prototype.getWorldMatrix.call(this);
  20455. };
  20456. /** @hidden */
  20457. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20458. if (this._masterMesh) {
  20459. return this._masterMesh._getWorldMatrixDeterminant();
  20460. }
  20461. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20462. };
  20463. // ================================== Point of View Movement =================================
  20464. /**
  20465. * Perform relative position change from the point of view of behind the front of the mesh.
  20466. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20467. * Supports definition of mesh facing forward or backward
  20468. * @param amountRight defines the distance on the right axis
  20469. * @param amountUp defines the distance on the up axis
  20470. * @param amountForward defines the distance on the forward axis
  20471. * @returns the current mesh
  20472. */
  20473. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20474. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20475. return this;
  20476. };
  20477. /**
  20478. * Calculate relative position change from the point of view of behind the front of the mesh.
  20479. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20480. * Supports definition of mesh facing forward or backward
  20481. * @param amountRight defines the distance on the right axis
  20482. * @param amountUp defines the distance on the up axis
  20483. * @param amountForward defines the distance on the forward axis
  20484. * @returns the new displacement vector
  20485. */
  20486. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20487. var rotMatrix = new BABYLON.Matrix();
  20488. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20489. rotQuaternion.toRotationMatrix(rotMatrix);
  20490. var translationDelta = BABYLON.Vector3.Zero();
  20491. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20492. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20493. return translationDelta;
  20494. };
  20495. // ================================== Point of View Rotation =================================
  20496. /**
  20497. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20498. * Supports definition of mesh facing forward or backward
  20499. * @param flipBack defines the flip
  20500. * @param twirlClockwise defines the twirl
  20501. * @param tiltRight defines the tilt
  20502. * @returns the current mesh
  20503. */
  20504. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20505. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20506. return this;
  20507. };
  20508. /**
  20509. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20510. * Supports definition of mesh facing forward or backward.
  20511. * @param flipBack defines the flip
  20512. * @param twirlClockwise defines the twirl
  20513. * @param tiltRight defines the tilt
  20514. * @returns the new rotation vector
  20515. */
  20516. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20517. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20518. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20519. };
  20520. /**
  20521. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20522. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20523. * @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
  20524. * @returns the new bounding vectors
  20525. */
  20526. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  20527. if (includeDescendants === void 0) { includeDescendants = true; }
  20528. if (predicate === void 0) { predicate = null; }
  20529. // Ensures that all world matrix will be recomputed.
  20530. this.getScene().incrementRenderId();
  20531. this.computeWorldMatrix(true);
  20532. var min;
  20533. var max;
  20534. var boundingInfo = this.getBoundingInfo();
  20535. if (!this.subMeshes) {
  20536. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20537. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20538. }
  20539. else {
  20540. min = boundingInfo.boundingBox.minimumWorld;
  20541. max = boundingInfo.boundingBox.maximumWorld;
  20542. }
  20543. if (includeDescendants) {
  20544. var descendants = this.getDescendants(false);
  20545. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20546. var descendant = descendants_1[_i];
  20547. var childMesh = descendant;
  20548. childMesh.computeWorldMatrix(true);
  20549. // Filters meshes based on custom predicate function.
  20550. if (predicate && !predicate(childMesh)) {
  20551. continue;
  20552. }
  20553. //make sure we have the needed params to get mix and max
  20554. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20555. continue;
  20556. }
  20557. var childBoundingInfo = childMesh.getBoundingInfo();
  20558. var boundingBox = childBoundingInfo.boundingBox;
  20559. var minBox = boundingBox.minimumWorld;
  20560. var maxBox = boundingBox.maximumWorld;
  20561. BABYLON.Tools.CheckExtends(minBox, min, max);
  20562. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20563. }
  20564. }
  20565. return {
  20566. min: min,
  20567. max: max
  20568. };
  20569. };
  20570. /** @hidden */
  20571. AbstractMesh.prototype._updateBoundingInfo = function () {
  20572. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20573. this._boundingInfo.update(this.worldMatrixFromCache);
  20574. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20575. return this;
  20576. };
  20577. /** @hidden */
  20578. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20579. if (!this.subMeshes) {
  20580. return this;
  20581. }
  20582. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20583. var subMesh = this.subMeshes[subIndex];
  20584. if (!subMesh.IsGlobal) {
  20585. subMesh.updateBoundingInfo(matrix);
  20586. }
  20587. }
  20588. return this;
  20589. };
  20590. /** @hidden */
  20591. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20592. // Bounding info
  20593. this._updateBoundingInfo();
  20594. };
  20595. /**
  20596. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20597. * A mesh is in the frustum if its bounding box intersects the frustum
  20598. * @param frustumPlanes defines the frustum to test
  20599. * @returns true if the mesh is in the frustum planes
  20600. */
  20601. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20602. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes, this.cullingStrategy);
  20603. };
  20604. /**
  20605. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20606. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20607. * @param frustumPlanes defines the frustum to test
  20608. * @returns true if the mesh is completely in the frustum planes
  20609. */
  20610. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20611. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20612. };
  20613. /**
  20614. * True if the mesh intersects another mesh or a SolidParticle object
  20615. * @param mesh defines a target mesh or SolidParticle to test
  20616. * @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)
  20617. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20618. * @returns true if there is an intersection
  20619. */
  20620. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20621. if (precise === void 0) { precise = false; }
  20622. if (!this._boundingInfo || !mesh._boundingInfo) {
  20623. return false;
  20624. }
  20625. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20626. return true;
  20627. }
  20628. if (includeDescendants) {
  20629. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20630. var child = _a[_i];
  20631. if (child.intersectsMesh(mesh, precise, true)) {
  20632. return true;
  20633. }
  20634. }
  20635. }
  20636. return false;
  20637. };
  20638. /**
  20639. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20640. * @param point defines the point to test
  20641. * @returns true if there is an intersection
  20642. */
  20643. AbstractMesh.prototype.intersectsPoint = function (point) {
  20644. if (!this._boundingInfo) {
  20645. return false;
  20646. }
  20647. return this._boundingInfo.intersectsPoint(point);
  20648. };
  20649. /**
  20650. * Gets the current physics impostor
  20651. * @see http://doc.babylonjs.com/features/physics_engine
  20652. * @returns a physics impostor or null
  20653. */
  20654. AbstractMesh.prototype.getPhysicsImpostor = function () {
  20655. return this.physicsImpostor;
  20656. };
  20657. /**
  20658. * Gets the position of the current mesh in camera space
  20659. * @param camera defines the camera to use
  20660. * @returns a position
  20661. */
  20662. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20663. if (camera === void 0) { camera = null; }
  20664. if (!camera) {
  20665. camera = this.getScene().activeCamera;
  20666. }
  20667. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20668. };
  20669. /**
  20670. * Returns the distance from the mesh to the active camera
  20671. * @param camera defines the camera to use
  20672. * @returns the distance
  20673. */
  20674. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20675. if (camera === void 0) { camera = null; }
  20676. if (!camera) {
  20677. camera = this.getScene().activeCamera;
  20678. }
  20679. return this.absolutePosition.subtract(camera.position).length();
  20680. };
  20681. /**
  20682. * Apply a physic impulse to the mesh
  20683. * @param force defines the force to apply
  20684. * @param contactPoint defines where to apply the force
  20685. * @returns the current mesh
  20686. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  20687. */
  20688. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  20689. if (!this.physicsImpostor) {
  20690. return this;
  20691. }
  20692. this.physicsImpostor.applyImpulse(force, contactPoint);
  20693. return this;
  20694. };
  20695. /**
  20696. * Creates a physic joint between two meshes
  20697. * @param otherMesh defines the other mesh to use
  20698. * @param pivot1 defines the pivot to use on this mesh
  20699. * @param pivot2 defines the pivot to use on the other mesh
  20700. * @param options defines additional options (can be plugin dependent)
  20701. * @returns the current mesh
  20702. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  20703. */
  20704. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  20705. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  20706. return this;
  20707. }
  20708. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  20709. mainPivot: pivot1,
  20710. connectedPivot: pivot2,
  20711. nativeParams: options
  20712. });
  20713. return this;
  20714. };
  20715. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20716. // Collisions
  20717. /**
  20718. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20719. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20720. */
  20721. get: function () {
  20722. return this._checkCollisions;
  20723. },
  20724. set: function (collisionEnabled) {
  20725. this._checkCollisions = collisionEnabled;
  20726. if (this.getScene().workerCollisions) {
  20727. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20728. }
  20729. },
  20730. enumerable: true,
  20731. configurable: true
  20732. });
  20733. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20734. /**
  20735. * Gets Collider object used to compute collisions (not physics)
  20736. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20737. */
  20738. get: function () {
  20739. return this._collider;
  20740. },
  20741. enumerable: true,
  20742. configurable: true
  20743. });
  20744. /**
  20745. * Move the mesh using collision engine
  20746. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20747. * @param displacement defines the requested displacement vector
  20748. * @returns the current mesh
  20749. */
  20750. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20751. var globalPosition = this.getAbsolutePosition();
  20752. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20753. if (!this._collider) {
  20754. this._collider = new BABYLON.Collider();
  20755. }
  20756. this._collider._radius = this.ellipsoid;
  20757. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20758. return this;
  20759. };
  20760. // Collisions
  20761. /** @hidden */
  20762. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20763. this._generatePointsArray();
  20764. if (!this._positions) {
  20765. return this;
  20766. }
  20767. // Transformation
  20768. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20769. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20770. subMesh._lastColliderWorldVertices = [];
  20771. subMesh._trianglePlanes = [];
  20772. var start = subMesh.verticesStart;
  20773. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20774. for (var i = start; i < end; i++) {
  20775. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20776. }
  20777. }
  20778. // Collide
  20779. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20780. if (collider.collisionFound) {
  20781. collider.collidedMesh = this;
  20782. }
  20783. return this;
  20784. };
  20785. /** @hidden */
  20786. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20787. var subMeshes = this._scene.getCollidingSubMeshCandidates(this, collider);
  20788. var len = subMeshes.length;
  20789. for (var index = 0; index < len; index++) {
  20790. var subMesh = subMeshes.data[index];
  20791. // Bounding test
  20792. if (len > 1 && !subMesh._checkCollision(collider))
  20793. continue;
  20794. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20795. }
  20796. return this;
  20797. };
  20798. /** @hidden */
  20799. AbstractMesh.prototype._checkCollision = function (collider) {
  20800. // Bounding box test
  20801. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20802. return this;
  20803. // Transformation matrix
  20804. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20805. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20806. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20807. return this;
  20808. };
  20809. // Picking
  20810. /** @hidden */
  20811. AbstractMesh.prototype._generatePointsArray = function () {
  20812. return false;
  20813. };
  20814. /**
  20815. * Checks if the passed Ray intersects with the mesh
  20816. * @param ray defines the ray to use
  20817. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  20818. * @returns the picking info
  20819. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20820. */
  20821. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20822. var pickingInfo = new BABYLON.PickingInfo();
  20823. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20824. return pickingInfo;
  20825. }
  20826. if (!this._generatePointsArray()) {
  20827. return pickingInfo;
  20828. }
  20829. var intersectInfo = null;
  20830. var subMeshes = this._scene.getIntersectingSubMeshCandidates(this, ray);
  20831. var len = subMeshes.length;
  20832. for (var index = 0; index < len; index++) {
  20833. var subMesh = subMeshes.data[index];
  20834. // Bounding test
  20835. if (len > 1 && !subMesh.canIntersects(ray))
  20836. continue;
  20837. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20838. if (currentIntersectInfo) {
  20839. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20840. intersectInfo = currentIntersectInfo;
  20841. intersectInfo.subMeshId = index;
  20842. if (fastCheck) {
  20843. break;
  20844. }
  20845. }
  20846. }
  20847. }
  20848. if (intersectInfo) {
  20849. // Get picked point
  20850. var world = this.getWorldMatrix();
  20851. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20852. var direction = ray.direction.clone();
  20853. direction = direction.scale(intersectInfo.distance);
  20854. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20855. var pickedPoint = worldOrigin.add(worldDirection);
  20856. // Return result
  20857. pickingInfo.hit = true;
  20858. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20859. pickingInfo.pickedPoint = pickedPoint;
  20860. pickingInfo.pickedMesh = this;
  20861. pickingInfo.bu = intersectInfo.bu || 0;
  20862. pickingInfo.bv = intersectInfo.bv || 0;
  20863. pickingInfo.faceId = intersectInfo.faceId;
  20864. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20865. return pickingInfo;
  20866. }
  20867. return pickingInfo;
  20868. };
  20869. /**
  20870. * Clones the current mesh
  20871. * @param name defines the mesh name
  20872. * @param newParent defines the new mesh parent
  20873. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  20874. * @returns the new mesh
  20875. */
  20876. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20877. return null;
  20878. };
  20879. /**
  20880. * Disposes all the submeshes of the current meshnp
  20881. * @returns the current mesh
  20882. */
  20883. AbstractMesh.prototype.releaseSubMeshes = function () {
  20884. if (this.subMeshes) {
  20885. while (this.subMeshes.length) {
  20886. this.subMeshes[0].dispose();
  20887. }
  20888. }
  20889. else {
  20890. this.subMeshes = new Array();
  20891. }
  20892. return this;
  20893. };
  20894. /**
  20895. * Releases resources associated with this abstract mesh.
  20896. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20897. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20898. */
  20899. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20900. var _this = this;
  20901. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20902. var index;
  20903. // Smart Array Retainers.
  20904. this.getScene().freeActiveMeshes();
  20905. this.getScene().freeRenderingGroups();
  20906. // Action manager
  20907. if (this.actionManager !== undefined && this.actionManager !== null) {
  20908. this.actionManager.dispose();
  20909. this.actionManager = null;
  20910. }
  20911. // Skeleton
  20912. this._skeleton = null;
  20913. // Physics
  20914. if (this.physicsImpostor) {
  20915. this.physicsImpostor.dispose( /*!doNotRecurse*/);
  20916. }
  20917. // Intersections in progress
  20918. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  20919. var other = this._intersectionsInProgress[index];
  20920. var pos = other._intersectionsInProgress.indexOf(this);
  20921. other._intersectionsInProgress.splice(pos, 1);
  20922. }
  20923. this._intersectionsInProgress = [];
  20924. // Lights
  20925. var lights = this.getScene().lights;
  20926. lights.forEach(function (light) {
  20927. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  20928. if (meshIndex !== -1) {
  20929. light.includedOnlyMeshes.splice(meshIndex, 1);
  20930. }
  20931. meshIndex = light.excludedMeshes.indexOf(_this);
  20932. if (meshIndex !== -1) {
  20933. light.excludedMeshes.splice(meshIndex, 1);
  20934. }
  20935. // Shadow generators
  20936. var generator = light.getShadowGenerator();
  20937. if (generator) {
  20938. var shadowMap = generator.getShadowMap();
  20939. if (shadowMap && shadowMap.renderList) {
  20940. meshIndex = shadowMap.renderList.indexOf(_this);
  20941. if (meshIndex !== -1) {
  20942. shadowMap.renderList.splice(meshIndex, 1);
  20943. }
  20944. }
  20945. }
  20946. });
  20947. // SubMeshes
  20948. if (this.getClassName() !== "InstancedMesh") {
  20949. this.releaseSubMeshes();
  20950. }
  20951. // Query
  20952. var engine = this.getScene().getEngine();
  20953. if (this._occlusionQuery) {
  20954. this._isOcclusionQueryInProgress = false;
  20955. engine.deleteQuery(this._occlusionQuery);
  20956. this._occlusionQuery = null;
  20957. }
  20958. // Engine
  20959. engine.wipeCaches();
  20960. // Remove from scene
  20961. this.getScene().removeMesh(this);
  20962. if (disposeMaterialAndTextures) {
  20963. if (this.material) {
  20964. this.material.dispose(false, true);
  20965. }
  20966. }
  20967. if (!doNotRecurse) {
  20968. // Particles
  20969. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  20970. if (this.getScene().particleSystems[index].emitter === this) {
  20971. this.getScene().particleSystems[index].dispose();
  20972. index--;
  20973. }
  20974. }
  20975. }
  20976. // facet data
  20977. if (this._facetDataEnabled) {
  20978. this.disableFacetData();
  20979. }
  20980. this.onAfterWorldMatrixUpdateObservable.clear();
  20981. this.onCollideObservable.clear();
  20982. this.onCollisionPositionChangeObservable.clear();
  20983. this.onRebuildObservable.clear();
  20984. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20985. };
  20986. /**
  20987. * Adds the passed mesh as a child to the current mesh
  20988. * @param mesh defines the child mesh
  20989. * @returns the current mesh
  20990. */
  20991. AbstractMesh.prototype.addChild = function (mesh) {
  20992. mesh.setParent(this);
  20993. return this;
  20994. };
  20995. /**
  20996. * Removes the passed mesh from the current mesh children list
  20997. * @param mesh defines the child mesh
  20998. * @returns the current mesh
  20999. */
  21000. AbstractMesh.prototype.removeChild = function (mesh) {
  21001. mesh.setParent(null);
  21002. return this;
  21003. };
  21004. // Facet data
  21005. /** @hidden */
  21006. AbstractMesh.prototype._initFacetData = function () {
  21007. if (!this._facetNormals) {
  21008. this._facetNormals = new Array();
  21009. }
  21010. if (!this._facetPositions) {
  21011. this._facetPositions = new Array();
  21012. }
  21013. if (!this._facetPartitioning) {
  21014. this._facetPartitioning = new Array();
  21015. }
  21016. this._facetNb = (this.getIndices().length / 3) | 0;
  21017. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  21018. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  21019. for (var f = 0; f < this._facetNb; f++) {
  21020. this._facetNormals[f] = BABYLON.Vector3.Zero();
  21021. this._facetPositions[f] = BABYLON.Vector3.Zero();
  21022. }
  21023. this._facetDataEnabled = true;
  21024. return this;
  21025. };
  21026. /**
  21027. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  21028. * This method can be called within the render loop.
  21029. * 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
  21030. * @returns the current mesh
  21031. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21032. */
  21033. AbstractMesh.prototype.updateFacetData = function () {
  21034. if (!this._facetDataEnabled) {
  21035. this._initFacetData();
  21036. }
  21037. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21038. var indices = this.getIndices();
  21039. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21040. var bInfo = this.getBoundingInfo();
  21041. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  21042. // init arrays, matrix and sort function on first call
  21043. this._facetDepthSortEnabled = true;
  21044. if (indices instanceof Uint16Array) {
  21045. this._depthSortedIndices = new Uint16Array(indices);
  21046. }
  21047. else if (indices instanceof Uint32Array) {
  21048. this._depthSortedIndices = new Uint32Array(indices);
  21049. }
  21050. else {
  21051. var needs32bits = false;
  21052. for (var i = 0; i < indices.length; i++) {
  21053. if (indices[i] > 65535) {
  21054. needs32bits = true;
  21055. break;
  21056. }
  21057. }
  21058. if (needs32bits) {
  21059. this._depthSortedIndices = new Uint32Array(indices);
  21060. }
  21061. else {
  21062. this._depthSortedIndices = new Uint16Array(indices);
  21063. }
  21064. }
  21065. this._facetDepthSortFunction = function (f1, f2) {
  21066. return (f2.sqDistance - f1.sqDistance);
  21067. };
  21068. if (!this._facetDepthSortFrom) {
  21069. var camera = this.getScene().activeCamera;
  21070. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  21071. }
  21072. this._depthSortedFacets = [];
  21073. for (var f = 0; f < this._facetNb; f++) {
  21074. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  21075. this._depthSortedFacets.push(depthSortedFacet);
  21076. }
  21077. this._invertedMatrix = BABYLON.Matrix.Identity();
  21078. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  21079. }
  21080. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  21081. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  21082. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  21083. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  21084. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  21085. this._subDiv.max = this._partitioningSubdivisions;
  21086. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  21087. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  21088. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  21089. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  21090. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  21091. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  21092. // set the parameters for ComputeNormals()
  21093. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  21094. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  21095. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  21096. this._facetParameters.bInfo = bInfo;
  21097. this._facetParameters.bbSize = this._bbSize;
  21098. this._facetParameters.subDiv = this._subDiv;
  21099. this._facetParameters.ratio = this.partitioningBBoxRatio;
  21100. this._facetParameters.depthSort = this._facetDepthSort;
  21101. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21102. this.computeWorldMatrix(true);
  21103. this._worldMatrix.invertToRef(this._invertedMatrix);
  21104. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  21105. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  21106. }
  21107. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  21108. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  21109. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21110. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  21111. var l = (this._depthSortedIndices.length / 3) | 0;
  21112. for (var f = 0; f < l; f++) {
  21113. var sind = this._depthSortedFacets[f].ind;
  21114. this._depthSortedIndices[f * 3] = indices[sind];
  21115. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  21116. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  21117. }
  21118. this.updateIndices(this._depthSortedIndices);
  21119. }
  21120. return this;
  21121. };
  21122. /**
  21123. * Returns the facetLocalNormals array.
  21124. * The normals are expressed in the mesh local spac
  21125. * @returns an array of Vector3
  21126. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21127. */
  21128. AbstractMesh.prototype.getFacetLocalNormals = function () {
  21129. if (!this._facetNormals) {
  21130. this.updateFacetData();
  21131. }
  21132. return this._facetNormals;
  21133. };
  21134. /**
  21135. * Returns the facetLocalPositions array.
  21136. * The facet positions are expressed in the mesh local space
  21137. * @returns an array of Vector3
  21138. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21139. */
  21140. AbstractMesh.prototype.getFacetLocalPositions = function () {
  21141. if (!this._facetPositions) {
  21142. this.updateFacetData();
  21143. }
  21144. return this._facetPositions;
  21145. };
  21146. /**
  21147. * Returns the facetLocalPartioning array
  21148. * @returns an array of array of numbers
  21149. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21150. */
  21151. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  21152. if (!this._facetPartitioning) {
  21153. this.updateFacetData();
  21154. }
  21155. return this._facetPartitioning;
  21156. };
  21157. /**
  21158. * Returns the i-th facet position in the world system.
  21159. * This method allocates a new Vector3 per call
  21160. * @param i defines the facet index
  21161. * @returns a new Vector3
  21162. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21163. */
  21164. AbstractMesh.prototype.getFacetPosition = function (i) {
  21165. var pos = BABYLON.Vector3.Zero();
  21166. this.getFacetPositionToRef(i, pos);
  21167. return pos;
  21168. };
  21169. /**
  21170. * Sets the reference Vector3 with the i-th facet position in the world system
  21171. * @param i defines the facet index
  21172. * @param ref defines the target vector
  21173. * @returns the current mesh
  21174. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21175. */
  21176. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  21177. var localPos = (this.getFacetLocalPositions())[i];
  21178. var world = this.getWorldMatrix();
  21179. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  21180. return this;
  21181. };
  21182. /**
  21183. * Returns the i-th facet normal in the world system.
  21184. * This method allocates a new Vector3 per call
  21185. * @param i defines the facet index
  21186. * @returns a new Vector3
  21187. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21188. */
  21189. AbstractMesh.prototype.getFacetNormal = function (i) {
  21190. var norm = BABYLON.Vector3.Zero();
  21191. this.getFacetNormalToRef(i, norm);
  21192. return norm;
  21193. };
  21194. /**
  21195. * Sets the reference Vector3 with the i-th facet normal in the world system
  21196. * @param i defines the facet index
  21197. * @param ref defines the target vector
  21198. * @returns the current mesh
  21199. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21200. */
  21201. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  21202. var localNorm = (this.getFacetLocalNormals())[i];
  21203. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  21204. return this;
  21205. };
  21206. /**
  21207. * 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)
  21208. * @param x defines x coordinate
  21209. * @param y defines y coordinate
  21210. * @param z defines z coordinate
  21211. * @returns the array of facet indexes
  21212. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21213. */
  21214. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  21215. var bInfo = this.getBoundingInfo();
  21216. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  21217. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  21218. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  21219. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  21220. return null;
  21221. }
  21222. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  21223. };
  21224. /**
  21225. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  21226. * @param projected sets as the (x,y,z) world projection on the facet
  21227. * @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
  21228. * @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
  21229. * @param x defines x coordinate
  21230. * @param y defines y coordinate
  21231. * @param z defines z coordinate
  21232. * @returns the face index if found (or null instead)
  21233. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21234. */
  21235. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21236. if (checkFace === void 0) { checkFace = false; }
  21237. if (facing === void 0) { facing = true; }
  21238. var world = this.getWorldMatrix();
  21239. var invMat = BABYLON.Tmp.Matrix[5];
  21240. world.invertToRef(invMat);
  21241. var invVect = BABYLON.Tmp.Vector3[8];
  21242. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21243. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21244. if (projected) {
  21245. // tranform the local computed projected vector to world coordinates
  21246. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21247. }
  21248. return closest;
  21249. };
  21250. /**
  21251. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21252. * @param projected sets as the (x,y,z) local projection on the facet
  21253. * @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
  21254. * @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
  21255. * @param x defines x coordinate
  21256. * @param y defines y coordinate
  21257. * @param z defines z coordinate
  21258. * @returns the face index if found (or null instead)
  21259. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21260. */
  21261. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21262. if (checkFace === void 0) { checkFace = false; }
  21263. if (facing === void 0) { facing = true; }
  21264. var closest = null;
  21265. var tmpx = 0.0;
  21266. var tmpy = 0.0;
  21267. var tmpz = 0.0;
  21268. var d = 0.0; // tmp dot facet normal * facet position
  21269. var t0 = 0.0;
  21270. var projx = 0.0;
  21271. var projy = 0.0;
  21272. var projz = 0.0;
  21273. // Get all the facets in the same partitioning block than (x, y, z)
  21274. var facetPositions = this.getFacetLocalPositions();
  21275. var facetNormals = this.getFacetLocalNormals();
  21276. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21277. if (!facetsInBlock) {
  21278. return null;
  21279. }
  21280. // Get the closest facet to (x, y, z)
  21281. var shortest = Number.MAX_VALUE; // init distance vars
  21282. var tmpDistance = shortest;
  21283. var fib; // current facet in the block
  21284. var norm; // current facet normal
  21285. var p0; // current facet barycenter position
  21286. // loop on all the facets in the current partitioning block
  21287. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21288. fib = facetsInBlock[idx];
  21289. norm = facetNormals[fib];
  21290. p0 = facetPositions[fib];
  21291. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21292. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21293. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21294. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21295. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21296. projx = x + norm.x * t0;
  21297. projy = y + norm.y * t0;
  21298. projz = z + norm.z * t0;
  21299. tmpx = projx - x;
  21300. tmpy = projy - y;
  21301. tmpz = projz - z;
  21302. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21303. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21304. shortest = tmpDistance;
  21305. closest = fib;
  21306. if (projected) {
  21307. projected.x = projx;
  21308. projected.y = projy;
  21309. projected.z = projz;
  21310. }
  21311. }
  21312. }
  21313. }
  21314. return closest;
  21315. };
  21316. /**
  21317. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21318. * @returns the parameters
  21319. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21320. */
  21321. AbstractMesh.prototype.getFacetDataParameters = function () {
  21322. return this._facetParameters;
  21323. };
  21324. /**
  21325. * Disables the feature FacetData and frees the related memory
  21326. * @returns the current mesh
  21327. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21328. */
  21329. AbstractMesh.prototype.disableFacetData = function () {
  21330. if (this._facetDataEnabled) {
  21331. this._facetDataEnabled = false;
  21332. this._facetPositions = new Array();
  21333. this._facetNormals = new Array();
  21334. this._facetPartitioning = new Array();
  21335. this._facetParameters = null;
  21336. this._depthSortedIndices = new Uint32Array(0);
  21337. }
  21338. return this;
  21339. };
  21340. /**
  21341. * Updates the AbstractMesh indices array
  21342. * @param indices defines the data source
  21343. * @returns the current mesh
  21344. */
  21345. AbstractMesh.prototype.updateIndices = function (indices) {
  21346. return this;
  21347. };
  21348. /**
  21349. * Creates new normals data for the mesh
  21350. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21351. * @returns the current mesh
  21352. */
  21353. AbstractMesh.prototype.createNormals = function (updatable) {
  21354. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21355. var indices = this.getIndices();
  21356. var normals;
  21357. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21358. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21359. }
  21360. else {
  21361. normals = [];
  21362. }
  21363. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21364. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21365. return this;
  21366. };
  21367. /**
  21368. * Align the mesh with a normal
  21369. * @param normal defines the normal to use
  21370. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21371. * @returns the current mesh
  21372. */
  21373. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21374. if (!upDirection) {
  21375. upDirection = BABYLON.Axis.Y;
  21376. }
  21377. var axisX = BABYLON.Tmp.Vector3[0];
  21378. var axisZ = BABYLON.Tmp.Vector3[1];
  21379. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21380. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21381. if (this.rotationQuaternion) {
  21382. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21383. }
  21384. else {
  21385. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21386. }
  21387. return this;
  21388. };
  21389. /** @hidden */
  21390. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21391. this._isOccluded = false;
  21392. };
  21393. /** No occlusion */
  21394. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21395. /** Occlusion set to optimisitic */
  21396. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21397. /** Occlusion set to strict */
  21398. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21399. /** Use an accurante occlusion algorithm */
  21400. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21401. /** Use a conservative occlusion algorithm */
  21402. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21403. /** Default culling strategy with bounding box and bounding sphere and then frustum culling */
  21404. AbstractMesh.CULLINGSTRATEGY_STANDARD = 0;
  21405. /** Culling strategy with bounding sphere only and then frustum culling */
  21406. AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY = 1;
  21407. return AbstractMesh;
  21408. }(BABYLON.TransformNode));
  21409. BABYLON.AbstractMesh = AbstractMesh;
  21410. })(BABYLON || (BABYLON = {}));
  21411. //# sourceMappingURL=babylon.abstractMesh.js.map
  21412. var BABYLON;
  21413. (function (BABYLON) {
  21414. /**
  21415. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21416. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21417. * 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.
  21418. */
  21419. var Light = /** @class */ (function (_super) {
  21420. __extends(Light, _super);
  21421. /**
  21422. * Creates a Light object in the scene.
  21423. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21424. * @param name The firendly name of the light
  21425. * @param scene The scene the light belongs too
  21426. */
  21427. function Light(name, scene) {
  21428. var _this = _super.call(this, name, scene) || this;
  21429. /**
  21430. * Diffuse gives the basic color to an object.
  21431. */
  21432. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21433. /**
  21434. * Specular produces a highlight color on an object.
  21435. * Note: This is note affecting PBR materials.
  21436. */
  21437. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21438. /**
  21439. * Defines the falloff type for this light. This lets overrriding how punctual light are
  21440. * falling off base on range or angle.
  21441. * This can be set to any values in Light.FALLOFF_x.
  21442. *
  21443. * Note: This is only usefull for PBR Materials at the moment. This could be extended if required to
  21444. * other types of materials.
  21445. */
  21446. _this.falloffType = Light.FALLOFF_DEFAULT;
  21447. /**
  21448. * Strength of the light.
  21449. * Note: By default it is define in the framework own unit.
  21450. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21451. */
  21452. _this.intensity = 1.0;
  21453. _this._range = Number.MAX_VALUE;
  21454. _this._inverseSquaredRange = 0;
  21455. /**
  21456. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21457. * of light.
  21458. */
  21459. _this._photometricScale = 1.0;
  21460. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21461. _this._radius = 0.00001;
  21462. /**
  21463. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21464. * exceeding the number allowed of the materials.
  21465. */
  21466. _this.renderPriority = 0;
  21467. _this._shadowEnabled = true;
  21468. _this._excludeWithLayerMask = 0;
  21469. _this._includeOnlyWithLayerMask = 0;
  21470. _this._lightmapMode = 0;
  21471. /**
  21472. * @hidden Internal use only.
  21473. */
  21474. _this._excludedMeshesIds = new Array();
  21475. /**
  21476. * @hidden Internal use only.
  21477. */
  21478. _this._includedOnlyMeshesIds = new Array();
  21479. _this.getScene().addLight(_this);
  21480. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21481. _this._buildUniformLayout();
  21482. _this.includedOnlyMeshes = new Array();
  21483. _this.excludedMeshes = new Array();
  21484. _this._resyncMeshes();
  21485. return _this;
  21486. }
  21487. Object.defineProperty(Light.prototype, "range", {
  21488. /**
  21489. * Defines how far from the source the light is impacting in scene units.
  21490. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21491. */
  21492. get: function () {
  21493. return this._range;
  21494. },
  21495. /**
  21496. * Defines how far from the source the light is impacting in scene units.
  21497. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21498. */
  21499. set: function (value) {
  21500. this._range = value;
  21501. this._inverseSquaredRange = 1.0 / (this.range * this.range);
  21502. },
  21503. enumerable: true,
  21504. configurable: true
  21505. });
  21506. Object.defineProperty(Light.prototype, "intensityMode", {
  21507. /**
  21508. * Gets the photometric scale used to interpret the intensity.
  21509. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21510. */
  21511. get: function () {
  21512. return this._intensityMode;
  21513. },
  21514. /**
  21515. * Sets the photometric scale used to interpret the intensity.
  21516. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21517. */
  21518. set: function (value) {
  21519. this._intensityMode = value;
  21520. this._computePhotometricScale();
  21521. },
  21522. enumerable: true,
  21523. configurable: true
  21524. });
  21525. ;
  21526. ;
  21527. Object.defineProperty(Light.prototype, "radius", {
  21528. /**
  21529. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21530. */
  21531. get: function () {
  21532. return this._radius;
  21533. },
  21534. /**
  21535. * sets the light radius used by PBR Materials to simulate soft area lights.
  21536. */
  21537. set: function (value) {
  21538. this._radius = value;
  21539. this._computePhotometricScale();
  21540. },
  21541. enumerable: true,
  21542. configurable: true
  21543. });
  21544. ;
  21545. ;
  21546. Object.defineProperty(Light.prototype, "shadowEnabled", {
  21547. /**
  21548. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21549. * the current shadow generator.
  21550. */
  21551. get: function () {
  21552. return this._shadowEnabled;
  21553. },
  21554. /**
  21555. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21556. * the current shadow generator.
  21557. */
  21558. set: function (value) {
  21559. if (this._shadowEnabled === value) {
  21560. return;
  21561. }
  21562. this._shadowEnabled = value;
  21563. this._markMeshesAsLightDirty();
  21564. },
  21565. enumerable: true,
  21566. configurable: true
  21567. });
  21568. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21569. /**
  21570. * Gets the only meshes impacted by this light.
  21571. */
  21572. get: function () {
  21573. return this._includedOnlyMeshes;
  21574. },
  21575. /**
  21576. * Sets the only meshes impacted by this light.
  21577. */
  21578. set: function (value) {
  21579. this._includedOnlyMeshes = value;
  21580. this._hookArrayForIncludedOnly(value);
  21581. },
  21582. enumerable: true,
  21583. configurable: true
  21584. });
  21585. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21586. /**
  21587. * Gets the meshes not impacted by this light.
  21588. */
  21589. get: function () {
  21590. return this._excludedMeshes;
  21591. },
  21592. /**
  21593. * Sets the meshes not impacted by this light.
  21594. */
  21595. set: function (value) {
  21596. this._excludedMeshes = value;
  21597. this._hookArrayForExcluded(value);
  21598. },
  21599. enumerable: true,
  21600. configurable: true
  21601. });
  21602. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21603. /**
  21604. * Gets the layer id use to find what meshes are not impacted by the light.
  21605. * Inactive if 0
  21606. */
  21607. get: function () {
  21608. return this._excludeWithLayerMask;
  21609. },
  21610. /**
  21611. * Sets the layer id use to find what meshes are not impacted by the light.
  21612. * Inactive if 0
  21613. */
  21614. set: function (value) {
  21615. this._excludeWithLayerMask = value;
  21616. this._resyncMeshes();
  21617. },
  21618. enumerable: true,
  21619. configurable: true
  21620. });
  21621. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21622. /**
  21623. * Gets the layer id use to find what meshes are impacted by the light.
  21624. * Inactive if 0
  21625. */
  21626. get: function () {
  21627. return this._includeOnlyWithLayerMask;
  21628. },
  21629. /**
  21630. * Sets the layer id use to find what meshes are impacted by the light.
  21631. * Inactive if 0
  21632. */
  21633. set: function (value) {
  21634. this._includeOnlyWithLayerMask = value;
  21635. this._resyncMeshes();
  21636. },
  21637. enumerable: true,
  21638. configurable: true
  21639. });
  21640. Object.defineProperty(Light.prototype, "lightmapMode", {
  21641. /**
  21642. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21643. */
  21644. get: function () {
  21645. return this._lightmapMode;
  21646. },
  21647. /**
  21648. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21649. */
  21650. set: function (value) {
  21651. if (this._lightmapMode === value) {
  21652. return;
  21653. }
  21654. this._lightmapMode = value;
  21655. this._markMeshesAsLightDirty();
  21656. },
  21657. enumerable: true,
  21658. configurable: true
  21659. });
  21660. /**
  21661. * Returns the string "Light".
  21662. * @returns the class name
  21663. */
  21664. Light.prototype.getClassName = function () {
  21665. return "Light";
  21666. };
  21667. /**
  21668. * Converts the light information to a readable string for debug purpose.
  21669. * @param fullDetails Supports for multiple levels of logging within scene loading
  21670. * @returns the human readable light info
  21671. */
  21672. Light.prototype.toString = function (fullDetails) {
  21673. var ret = "Name: " + this.name;
  21674. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21675. if (this.animations) {
  21676. for (var i = 0; i < this.animations.length; i++) {
  21677. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21678. }
  21679. }
  21680. if (fullDetails) {
  21681. }
  21682. return ret;
  21683. };
  21684. /**
  21685. * Set the enabled state of this node.
  21686. * @param value - the new enabled state
  21687. */
  21688. Light.prototype.setEnabled = function (value) {
  21689. _super.prototype.setEnabled.call(this, value);
  21690. this._resyncMeshes();
  21691. };
  21692. /**
  21693. * Returns the Light associated shadow generator if any.
  21694. * @return the associated shadow generator.
  21695. */
  21696. Light.prototype.getShadowGenerator = function () {
  21697. return this._shadowGenerator;
  21698. };
  21699. /**
  21700. * Returns a Vector3, the absolute light position in the World.
  21701. * @returns the world space position of the light
  21702. */
  21703. Light.prototype.getAbsolutePosition = function () {
  21704. return BABYLON.Vector3.Zero();
  21705. };
  21706. /**
  21707. * Specifies if the light will affect the passed mesh.
  21708. * @param mesh The mesh to test against the light
  21709. * @return true the mesh is affected otherwise, false.
  21710. */
  21711. Light.prototype.canAffectMesh = function (mesh) {
  21712. if (!mesh) {
  21713. return true;
  21714. }
  21715. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21716. return false;
  21717. }
  21718. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21719. return false;
  21720. }
  21721. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21722. return false;
  21723. }
  21724. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21725. return false;
  21726. }
  21727. return true;
  21728. };
  21729. /**
  21730. * Computes and Returns the light World matrix.
  21731. * @returns the world matrix
  21732. */
  21733. Light.prototype.getWorldMatrix = function () {
  21734. this._currentRenderId = this.getScene().getRenderId();
  21735. this._childRenderId = this._currentRenderId;
  21736. var worldMatrix = this._getWorldMatrix();
  21737. if (this.parent && this.parent.getWorldMatrix) {
  21738. if (!this._parentedWorldMatrix) {
  21739. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  21740. }
  21741. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  21742. this._markSyncedWithParent();
  21743. return this._parentedWorldMatrix;
  21744. }
  21745. return worldMatrix;
  21746. };
  21747. /**
  21748. * Sort function to order lights for rendering.
  21749. * @param a First Light object to compare to second.
  21750. * @param b Second Light object to compare first.
  21751. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21752. */
  21753. Light.CompareLightsPriority = function (a, b) {
  21754. //shadow-casting lights have priority over non-shadow-casting lights
  21755. //the renderPrioirty is a secondary sort criterion
  21756. if (a.shadowEnabled !== b.shadowEnabled) {
  21757. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21758. }
  21759. return b.renderPriority - a.renderPriority;
  21760. };
  21761. /**
  21762. * Releases resources associated with this node.
  21763. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21764. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21765. */
  21766. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21767. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21768. if (this._shadowGenerator) {
  21769. this._shadowGenerator.dispose();
  21770. this._shadowGenerator = null;
  21771. }
  21772. // Animations
  21773. this.getScene().stopAnimation(this);
  21774. // Remove from meshes
  21775. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21776. var mesh = _a[_i];
  21777. mesh._removeLightSource(this);
  21778. }
  21779. this._uniformBuffer.dispose();
  21780. // Remove from scene
  21781. this.getScene().removeLight(this);
  21782. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21783. };
  21784. /**
  21785. * Returns the light type ID (integer).
  21786. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  21787. */
  21788. Light.prototype.getTypeID = function () {
  21789. return 0;
  21790. };
  21791. /**
  21792. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  21793. * @returns the scaled intensity in intensity mode unit
  21794. */
  21795. Light.prototype.getScaledIntensity = function () {
  21796. return this._photometricScale * this.intensity;
  21797. };
  21798. /**
  21799. * Returns a new Light object, named "name", from the current one.
  21800. * @param name The name of the cloned light
  21801. * @returns the new created light
  21802. */
  21803. Light.prototype.clone = function (name) {
  21804. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  21805. if (!constructor) {
  21806. return null;
  21807. }
  21808. return BABYLON.SerializationHelper.Clone(constructor, this);
  21809. };
  21810. /**
  21811. * Serializes the current light into a Serialization object.
  21812. * @returns the serialized object.
  21813. */
  21814. Light.prototype.serialize = function () {
  21815. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21816. // Type
  21817. serializationObject.type = this.getTypeID();
  21818. // Parent
  21819. if (this.parent) {
  21820. serializationObject.parentId = this.parent.id;
  21821. }
  21822. // Inclusion / exclusions
  21823. if (this.excludedMeshes.length > 0) {
  21824. serializationObject.excludedMeshesIds = [];
  21825. this.excludedMeshes.forEach(function (mesh) {
  21826. serializationObject.excludedMeshesIds.push(mesh.id);
  21827. });
  21828. }
  21829. if (this.includedOnlyMeshes.length > 0) {
  21830. serializationObject.includedOnlyMeshesIds = [];
  21831. this.includedOnlyMeshes.forEach(function (mesh) {
  21832. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  21833. });
  21834. }
  21835. // Animations
  21836. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21837. serializationObject.ranges = this.serializeAnimationRanges();
  21838. return serializationObject;
  21839. };
  21840. /**
  21841. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  21842. * This new light is named "name" and added to the passed scene.
  21843. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  21844. * @param name The friendly name of the light
  21845. * @param scene The scene the new light will belong to
  21846. * @returns the constructor function
  21847. */
  21848. Light.GetConstructorFromName = function (type, name, scene) {
  21849. var constructorFunc = BABYLON.Node.Construct("Light_Type_" + type, name, scene);
  21850. if (constructorFunc) {
  21851. return constructorFunc;
  21852. }
  21853. // Default to no light for none present once.
  21854. return null;
  21855. };
  21856. /**
  21857. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  21858. * @param parsedLight The JSON representation of the light
  21859. * @param scene The scene to create the parsed light in
  21860. * @returns the created light after parsing
  21861. */
  21862. Light.Parse = function (parsedLight, scene) {
  21863. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  21864. if (!constructor) {
  21865. return null;
  21866. }
  21867. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  21868. // Inclusion / exclusions
  21869. if (parsedLight.excludedMeshesIds) {
  21870. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  21871. }
  21872. if (parsedLight.includedOnlyMeshesIds) {
  21873. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  21874. }
  21875. // Parent
  21876. if (parsedLight.parentId) {
  21877. light._waitingParentId = parsedLight.parentId;
  21878. }
  21879. // Animations
  21880. if (parsedLight.animations) {
  21881. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  21882. var parsedAnimation = parsedLight.animations[animationIndex];
  21883. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21884. }
  21885. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  21886. }
  21887. if (parsedLight.autoAnimate) {
  21888. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  21889. }
  21890. return light;
  21891. };
  21892. Light.prototype._hookArrayForExcluded = function (array) {
  21893. var _this = this;
  21894. var oldPush = array.push;
  21895. array.push = function () {
  21896. var items = [];
  21897. for (var _i = 0; _i < arguments.length; _i++) {
  21898. items[_i] = arguments[_i];
  21899. }
  21900. var result = oldPush.apply(array, items);
  21901. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  21902. var item = items_1[_a];
  21903. item._resyncLighSource(_this);
  21904. }
  21905. return result;
  21906. };
  21907. var oldSplice = array.splice;
  21908. array.splice = function (index, deleteCount) {
  21909. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21910. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  21911. var item = deleted_1[_i];
  21912. item._resyncLighSource(_this);
  21913. }
  21914. return deleted;
  21915. };
  21916. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  21917. var item = array_1[_i];
  21918. item._resyncLighSource(this);
  21919. }
  21920. };
  21921. Light.prototype._hookArrayForIncludedOnly = function (array) {
  21922. var _this = this;
  21923. var oldPush = array.push;
  21924. array.push = function () {
  21925. var items = [];
  21926. for (var _i = 0; _i < arguments.length; _i++) {
  21927. items[_i] = arguments[_i];
  21928. }
  21929. var result = oldPush.apply(array, items);
  21930. _this._resyncMeshes();
  21931. return result;
  21932. };
  21933. var oldSplice = array.splice;
  21934. array.splice = function (index, deleteCount) {
  21935. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21936. _this._resyncMeshes();
  21937. return deleted;
  21938. };
  21939. this._resyncMeshes();
  21940. };
  21941. Light.prototype._resyncMeshes = function () {
  21942. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21943. var mesh = _a[_i];
  21944. mesh._resyncLighSource(this);
  21945. }
  21946. };
  21947. /**
  21948. * Forces the meshes to update their light related information in their rendering used effects
  21949. * @hidden Internal Use Only
  21950. */
  21951. Light.prototype._markMeshesAsLightDirty = function () {
  21952. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21953. var mesh = _a[_i];
  21954. if (mesh._lightSources.indexOf(this) !== -1) {
  21955. mesh._markSubMeshesAsLightDirty();
  21956. }
  21957. }
  21958. };
  21959. /**
  21960. * Recomputes the cached photometric scale if needed.
  21961. */
  21962. Light.prototype._computePhotometricScale = function () {
  21963. this._photometricScale = this._getPhotometricScale();
  21964. this.getScene().resetCachedMaterial();
  21965. };
  21966. /**
  21967. * Returns the Photometric Scale according to the light type and intensity mode.
  21968. */
  21969. Light.prototype._getPhotometricScale = function () {
  21970. var photometricScale = 0.0;
  21971. var lightTypeID = this.getTypeID();
  21972. //get photometric mode
  21973. var photometricMode = this.intensityMode;
  21974. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  21975. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  21976. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  21977. }
  21978. else {
  21979. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  21980. }
  21981. }
  21982. //compute photometric scale
  21983. switch (lightTypeID) {
  21984. case Light.LIGHTTYPEID_POINTLIGHT:
  21985. case Light.LIGHTTYPEID_SPOTLIGHT:
  21986. switch (photometricMode) {
  21987. case Light.INTENSITYMODE_LUMINOUSPOWER:
  21988. photometricScale = 1.0 / (4.0 * Math.PI);
  21989. break;
  21990. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  21991. photometricScale = 1.0;
  21992. break;
  21993. case Light.INTENSITYMODE_LUMINANCE:
  21994. photometricScale = this.radius * this.radius;
  21995. break;
  21996. }
  21997. break;
  21998. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  21999. switch (photometricMode) {
  22000. case Light.INTENSITYMODE_ILLUMINANCE:
  22001. photometricScale = 1.0;
  22002. break;
  22003. case Light.INTENSITYMODE_LUMINANCE:
  22004. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  22005. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  22006. var apexAngleRadians = this.radius;
  22007. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  22008. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  22009. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  22010. photometricScale = solidAngle;
  22011. break;
  22012. }
  22013. break;
  22014. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  22015. // No fall off in hemisperic light.
  22016. photometricScale = 1.0;
  22017. break;
  22018. }
  22019. return photometricScale;
  22020. };
  22021. /**
  22022. * Reorder the light in the scene according to their defined priority.
  22023. * @hidden Internal Use Only
  22024. */
  22025. Light.prototype._reorderLightsInScene = function () {
  22026. var scene = this.getScene();
  22027. if (this._renderPriority != 0) {
  22028. scene.requireLightSorting = true;
  22029. }
  22030. this.getScene().sortLightsByPriority();
  22031. };
  22032. /**
  22033. * Falloff Default: light is falling off following the material specification:
  22034. * standard material is using standard falloff whereas pbr material can request special falloff per materials.
  22035. */
  22036. Light.FALLOFF_DEFAULT = 0;
  22037. /**
  22038. * Falloff Physical: light is falling off following the inverse squared distance law.
  22039. */
  22040. Light.FALLOFF_PHYSICAL = 1;
  22041. /**
  22042. * Falloff gltf: light is falling off as described in the gltf moving to PBR document
  22043. * to enhance interoperability with other engines.
  22044. */
  22045. Light.FALLOFF_GLTF = 2;
  22046. /**
  22047. * Falloff Standard: light is falling off like in the standard material
  22048. * to enhance interoperability with other materials.
  22049. */
  22050. Light.FALLOFF_STANDARD = 3;
  22051. //lightmapMode Consts
  22052. /**
  22053. * If every light affecting the material is in this lightmapMode,
  22054. * material.lightmapTexture adds or multiplies
  22055. * (depends on material.useLightmapAsShadowmap)
  22056. * after every other light calculations.
  22057. */
  22058. Light.LIGHTMAP_DEFAULT = 0;
  22059. /**
  22060. * material.lightmapTexture as only diffuse lighting from this light
  22061. * adds only specular lighting from this light
  22062. * adds dynamic shadows
  22063. */
  22064. Light.LIGHTMAP_SPECULAR = 1;
  22065. /**
  22066. * material.lightmapTexture as only lighting
  22067. * no light calculation from this light
  22068. * only adds dynamic shadows from this light
  22069. */
  22070. Light.LIGHTMAP_SHADOWSONLY = 2;
  22071. // Intensity Mode Consts
  22072. /**
  22073. * Each light type uses the default quantity according to its type:
  22074. * point/spot lights use luminous intensity
  22075. * directional lights use illuminance
  22076. */
  22077. Light.INTENSITYMODE_AUTOMATIC = 0;
  22078. /**
  22079. * lumen (lm)
  22080. */
  22081. Light.INTENSITYMODE_LUMINOUSPOWER = 1;
  22082. /**
  22083. * candela (lm/sr)
  22084. */
  22085. Light.INTENSITYMODE_LUMINOUSINTENSITY = 2;
  22086. /**
  22087. * lux (lm/m^2)
  22088. */
  22089. Light.INTENSITYMODE_ILLUMINANCE = 3;
  22090. /**
  22091. * nit (cd/m^2)
  22092. */
  22093. Light.INTENSITYMODE_LUMINANCE = 4;
  22094. // Light types ids const.
  22095. /**
  22096. * Light type const id of the point light.
  22097. */
  22098. Light.LIGHTTYPEID_POINTLIGHT = 0;
  22099. /**
  22100. * Light type const id of the directional light.
  22101. */
  22102. Light.LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  22103. /**
  22104. * Light type const id of the spot light.
  22105. */
  22106. Light.LIGHTTYPEID_SPOTLIGHT = 2;
  22107. /**
  22108. * Light type const id of the hemispheric light.
  22109. */
  22110. Light.LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  22111. __decorate([
  22112. BABYLON.serializeAsColor3()
  22113. ], Light.prototype, "diffuse", void 0);
  22114. __decorate([
  22115. BABYLON.serializeAsColor3()
  22116. ], Light.prototype, "specular", void 0);
  22117. __decorate([
  22118. BABYLON.serialize()
  22119. ], Light.prototype, "falloffType", void 0);
  22120. __decorate([
  22121. BABYLON.serialize()
  22122. ], Light.prototype, "intensity", void 0);
  22123. __decorate([
  22124. BABYLON.serialize()
  22125. ], Light.prototype, "range", null);
  22126. __decorate([
  22127. BABYLON.serialize()
  22128. ], Light.prototype, "intensityMode", null);
  22129. __decorate([
  22130. BABYLON.serialize()
  22131. ], Light.prototype, "radius", null);
  22132. __decorate([
  22133. BABYLON.serialize()
  22134. ], Light.prototype, "_renderPriority", void 0);
  22135. __decorate([
  22136. BABYLON.expandToProperty("_reorderLightsInScene")
  22137. ], Light.prototype, "renderPriority", void 0);
  22138. __decorate([
  22139. BABYLON.serialize("shadowEnabled")
  22140. ], Light.prototype, "_shadowEnabled", void 0);
  22141. __decorate([
  22142. BABYLON.serialize("excludeWithLayerMask")
  22143. ], Light.prototype, "_excludeWithLayerMask", void 0);
  22144. __decorate([
  22145. BABYLON.serialize("includeOnlyWithLayerMask")
  22146. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  22147. __decorate([
  22148. BABYLON.serialize("lightmapMode")
  22149. ], Light.prototype, "_lightmapMode", void 0);
  22150. return Light;
  22151. }(BABYLON.Node));
  22152. BABYLON.Light = Light;
  22153. })(BABYLON || (BABYLON = {}));
  22154. //# sourceMappingURL=babylon.light.js.map
  22155. var BABYLON;
  22156. (function (BABYLON) {
  22157. var Camera = /** @class */ (function (_super) {
  22158. __extends(Camera, _super);
  22159. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  22160. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  22161. var _this = _super.call(this, name, scene) || this;
  22162. /**
  22163. * The vector the camera should consider as up.
  22164. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  22165. */
  22166. _this.upVector = BABYLON.Vector3.Up();
  22167. _this.orthoLeft = null;
  22168. _this.orthoRight = null;
  22169. _this.orthoBottom = null;
  22170. _this.orthoTop = null;
  22171. /**
  22172. * FOV is set in Radians. (default is 0.8)
  22173. */
  22174. _this.fov = 0.8;
  22175. _this.minZ = 1;
  22176. _this.maxZ = 10000.0;
  22177. _this.inertia = 0.9;
  22178. _this.mode = Camera.PERSPECTIVE_CAMERA;
  22179. _this.isIntermediate = false;
  22180. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  22181. /**
  22182. * Restricts the camera to viewing objects with the same layerMask.
  22183. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  22184. */
  22185. _this.layerMask = 0x0FFFFFFF;
  22186. /**
  22187. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  22188. */
  22189. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  22190. // Camera rig members
  22191. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  22192. /** @hidden */
  22193. _this._rigCameras = new Array();
  22194. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  22195. /** @hidden */
  22196. _this._skipRendering = false;
  22197. _this.customRenderTargets = new Array();
  22198. // Observables
  22199. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  22200. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  22201. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  22202. _this.onRestoreStateObservable = new BABYLON.Observable();
  22203. // Cache
  22204. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  22205. _this._projectionMatrix = new BABYLON.Matrix();
  22206. _this._doNotComputeProjectionMatrix = false;
  22207. _this._worldMatrix = BABYLON.Matrix.Identity();
  22208. _this._postProcesses = new Array();
  22209. _this._transformMatrix = BABYLON.Matrix.Zero();
  22210. _this._activeMeshes = new BABYLON.SmartArray(256);
  22211. _this._globalPosition = BABYLON.Vector3.Zero();
  22212. _this._refreshFrustumPlanes = true;
  22213. _this.getScene().addCamera(_this);
  22214. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  22215. _this.getScene().activeCamera = _this;
  22216. }
  22217. _this.position = position;
  22218. return _this;
  22219. }
  22220. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  22221. get: function () {
  22222. return Camera._PERSPECTIVE_CAMERA;
  22223. },
  22224. enumerable: true,
  22225. configurable: true
  22226. });
  22227. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  22228. get: function () {
  22229. return Camera._ORTHOGRAPHIC_CAMERA;
  22230. },
  22231. enumerable: true,
  22232. configurable: true
  22233. });
  22234. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  22235. /**
  22236. * This is the default FOV mode for perspective cameras.
  22237. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  22238. *
  22239. */
  22240. get: function () {
  22241. return Camera._FOVMODE_VERTICAL_FIXED;
  22242. },
  22243. enumerable: true,
  22244. configurable: true
  22245. });
  22246. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  22247. /**
  22248. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  22249. *
  22250. */
  22251. get: function () {
  22252. return Camera._FOVMODE_HORIZONTAL_FIXED;
  22253. },
  22254. enumerable: true,
  22255. configurable: true
  22256. });
  22257. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  22258. get: function () {
  22259. return Camera._RIG_MODE_NONE;
  22260. },
  22261. enumerable: true,
  22262. configurable: true
  22263. });
  22264. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  22265. get: function () {
  22266. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  22267. },
  22268. enumerable: true,
  22269. configurable: true
  22270. });
  22271. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  22272. get: function () {
  22273. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  22274. },
  22275. enumerable: true,
  22276. configurable: true
  22277. });
  22278. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  22279. get: function () {
  22280. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22281. },
  22282. enumerable: true,
  22283. configurable: true
  22284. });
  22285. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  22286. get: function () {
  22287. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  22288. },
  22289. enumerable: true,
  22290. configurable: true
  22291. });
  22292. Object.defineProperty(Camera, "RIG_MODE_VR", {
  22293. get: function () {
  22294. return Camera._RIG_MODE_VR;
  22295. },
  22296. enumerable: true,
  22297. configurable: true
  22298. });
  22299. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  22300. get: function () {
  22301. return Camera._RIG_MODE_WEBVR;
  22302. },
  22303. enumerable: true,
  22304. configurable: true
  22305. });
  22306. /**
  22307. * Store current camera state (fov, position, etc..)
  22308. */
  22309. Camera.prototype.storeState = function () {
  22310. this._stateStored = true;
  22311. this._storedFov = this.fov;
  22312. return this;
  22313. };
  22314. /**
  22315. * Restores the camera state values if it has been stored. You must call storeState() first
  22316. */
  22317. Camera.prototype._restoreStateValues = function () {
  22318. if (!this._stateStored) {
  22319. return false;
  22320. }
  22321. this.fov = this._storedFov;
  22322. return true;
  22323. };
  22324. /**
  22325. * Restored camera state. You must call storeState() first
  22326. */
  22327. Camera.prototype.restoreState = function () {
  22328. if (this._restoreStateValues()) {
  22329. this.onRestoreStateObservable.notifyObservers(this);
  22330. return true;
  22331. }
  22332. return false;
  22333. };
  22334. Camera.prototype.getClassName = function () {
  22335. return "Camera";
  22336. };
  22337. /**
  22338. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22339. */
  22340. Camera.prototype.toString = function (fullDetails) {
  22341. var ret = "Name: " + this.name;
  22342. ret += ", type: " + this.getClassName();
  22343. if (this.animations) {
  22344. for (var i = 0; i < this.animations.length; i++) {
  22345. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22346. }
  22347. }
  22348. if (fullDetails) {
  22349. }
  22350. return ret;
  22351. };
  22352. Object.defineProperty(Camera.prototype, "globalPosition", {
  22353. get: function () {
  22354. return this._globalPosition;
  22355. },
  22356. enumerable: true,
  22357. configurable: true
  22358. });
  22359. Camera.prototype.getActiveMeshes = function () {
  22360. return this._activeMeshes;
  22361. };
  22362. Camera.prototype.isActiveMesh = function (mesh) {
  22363. return (this._activeMeshes.indexOf(mesh) !== -1);
  22364. };
  22365. /**
  22366. * Is this camera ready to be used/rendered
  22367. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22368. * @return true if the camera is ready
  22369. */
  22370. Camera.prototype.isReady = function (completeCheck) {
  22371. if (completeCheck === void 0) { completeCheck = false; }
  22372. if (completeCheck) {
  22373. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22374. var pp = _a[_i];
  22375. if (pp && !pp.isReady()) {
  22376. return false;
  22377. }
  22378. }
  22379. }
  22380. return _super.prototype.isReady.call(this, completeCheck);
  22381. };
  22382. //Cache
  22383. /** @hidden */
  22384. Camera.prototype._initCache = function () {
  22385. _super.prototype._initCache.call(this);
  22386. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22387. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22388. this._cache.mode = undefined;
  22389. this._cache.minZ = undefined;
  22390. this._cache.maxZ = undefined;
  22391. this._cache.fov = undefined;
  22392. this._cache.fovMode = undefined;
  22393. this._cache.aspectRatio = undefined;
  22394. this._cache.orthoLeft = undefined;
  22395. this._cache.orthoRight = undefined;
  22396. this._cache.orthoBottom = undefined;
  22397. this._cache.orthoTop = undefined;
  22398. this._cache.renderWidth = undefined;
  22399. this._cache.renderHeight = undefined;
  22400. };
  22401. /** @hidden */
  22402. Camera.prototype._updateCache = function (ignoreParentClass) {
  22403. if (!ignoreParentClass) {
  22404. _super.prototype._updateCache.call(this);
  22405. }
  22406. this._cache.position.copyFrom(this.position);
  22407. this._cache.upVector.copyFrom(this.upVector);
  22408. };
  22409. // Synchronized
  22410. /** @hidden */
  22411. Camera.prototype._isSynchronized = function () {
  22412. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22413. };
  22414. /** @hidden */
  22415. Camera.prototype._isSynchronizedViewMatrix = function () {
  22416. if (!_super.prototype._isSynchronized.call(this))
  22417. return false;
  22418. return this._cache.position.equals(this.position)
  22419. && this._cache.upVector.equals(this.upVector)
  22420. && this.isSynchronizedWithParent();
  22421. };
  22422. /** @hidden */
  22423. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22424. var check = this._cache.mode === this.mode
  22425. && this._cache.minZ === this.minZ
  22426. && this._cache.maxZ === this.maxZ;
  22427. if (!check) {
  22428. return false;
  22429. }
  22430. var engine = this.getEngine();
  22431. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22432. check = this._cache.fov === this.fov
  22433. && this._cache.fovMode === this.fovMode
  22434. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22435. }
  22436. else {
  22437. check = this._cache.orthoLeft === this.orthoLeft
  22438. && this._cache.orthoRight === this.orthoRight
  22439. && this._cache.orthoBottom === this.orthoBottom
  22440. && this._cache.orthoTop === this.orthoTop
  22441. && this._cache.renderWidth === engine.getRenderWidth()
  22442. && this._cache.renderHeight === engine.getRenderHeight();
  22443. }
  22444. return check;
  22445. };
  22446. // Controls
  22447. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22448. };
  22449. Camera.prototype.detachControl = function (element) {
  22450. };
  22451. Camera.prototype.update = function () {
  22452. this._checkInputs();
  22453. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22454. this._updateRigCameras();
  22455. }
  22456. };
  22457. /** @hidden */
  22458. Camera.prototype._checkInputs = function () {
  22459. this.onAfterCheckInputsObservable.notifyObservers(this);
  22460. };
  22461. Object.defineProperty(Camera.prototype, "rigCameras", {
  22462. get: function () {
  22463. return this._rigCameras;
  22464. },
  22465. enumerable: true,
  22466. configurable: true
  22467. });
  22468. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22469. get: function () {
  22470. return this._rigPostProcess;
  22471. },
  22472. enumerable: true,
  22473. configurable: true
  22474. });
  22475. /**
  22476. * Internal, gets the first post proces.
  22477. * @returns the first post process to be run on this camera.
  22478. */
  22479. Camera.prototype._getFirstPostProcess = function () {
  22480. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22481. if (this._postProcesses[ppIndex] !== null) {
  22482. return this._postProcesses[ppIndex];
  22483. }
  22484. }
  22485. return null;
  22486. };
  22487. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22488. // invalidate framebuffer
  22489. var firstPostProcess = this._getFirstPostProcess();
  22490. if (firstPostProcess) {
  22491. firstPostProcess.markTextureDirty();
  22492. }
  22493. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22494. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22495. var cam = this._rigCameras[i];
  22496. var rigPostProcess = cam._rigPostProcess;
  22497. // for VR rig, there does not have to be a post process
  22498. if (rigPostProcess) {
  22499. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22500. if (isPass) {
  22501. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22502. cam.isIntermediate = this._postProcesses.length === 0;
  22503. }
  22504. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22505. rigPostProcess.markTextureDirty();
  22506. }
  22507. else {
  22508. cam._postProcesses = this._postProcesses.slice(0);
  22509. }
  22510. }
  22511. };
  22512. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22513. if (insertAt === void 0) { insertAt = null; }
  22514. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22515. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22516. return 0;
  22517. }
  22518. if (insertAt == null || insertAt < 0) {
  22519. this._postProcesses.push(postProcess);
  22520. }
  22521. else if (this._postProcesses[insertAt] === null) {
  22522. this._postProcesses[insertAt] = postProcess;
  22523. }
  22524. else {
  22525. this._postProcesses.splice(insertAt, 0, postProcess);
  22526. }
  22527. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22528. return this._postProcesses.indexOf(postProcess);
  22529. };
  22530. Camera.prototype.detachPostProcess = function (postProcess) {
  22531. var idx = this._postProcesses.indexOf(postProcess);
  22532. if (idx !== -1) {
  22533. this._postProcesses[idx] = null;
  22534. }
  22535. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22536. };
  22537. Camera.prototype.getWorldMatrix = function () {
  22538. if (this._isSynchronizedViewMatrix()) {
  22539. return this._worldMatrix;
  22540. }
  22541. // Getting the the view matrix will also compute the world matrix.
  22542. this.getViewMatrix();
  22543. return this._worldMatrix;
  22544. };
  22545. /** @hidden */
  22546. Camera.prototype._getViewMatrix = function () {
  22547. return BABYLON.Matrix.Identity();
  22548. };
  22549. Camera.prototype.getViewMatrix = function (force) {
  22550. if (!force && this._isSynchronizedViewMatrix()) {
  22551. return this._computedViewMatrix;
  22552. }
  22553. this.updateCache();
  22554. this._computedViewMatrix = this._getViewMatrix();
  22555. this._currentRenderId = this.getScene().getRenderId();
  22556. this._childRenderId = this._currentRenderId;
  22557. this._refreshFrustumPlanes = true;
  22558. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22559. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22560. }
  22561. this.onViewMatrixChangedObservable.notifyObservers(this);
  22562. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22563. return this._computedViewMatrix;
  22564. };
  22565. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22566. this._doNotComputeProjectionMatrix = true;
  22567. if (projection !== undefined) {
  22568. this._projectionMatrix = projection;
  22569. }
  22570. };
  22571. ;
  22572. Camera.prototype.unfreezeProjectionMatrix = function () {
  22573. this._doNotComputeProjectionMatrix = false;
  22574. };
  22575. ;
  22576. Camera.prototype.getProjectionMatrix = function (force) {
  22577. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22578. return this._projectionMatrix;
  22579. }
  22580. // Cache
  22581. this._cache.mode = this.mode;
  22582. this._cache.minZ = this.minZ;
  22583. this._cache.maxZ = this.maxZ;
  22584. // Matrix
  22585. this._refreshFrustumPlanes = true;
  22586. var engine = this.getEngine();
  22587. var scene = this.getScene();
  22588. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22589. this._cache.fov = this.fov;
  22590. this._cache.fovMode = this.fovMode;
  22591. this._cache.aspectRatio = engine.getAspectRatio(this);
  22592. if (this.minZ <= 0) {
  22593. this.minZ = 0.1;
  22594. }
  22595. if (scene.useRightHandedSystem) {
  22596. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22597. }
  22598. else {
  22599. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22600. }
  22601. }
  22602. else {
  22603. var halfWidth = engine.getRenderWidth() / 2.0;
  22604. var halfHeight = engine.getRenderHeight() / 2.0;
  22605. if (scene.useRightHandedSystem) {
  22606. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22607. }
  22608. else {
  22609. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22610. }
  22611. this._cache.orthoLeft = this.orthoLeft;
  22612. this._cache.orthoRight = this.orthoRight;
  22613. this._cache.orthoBottom = this.orthoBottom;
  22614. this._cache.orthoTop = this.orthoTop;
  22615. this._cache.renderWidth = engine.getRenderWidth();
  22616. this._cache.renderHeight = engine.getRenderHeight();
  22617. }
  22618. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22619. return this._projectionMatrix;
  22620. };
  22621. /**
  22622. * Gets the transformation matrix (ie. the multiplication of view by projection matrices)
  22623. * @returns a Matrix
  22624. */
  22625. Camera.prototype.getTransformationMatrix = function () {
  22626. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22627. return this._transformMatrix;
  22628. };
  22629. Camera.prototype.updateFrustumPlanes = function () {
  22630. if (!this._refreshFrustumPlanes) {
  22631. return;
  22632. }
  22633. this.getTransformationMatrix();
  22634. if (!this._frustumPlanes) {
  22635. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22636. }
  22637. else {
  22638. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22639. }
  22640. this._refreshFrustumPlanes = false;
  22641. };
  22642. Camera.prototype.isInFrustum = function (target) {
  22643. this.updateFrustumPlanes();
  22644. return target.isInFrustum(this._frustumPlanes);
  22645. };
  22646. Camera.prototype.isCompletelyInFrustum = function (target) {
  22647. this.updateFrustumPlanes();
  22648. return target.isCompletelyInFrustum(this._frustumPlanes);
  22649. };
  22650. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22651. if (length === void 0) { length = 100; }
  22652. if (!transform) {
  22653. transform = this.getWorldMatrix();
  22654. }
  22655. if (!origin) {
  22656. origin = this.position;
  22657. }
  22658. var forward = new BABYLON.Vector3(0, 0, 1);
  22659. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22660. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22661. return new BABYLON.Ray(origin, direction, length);
  22662. };
  22663. /**
  22664. * Releases resources associated with this node.
  22665. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22666. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22667. */
  22668. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22669. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22670. // Observables
  22671. this.onViewMatrixChangedObservable.clear();
  22672. this.onProjectionMatrixChangedObservable.clear();
  22673. this.onAfterCheckInputsObservable.clear();
  22674. this.onRestoreStateObservable.clear();
  22675. // Inputs
  22676. if (this.inputs) {
  22677. this.inputs.clear();
  22678. }
  22679. // Animations
  22680. this.getScene().stopAnimation(this);
  22681. // Remove from scene
  22682. this.getScene().removeCamera(this);
  22683. while (this._rigCameras.length > 0) {
  22684. var camera = this._rigCameras.pop();
  22685. if (camera) {
  22686. camera.dispose();
  22687. }
  22688. }
  22689. // Postprocesses
  22690. if (this._rigPostProcess) {
  22691. this._rigPostProcess.dispose(this);
  22692. this._rigPostProcess = null;
  22693. this._postProcesses = [];
  22694. }
  22695. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22696. this._rigPostProcess = null;
  22697. this._postProcesses = [];
  22698. }
  22699. else {
  22700. var i = this._postProcesses.length;
  22701. while (--i >= 0) {
  22702. var postProcess = this._postProcesses[i];
  22703. if (postProcess) {
  22704. postProcess.dispose(this);
  22705. }
  22706. }
  22707. }
  22708. // Render targets
  22709. var i = this.customRenderTargets.length;
  22710. while (--i >= 0) {
  22711. this.customRenderTargets[i].dispose();
  22712. }
  22713. this.customRenderTargets = [];
  22714. // Active Meshes
  22715. this._activeMeshes.dispose();
  22716. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22717. };
  22718. Object.defineProperty(Camera.prototype, "leftCamera", {
  22719. // ---- Camera rigs section ----
  22720. get: function () {
  22721. if (this._rigCameras.length < 1) {
  22722. return null;
  22723. }
  22724. return this._rigCameras[0];
  22725. },
  22726. enumerable: true,
  22727. configurable: true
  22728. });
  22729. Object.defineProperty(Camera.prototype, "rightCamera", {
  22730. get: function () {
  22731. if (this._rigCameras.length < 2) {
  22732. return null;
  22733. }
  22734. return this._rigCameras[1];
  22735. },
  22736. enumerable: true,
  22737. configurable: true
  22738. });
  22739. Camera.prototype.getLeftTarget = function () {
  22740. if (this._rigCameras.length < 1) {
  22741. return null;
  22742. }
  22743. return this._rigCameras[0].getTarget();
  22744. };
  22745. Camera.prototype.getRightTarget = function () {
  22746. if (this._rigCameras.length < 2) {
  22747. return null;
  22748. }
  22749. return this._rigCameras[1].getTarget();
  22750. };
  22751. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22752. if (this.cameraRigMode === mode) {
  22753. return;
  22754. }
  22755. while (this._rigCameras.length > 0) {
  22756. var camera = this._rigCameras.pop();
  22757. if (camera) {
  22758. camera.dispose();
  22759. }
  22760. }
  22761. this.cameraRigMode = mode;
  22762. this._cameraRigParams = {};
  22763. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22764. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22765. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22766. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22767. // create the rig cameras, unless none
  22768. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22769. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22770. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22771. if (leftCamera && rightCamera) {
  22772. this._rigCameras.push(leftCamera);
  22773. this._rigCameras.push(rightCamera);
  22774. }
  22775. }
  22776. switch (this.cameraRigMode) {
  22777. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22778. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22779. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22780. break;
  22781. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22782. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22783. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22784. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22785. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22786. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22787. break;
  22788. case Camera.RIG_MODE_VR:
  22789. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22790. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22791. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22792. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22793. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22794. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22795. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22796. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22797. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22798. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22799. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  22800. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  22801. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  22802. if (metrics.compensateDistortion) {
  22803. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  22804. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  22805. }
  22806. break;
  22807. case Camera.RIG_MODE_WEBVR:
  22808. if (rigParams.vrDisplay) {
  22809. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  22810. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  22811. //Left eye
  22812. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22813. this._rigCameras[0].setCameraRigParameter("left", true);
  22814. //leaving this for future reference
  22815. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  22816. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  22817. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  22818. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22819. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22820. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22821. this._rigCameras[0].parent = this;
  22822. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  22823. //Right eye
  22824. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22825. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  22826. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  22827. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  22828. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22829. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22830. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22831. this._rigCameras[1].parent = this;
  22832. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  22833. if (Camera.UseAlternateWebVRRendering) {
  22834. this._rigCameras[1]._skipRendering = true;
  22835. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  22836. }
  22837. }
  22838. break;
  22839. }
  22840. this._cascadePostProcessesToRigCams();
  22841. this.update();
  22842. };
  22843. Camera.prototype._getVRProjectionMatrix = function () {
  22844. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  22845. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  22846. return this._projectionMatrix;
  22847. };
  22848. Camera.prototype._updateCameraRotationMatrix = function () {
  22849. //Here for WebVR
  22850. };
  22851. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  22852. //Here for WebVR
  22853. };
  22854. /**
  22855. * This function MUST be overwritten by the different WebVR cameras available.
  22856. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22857. */
  22858. Camera.prototype._getWebVRProjectionMatrix = function () {
  22859. return BABYLON.Matrix.Identity();
  22860. };
  22861. /**
  22862. * This function MUST be overwritten by the different WebVR cameras available.
  22863. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22864. */
  22865. Camera.prototype._getWebVRViewMatrix = function () {
  22866. return BABYLON.Matrix.Identity();
  22867. };
  22868. Camera.prototype.setCameraRigParameter = function (name, value) {
  22869. if (!this._cameraRigParams) {
  22870. this._cameraRigParams = {};
  22871. }
  22872. this._cameraRigParams[name] = value;
  22873. //provisionnally:
  22874. if (name === "interaxialDistance") {
  22875. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  22876. }
  22877. };
  22878. /**
  22879. * needs to be overridden by children so sub has required properties to be copied
  22880. */
  22881. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  22882. return null;
  22883. };
  22884. /**
  22885. * May need to be overridden by children
  22886. * @hidden
  22887. */
  22888. Camera.prototype._updateRigCameras = function () {
  22889. for (var i = 0; i < this._rigCameras.length; i++) {
  22890. this._rigCameras[i].minZ = this.minZ;
  22891. this._rigCameras[i].maxZ = this.maxZ;
  22892. this._rigCameras[i].fov = this.fov;
  22893. }
  22894. // only update viewport when ANAGLYPH
  22895. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  22896. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  22897. }
  22898. };
  22899. /** @hidden */
  22900. Camera.prototype._setupInputs = function () {
  22901. };
  22902. Camera.prototype.serialize = function () {
  22903. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22904. // Type
  22905. serializationObject.type = this.getClassName();
  22906. // Parent
  22907. if (this.parent) {
  22908. serializationObject.parentId = this.parent.id;
  22909. }
  22910. if (this.inputs) {
  22911. this.inputs.serialize(serializationObject);
  22912. }
  22913. // Animations
  22914. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22915. serializationObject.ranges = this.serializeAnimationRanges();
  22916. return serializationObject;
  22917. };
  22918. Camera.prototype.clone = function (name) {
  22919. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  22920. };
  22921. Camera.prototype.getDirection = function (localAxis) {
  22922. var result = BABYLON.Vector3.Zero();
  22923. this.getDirectionToRef(localAxis, result);
  22924. return result;
  22925. };
  22926. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  22927. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  22928. };
  22929. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  22930. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  22931. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  22932. var constructorFunc = BABYLON.Node.Construct(type, name, scene, {
  22933. interaxial_distance: interaxial_distance,
  22934. isStereoscopicSideBySide: isStereoscopicSideBySide
  22935. });
  22936. if (constructorFunc) {
  22937. return constructorFunc;
  22938. }
  22939. // Default to universal camera
  22940. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22941. };
  22942. Camera.prototype.computeWorldMatrix = function () {
  22943. return this.getWorldMatrix();
  22944. };
  22945. Camera.Parse = function (parsedCamera, scene) {
  22946. var type = parsedCamera.type;
  22947. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  22948. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  22949. // Parent
  22950. if (parsedCamera.parentId) {
  22951. camera._waitingParentId = parsedCamera.parentId;
  22952. }
  22953. //If camera has an input manager, let it parse inputs settings
  22954. if (camera.inputs) {
  22955. camera.inputs.parse(parsedCamera);
  22956. camera._setupInputs();
  22957. }
  22958. if (camera.setPosition) { // need to force position
  22959. camera.position.copyFromFloats(0, 0, 0);
  22960. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  22961. }
  22962. // Target
  22963. if (parsedCamera.target) {
  22964. if (camera.setTarget) {
  22965. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  22966. }
  22967. }
  22968. // Apply 3d rig, when found
  22969. if (parsedCamera.cameraRigMode) {
  22970. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  22971. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  22972. }
  22973. // Animations
  22974. if (parsedCamera.animations) {
  22975. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  22976. var parsedAnimation = parsedCamera.animations[animationIndex];
  22977. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22978. }
  22979. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  22980. }
  22981. if (parsedCamera.autoAnimate) {
  22982. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  22983. }
  22984. return camera;
  22985. };
  22986. // Statics
  22987. Camera._PERSPECTIVE_CAMERA = 0;
  22988. Camera._ORTHOGRAPHIC_CAMERA = 1;
  22989. Camera._FOVMODE_VERTICAL_FIXED = 0;
  22990. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  22991. Camera._RIG_MODE_NONE = 0;
  22992. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  22993. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  22994. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  22995. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  22996. Camera._RIG_MODE_VR = 20;
  22997. Camera._RIG_MODE_WEBVR = 21;
  22998. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  22999. Camera.UseAlternateWebVRRendering = false;
  23000. __decorate([
  23001. BABYLON.serializeAsVector3()
  23002. ], Camera.prototype, "position", void 0);
  23003. __decorate([
  23004. BABYLON.serializeAsVector3()
  23005. ], Camera.prototype, "upVector", void 0);
  23006. __decorate([
  23007. BABYLON.serialize()
  23008. ], Camera.prototype, "orthoLeft", void 0);
  23009. __decorate([
  23010. BABYLON.serialize()
  23011. ], Camera.prototype, "orthoRight", void 0);
  23012. __decorate([
  23013. BABYLON.serialize()
  23014. ], Camera.prototype, "orthoBottom", void 0);
  23015. __decorate([
  23016. BABYLON.serialize()
  23017. ], Camera.prototype, "orthoTop", void 0);
  23018. __decorate([
  23019. BABYLON.serialize()
  23020. ], Camera.prototype, "fov", void 0);
  23021. __decorate([
  23022. BABYLON.serialize()
  23023. ], Camera.prototype, "minZ", void 0);
  23024. __decorate([
  23025. BABYLON.serialize()
  23026. ], Camera.prototype, "maxZ", void 0);
  23027. __decorate([
  23028. BABYLON.serialize()
  23029. ], Camera.prototype, "inertia", void 0);
  23030. __decorate([
  23031. BABYLON.serialize()
  23032. ], Camera.prototype, "mode", void 0);
  23033. __decorate([
  23034. BABYLON.serialize()
  23035. ], Camera.prototype, "layerMask", void 0);
  23036. __decorate([
  23037. BABYLON.serialize()
  23038. ], Camera.prototype, "fovMode", void 0);
  23039. __decorate([
  23040. BABYLON.serialize()
  23041. ], Camera.prototype, "cameraRigMode", void 0);
  23042. __decorate([
  23043. BABYLON.serialize()
  23044. ], Camera.prototype, "interaxialDistance", void 0);
  23045. __decorate([
  23046. BABYLON.serialize()
  23047. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  23048. return Camera;
  23049. }(BABYLON.Node));
  23050. BABYLON.Camera = Camera;
  23051. })(BABYLON || (BABYLON = {}));
  23052. //# sourceMappingURL=babylon.camera.js.map
  23053. var BABYLON;
  23054. (function (BABYLON) {
  23055. var RenderingManager = /** @class */ (function () {
  23056. function RenderingManager(scene) {
  23057. /**
  23058. * @hidden
  23059. */
  23060. this._useSceneAutoClearSetup = false;
  23061. this._renderingGroups = new Array();
  23062. this._autoClearDepthStencil = {};
  23063. this._customOpaqueSortCompareFn = {};
  23064. this._customAlphaTestSortCompareFn = {};
  23065. this._customTransparentSortCompareFn = {};
  23066. this._renderingGroupInfo = new BABYLON.RenderingGroupInfo();
  23067. this._scene = scene;
  23068. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  23069. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  23070. }
  23071. }
  23072. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  23073. if (depth === void 0) { depth = true; }
  23074. if (stencil === void 0) { stencil = true; }
  23075. if (this._depthStencilBufferAlreadyCleaned) {
  23076. return;
  23077. }
  23078. this._scene.getEngine().clear(null, false, depth, stencil);
  23079. this._depthStencilBufferAlreadyCleaned = true;
  23080. };
  23081. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  23082. // Update the observable context (not null as it only goes away on dispose)
  23083. var info = this._renderingGroupInfo;
  23084. info.scene = this._scene;
  23085. info.camera = this._scene.activeCamera;
  23086. // Dispatch sprites
  23087. if (this._scene.spriteManagers && renderSprites) {
  23088. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  23089. var manager = this._scene.spriteManagers[index];
  23090. this.dispatchSprites(manager);
  23091. }
  23092. }
  23093. // Render
  23094. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23095. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  23096. var renderingGroup = this._renderingGroups[index];
  23097. if (!renderingGroup)
  23098. continue;
  23099. var renderingGroupMask = Math.pow(2, index);
  23100. info.renderingGroupId = index;
  23101. // Before Observable
  23102. this._scene.onBeforeRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  23103. // Clear depth/stencil if needed
  23104. if (RenderingManager.AUTOCLEAR) {
  23105. var autoClear = this._useSceneAutoClearSetup ?
  23106. this._scene.getAutoClearDepthStencilSetup(index) :
  23107. this._autoClearDepthStencil[index];
  23108. if (autoClear && autoClear.autoClear) {
  23109. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  23110. }
  23111. }
  23112. // Render
  23113. for (var _i = 0, _a = this._scene._beforeRenderingGroupDrawStage; _i < _a.length; _i++) {
  23114. var step = _a[_i];
  23115. step.action(index);
  23116. }
  23117. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  23118. for (var _b = 0, _c = this._scene._afterRenderingGroupDrawStage; _b < _c.length; _b++) {
  23119. var step = _c[_b];
  23120. step.action(index);
  23121. }
  23122. // After Observable
  23123. this._scene.onAfterRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  23124. }
  23125. };
  23126. RenderingManager.prototype.reset = function () {
  23127. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23128. var renderingGroup = this._renderingGroups[index];
  23129. if (renderingGroup) {
  23130. renderingGroup.prepare();
  23131. }
  23132. }
  23133. };
  23134. RenderingManager.prototype.dispose = function () {
  23135. this.freeRenderingGroups();
  23136. this._renderingGroups.length = 0;
  23137. this._renderingGroupInfo = null;
  23138. };
  23139. /**
  23140. * Clear the info related to rendering groups preventing retention points during dispose.
  23141. */
  23142. RenderingManager.prototype.freeRenderingGroups = function () {
  23143. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23144. var renderingGroup = this._renderingGroups[index];
  23145. if (renderingGroup) {
  23146. renderingGroup.dispose();
  23147. }
  23148. }
  23149. };
  23150. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  23151. if (this._renderingGroups[renderingGroupId] === undefined) {
  23152. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  23153. }
  23154. };
  23155. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  23156. var renderingGroupId = spriteManager.renderingGroupId || 0;
  23157. this._prepareRenderingGroup(renderingGroupId);
  23158. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  23159. };
  23160. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  23161. var renderingGroupId = particleSystem.renderingGroupId || 0;
  23162. this._prepareRenderingGroup(renderingGroupId);
  23163. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  23164. };
  23165. /**
  23166. * @param subMesh The submesh to dispatch
  23167. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23168. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23169. */
  23170. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  23171. if (mesh === undefined) {
  23172. mesh = subMesh.getMesh();
  23173. }
  23174. var renderingGroupId = mesh.renderingGroupId || 0;
  23175. this._prepareRenderingGroup(renderingGroupId);
  23176. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  23177. };
  23178. /**
  23179. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23180. * This allowed control for front to back rendering or reversly depending of the special needs.
  23181. *
  23182. * @param renderingGroupId The rendering group id corresponding to its index
  23183. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23184. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23185. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23186. */
  23187. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23188. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23189. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23190. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23191. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  23192. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  23193. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  23194. if (this._renderingGroups[renderingGroupId]) {
  23195. var group = this._renderingGroups[renderingGroupId];
  23196. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  23197. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  23198. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  23199. }
  23200. };
  23201. /**
  23202. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23203. *
  23204. * @param renderingGroupId The rendering group id corresponding to its index
  23205. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23206. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23207. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23208. */
  23209. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23210. if (depth === void 0) { depth = true; }
  23211. if (stencil === void 0) { stencil = true; }
  23212. this._autoClearDepthStencil[renderingGroupId] = {
  23213. autoClear: autoClearDepthStencil,
  23214. depth: depth,
  23215. stencil: stencil
  23216. };
  23217. };
  23218. /**
  23219. * Gets the current auto clear configuration for one rendering group of the rendering
  23220. * manager.
  23221. * @param index the rendering group index to get the information for
  23222. * @returns The auto clear setup for the requested rendering group
  23223. */
  23224. RenderingManager.prototype.getAutoClearDepthStencilSetup = function (index) {
  23225. return this._autoClearDepthStencil[index];
  23226. };
  23227. /**
  23228. * The max id used for rendering groups (not included)
  23229. */
  23230. RenderingManager.MAX_RENDERINGGROUPS = 4;
  23231. /**
  23232. * The min id used for rendering groups (included)
  23233. */
  23234. RenderingManager.MIN_RENDERINGGROUPS = 0;
  23235. /**
  23236. * Used to globally prevent autoclearing scenes.
  23237. */
  23238. RenderingManager.AUTOCLEAR = true;
  23239. return RenderingManager;
  23240. }());
  23241. BABYLON.RenderingManager = RenderingManager;
  23242. })(BABYLON || (BABYLON = {}));
  23243. //# sourceMappingURL=babylon.renderingManager.js.map
  23244. var BABYLON;
  23245. (function (BABYLON) {
  23246. var RenderingGroup = /** @class */ (function () {
  23247. /**
  23248. * Creates a new rendering group.
  23249. * @param index The rendering group index
  23250. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  23251. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  23252. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  23253. */
  23254. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23255. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23256. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23257. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23258. this.index = index;
  23259. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  23260. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  23261. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  23262. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  23263. this._particleSystems = new BABYLON.SmartArray(256);
  23264. this._spriteManagers = new BABYLON.SmartArray(256);
  23265. this._edgesRenderers = new BABYLON.SmartArray(16);
  23266. this._scene = scene;
  23267. this.opaqueSortCompareFn = opaqueSortCompareFn;
  23268. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  23269. this.transparentSortCompareFn = transparentSortCompareFn;
  23270. }
  23271. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  23272. /**
  23273. * Set the opaque sort comparison function.
  23274. * If null the sub meshes will be render in the order they were created
  23275. */
  23276. set: function (value) {
  23277. this._opaqueSortCompareFn = value;
  23278. if (value) {
  23279. this._renderOpaque = this.renderOpaqueSorted;
  23280. }
  23281. else {
  23282. this._renderOpaque = RenderingGroup.renderUnsorted;
  23283. }
  23284. },
  23285. enumerable: true,
  23286. configurable: true
  23287. });
  23288. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  23289. /**
  23290. * Set the alpha test sort comparison function.
  23291. * If null the sub meshes will be render in the order they were created
  23292. */
  23293. set: function (value) {
  23294. this._alphaTestSortCompareFn = value;
  23295. if (value) {
  23296. this._renderAlphaTest = this.renderAlphaTestSorted;
  23297. }
  23298. else {
  23299. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  23300. }
  23301. },
  23302. enumerable: true,
  23303. configurable: true
  23304. });
  23305. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  23306. /**
  23307. * Set the transparent sort comparison function.
  23308. * If null the sub meshes will be render in the order they were created
  23309. */
  23310. set: function (value) {
  23311. if (value) {
  23312. this._transparentSortCompareFn = value;
  23313. }
  23314. else {
  23315. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  23316. }
  23317. this._renderTransparent = this.renderTransparentSorted;
  23318. },
  23319. enumerable: true,
  23320. configurable: true
  23321. });
  23322. /**
  23323. * Render all the sub meshes contained in the group.
  23324. * @param customRenderFunction Used to override the default render behaviour of the group.
  23325. * @returns true if rendered some submeshes.
  23326. */
  23327. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  23328. if (customRenderFunction) {
  23329. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  23330. return;
  23331. }
  23332. var engine = this._scene.getEngine();
  23333. // Depth only
  23334. if (this._depthOnlySubMeshes.length !== 0) {
  23335. engine.setColorWrite(false);
  23336. this._renderAlphaTest(this._depthOnlySubMeshes);
  23337. engine.setColorWrite(true);
  23338. }
  23339. // Opaque
  23340. if (this._opaqueSubMeshes.length !== 0) {
  23341. this._renderOpaque(this._opaqueSubMeshes);
  23342. }
  23343. // Alpha test
  23344. if (this._alphaTestSubMeshes.length !== 0) {
  23345. this._renderAlphaTest(this._alphaTestSubMeshes);
  23346. }
  23347. var stencilState = engine.getStencilBuffer();
  23348. engine.setStencilBuffer(false);
  23349. // Sprites
  23350. if (renderSprites) {
  23351. this._renderSprites();
  23352. }
  23353. // Particles
  23354. if (renderParticles) {
  23355. this._renderParticles(activeMeshes);
  23356. }
  23357. if (this.onBeforeTransparentRendering) {
  23358. this.onBeforeTransparentRendering();
  23359. }
  23360. // Transparent
  23361. if (this._transparentSubMeshes.length !== 0) {
  23362. this._renderTransparent(this._transparentSubMeshes);
  23363. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23364. }
  23365. // Set back stencil to false in case it changes before the edge renderer.
  23366. engine.setStencilBuffer(false);
  23367. // Edges
  23368. if (this._edgesRenderers.length) {
  23369. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23370. this._edgesRenderers.data[edgesRendererIndex].render();
  23371. }
  23372. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23373. }
  23374. // Restore Stencil state.
  23375. engine.setStencilBuffer(stencilState);
  23376. };
  23377. /**
  23378. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23379. * @param subMeshes The submeshes to render
  23380. */
  23381. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23382. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23383. };
  23384. /**
  23385. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23386. * @param subMeshes The submeshes to render
  23387. */
  23388. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23389. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23390. };
  23391. /**
  23392. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23393. * @param subMeshes The submeshes to render
  23394. */
  23395. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23396. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23397. };
  23398. /**
  23399. * Renders the submeshes in a specified order.
  23400. * @param subMeshes The submeshes to sort before render
  23401. * @param sortCompareFn The comparison function use to sort
  23402. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23403. * @param transparent Specifies to activate blending if true
  23404. */
  23405. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23406. var subIndex = 0;
  23407. var subMesh;
  23408. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23409. for (; subIndex < subMeshes.length; subIndex++) {
  23410. subMesh = subMeshes.data[subIndex];
  23411. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23412. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23413. }
  23414. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23415. if (sortCompareFn) {
  23416. sortedArray.sort(sortCompareFn);
  23417. }
  23418. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23419. subMesh = sortedArray[subIndex];
  23420. if (transparent) {
  23421. var material = subMesh.getMaterial();
  23422. if (material && material.needDepthPrePass) {
  23423. var engine = material.getScene().getEngine();
  23424. engine.setColorWrite(false);
  23425. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23426. subMesh.render(false);
  23427. engine.setColorWrite(true);
  23428. }
  23429. }
  23430. subMesh.render(transparent);
  23431. }
  23432. };
  23433. /**
  23434. * Renders the submeshes in the order they were dispatched (no sort applied).
  23435. * @param subMeshes The submeshes to render
  23436. */
  23437. RenderingGroup.renderUnsorted = function (subMeshes) {
  23438. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23439. var submesh = subMeshes.data[subIndex];
  23440. submesh.render(false);
  23441. }
  23442. };
  23443. /**
  23444. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23445. * are rendered back to front if in the same alpha index.
  23446. *
  23447. * @param a The first submesh
  23448. * @param b The second submesh
  23449. * @returns The result of the comparison
  23450. */
  23451. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23452. // Alpha index first
  23453. if (a._alphaIndex > b._alphaIndex) {
  23454. return 1;
  23455. }
  23456. if (a._alphaIndex < b._alphaIndex) {
  23457. return -1;
  23458. }
  23459. // Then distance to camera
  23460. return RenderingGroup.backToFrontSortCompare(a, b);
  23461. };
  23462. /**
  23463. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23464. * are rendered back to front.
  23465. *
  23466. * @param a The first submesh
  23467. * @param b The second submesh
  23468. * @returns The result of the comparison
  23469. */
  23470. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23471. // Then distance to camera
  23472. if (a._distanceToCamera < b._distanceToCamera) {
  23473. return 1;
  23474. }
  23475. if (a._distanceToCamera > b._distanceToCamera) {
  23476. return -1;
  23477. }
  23478. return 0;
  23479. };
  23480. /**
  23481. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23482. * are rendered front to back (prevent overdraw).
  23483. *
  23484. * @param a The first submesh
  23485. * @param b The second submesh
  23486. * @returns The result of the comparison
  23487. */
  23488. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23489. // Then distance to camera
  23490. if (a._distanceToCamera < b._distanceToCamera) {
  23491. return -1;
  23492. }
  23493. if (a._distanceToCamera > b._distanceToCamera) {
  23494. return 1;
  23495. }
  23496. return 0;
  23497. };
  23498. /**
  23499. * Resets the different lists of submeshes to prepare a new frame.
  23500. */
  23501. RenderingGroup.prototype.prepare = function () {
  23502. this._opaqueSubMeshes.reset();
  23503. this._transparentSubMeshes.reset();
  23504. this._alphaTestSubMeshes.reset();
  23505. this._depthOnlySubMeshes.reset();
  23506. this._particleSystems.reset();
  23507. this._spriteManagers.reset();
  23508. this._edgesRenderers.reset();
  23509. };
  23510. RenderingGroup.prototype.dispose = function () {
  23511. this._opaqueSubMeshes.dispose();
  23512. this._transparentSubMeshes.dispose();
  23513. this._alphaTestSubMeshes.dispose();
  23514. this._depthOnlySubMeshes.dispose();
  23515. this._particleSystems.dispose();
  23516. this._spriteManagers.dispose();
  23517. this._edgesRenderers.dispose();
  23518. };
  23519. /**
  23520. * Inserts the submesh in its correct queue depending on its material.
  23521. * @param subMesh The submesh to dispatch
  23522. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23523. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23524. */
  23525. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23526. // Get mesh and materials if not provided
  23527. if (mesh === undefined) {
  23528. mesh = subMesh.getMesh();
  23529. }
  23530. if (material === undefined) {
  23531. material = subMesh.getMaterial();
  23532. }
  23533. if (material === null || material === undefined) {
  23534. return;
  23535. }
  23536. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23537. this._transparentSubMeshes.push(subMesh);
  23538. }
  23539. else if (material.needAlphaTesting()) { // Alpha test
  23540. if (material.needDepthPrePass) {
  23541. this._depthOnlySubMeshes.push(subMesh);
  23542. }
  23543. this._alphaTestSubMeshes.push(subMesh);
  23544. }
  23545. else {
  23546. if (material.needDepthPrePass) {
  23547. this._depthOnlySubMeshes.push(subMesh);
  23548. }
  23549. this._opaqueSubMeshes.push(subMesh); // Opaque
  23550. }
  23551. if (mesh._edgesRenderer && mesh._edgesRenderer.isEnabled) {
  23552. this._edgesRenderers.push(mesh._edgesRenderer);
  23553. }
  23554. };
  23555. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23556. this._spriteManagers.push(spriteManager);
  23557. };
  23558. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23559. this._particleSystems.push(particleSystem);
  23560. };
  23561. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23562. if (this._particleSystems.length === 0) {
  23563. return;
  23564. }
  23565. // Particles
  23566. var activeCamera = this._scene.activeCamera;
  23567. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23568. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23569. var particleSystem = this._particleSystems.data[particleIndex];
  23570. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23571. continue;
  23572. }
  23573. var emitter = particleSystem.emitter;
  23574. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23575. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23576. }
  23577. }
  23578. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23579. };
  23580. RenderingGroup.prototype._renderSprites = function () {
  23581. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23582. return;
  23583. }
  23584. // Sprites
  23585. var activeCamera = this._scene.activeCamera;
  23586. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23587. for (var id = 0; id < this._spriteManagers.length; id++) {
  23588. var spriteManager = this._spriteManagers.data[id];
  23589. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23590. spriteManager.render();
  23591. }
  23592. }
  23593. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23594. };
  23595. return RenderingGroup;
  23596. }());
  23597. BABYLON.RenderingGroup = RenderingGroup;
  23598. })(BABYLON || (BABYLON = {}));
  23599. //# sourceMappingURL=babylon.renderingGroup.js.map
  23600. var BABYLON;
  23601. (function (BABYLON) {
  23602. /**
  23603. * Groups all the scene component constants in one place to ease maintenance.
  23604. * @hidden
  23605. */
  23606. var SceneComponentConstants = /** @class */ (function () {
  23607. function SceneComponentConstants() {
  23608. }
  23609. SceneComponentConstants.NAME_EFFECTLAYER = "EffectLayer";
  23610. SceneComponentConstants.NAME_LAYER = "Layer";
  23611. SceneComponentConstants.NAME_LENSFLARESYSTEM = "LensFlareSystem";
  23612. SceneComponentConstants.NAME_BOUNDINGBOXRENDERER = "BoundingBoxRenderer";
  23613. SceneComponentConstants.NAME_PARTICLESYSTEM = "ParticleSystem";
  23614. SceneComponentConstants.NAME_GAMEPAD = "Gamepad";
  23615. SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE = "SimplificationQueue";
  23616. SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER = "GeometryBufferRenderer";
  23617. SceneComponentConstants.NAME_DEPTHRENDERER = "DepthRenderer";
  23618. SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER = "PostProcessRenderPipelineManager";
  23619. SceneComponentConstants.NAME_SPRITE = "Sprite";
  23620. SceneComponentConstants.NAME_OUTLINERENDERER = "Outline";
  23621. SceneComponentConstants.NAME_PROCEDURALTEXTURE = "ProceduralTexture";
  23622. SceneComponentConstants.NAME_SHADOWGENERATOR = "ShadowGenerator";
  23623. SceneComponentConstants.NAME_OCTREE = "Octree";
  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_BEFORERENDERINGMESH_OUTLINE = 0;
  23632. SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE = 0;
  23633. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW = 0;
  23634. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE = 0;
  23635. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD = 1;
  23636. SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE = 0;
  23637. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER = 0;
  23638. SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM = 1;
  23639. SceneComponentConstants.STEP_AFTERCAMERADRAW_BOUNDINGBOXRENDERER = 2;
  23640. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW = 3;
  23641. SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER = 4;
  23642. SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR = 0;
  23643. SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER = 1;
  23644. SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER = 2;
  23645. SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER = 3;
  23646. SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER = 0;
  23647. SceneComponentConstants.STEP_POINTERMOVE_SPRITE = 0;
  23648. SceneComponentConstants.STEP_POINTERDOWN_SPRITE = 0;
  23649. SceneComponentConstants.STEP_POINTERUP_SPRITE = 0;
  23650. return SceneComponentConstants;
  23651. }());
  23652. BABYLON.SceneComponentConstants = SceneComponentConstants;
  23653. /**
  23654. * Repressentation of a stage in the scene (Basically a list of ordered steps)
  23655. * @hidden
  23656. */
  23657. var Stage = /** @class */ (function (_super) {
  23658. __extends(Stage, _super);
  23659. /**
  23660. * Hide ctor from the rest of the world.
  23661. * @param items The items to add.
  23662. */
  23663. function Stage(items) {
  23664. return _super.apply(this, items) || this;
  23665. }
  23666. /**
  23667. * Creates a new Stage.
  23668. * @returns A new instance of a Stage
  23669. */
  23670. Stage.Create = function () {
  23671. return Object.create(Stage.prototype);
  23672. };
  23673. /**
  23674. * Registers a step in an ordered way in the targeted stage.
  23675. * @param index Defines the position to register the step in
  23676. * @param component Defines the component attached to the step
  23677. * @param action Defines the action to launch during the step
  23678. */
  23679. Stage.prototype.registerStep = function (index, component, action) {
  23680. var i = 0;
  23681. var maxIndex = Number.MAX_VALUE;
  23682. for (; i < this.length && i < maxIndex; i++) {
  23683. var step = this[i];
  23684. maxIndex = step.index;
  23685. }
  23686. this.splice(i, 0, { index: index, component: component, action: action.bind(component) });
  23687. };
  23688. /**
  23689. * Clears all the steps from the stage.
  23690. */
  23691. Stage.prototype.clear = function () {
  23692. this.length = 0;
  23693. };
  23694. return Stage;
  23695. }(Array));
  23696. BABYLON.Stage = Stage;
  23697. })(BABYLON || (BABYLON = {}));
  23698. //# sourceMappingURL=babylon.sceneComponent.js.map
  23699. var BABYLON;
  23700. (function (BABYLON) {
  23701. /**
  23702. * Base class of the scene acting as a container for the different elements composing a scene.
  23703. * This class is dynamically extended by the different components of the scene increasing
  23704. * flexibility and reducing coupling
  23705. */
  23706. var AbstractScene = /** @class */ (function () {
  23707. function AbstractScene() {
  23708. /**
  23709. * Gets the list of root nodes (ie. nodes with no parent)
  23710. */
  23711. this.rootNodes = new Array();
  23712. /** All of the cameras added to this scene
  23713. * @see http://doc.babylonjs.com/babylon101/cameras
  23714. */
  23715. this.cameras = new Array();
  23716. /**
  23717. * All of the lights added to this scene
  23718. * @see http://doc.babylonjs.com/babylon101/lights
  23719. */
  23720. this.lights = new Array();
  23721. /**
  23722. * All of the (abstract) meshes added to this scene
  23723. */
  23724. this.meshes = new Array();
  23725. /**
  23726. * The list of skeletons added to the scene
  23727. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  23728. */
  23729. this.skeletons = new Array();
  23730. /**
  23731. * All of the particle systems added to this scene
  23732. * @see http://doc.babylonjs.com/babylon101/particles
  23733. */
  23734. this.particleSystems = new Array();
  23735. /**
  23736. * Gets a list of Animations associated with the scene
  23737. */
  23738. this.animations = [];
  23739. /**
  23740. * All of the animation groups added to this scene
  23741. * @see http://doc.babylonjs.com/how_to/group
  23742. */
  23743. this.animationGroups = new Array();
  23744. /**
  23745. * All of the multi-materials added to this scene
  23746. * @see http://doc.babylonjs.com/how_to/multi_materials
  23747. */
  23748. this.multiMaterials = new Array();
  23749. /**
  23750. * All of the materials added to this scene
  23751. * @see http://doc.babylonjs.com/babylon101/materials
  23752. */
  23753. this.materials = new Array();
  23754. /**
  23755. * The list of morph target managers added to the scene
  23756. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  23757. */
  23758. this.morphTargetManagers = new Array();
  23759. /**
  23760. * The list of geometries used in the scene.
  23761. */
  23762. this.geometries = new Array();
  23763. /**
  23764. * All of the tranform nodes added to this scene
  23765. * @see http://doc.babylonjs.com/how_to/transformnode
  23766. */
  23767. this.transformNodes = new Array();
  23768. /**
  23769. * ActionManagers available on the scene.
  23770. */
  23771. this.actionManagers = new Array();
  23772. /**
  23773. * Sounds to keep.
  23774. */
  23775. this.sounds = new Array();
  23776. /**
  23777. * Textures to keep.
  23778. */
  23779. this.textures = new Array();
  23780. }
  23781. /**
  23782. * Adds a parser in the list of available ones
  23783. * @param name Defines the name of the parser
  23784. * @param parser Defines the parser to add
  23785. */
  23786. AbstractScene.AddParser = function (name, parser) {
  23787. this._BabylonFileParsers[name] = parser;
  23788. };
  23789. /**
  23790. * Gets a general parser from the list of avaialble ones
  23791. * @param name Defines the name of the parser
  23792. * @returns the requested parser or null
  23793. */
  23794. AbstractScene.GetParser = function (name) {
  23795. if (this._BabylonFileParsers[name]) {
  23796. return this._BabylonFileParsers[name];
  23797. }
  23798. return null;
  23799. };
  23800. /**
  23801. * Adds n individual parser in the list of available ones
  23802. * @param name Defines the name of the parser
  23803. * @param parser Defines the parser to add
  23804. */
  23805. AbstractScene.AddIndividualParser = function (name, parser) {
  23806. this._IndividualBabylonFileParsers[name] = parser;
  23807. };
  23808. /**
  23809. * Gets an individual parser from the list of avaialble ones
  23810. * @param name Defines the name of the parser
  23811. * @returns the requested parser or null
  23812. */
  23813. AbstractScene.GetIndividualParser = function (name) {
  23814. if (this._IndividualBabylonFileParsers[name]) {
  23815. return this._IndividualBabylonFileParsers[name];
  23816. }
  23817. return null;
  23818. };
  23819. /**
  23820. * Parser json data and populate both a scene and its associated container object
  23821. * @param jsonData Defines the data to parse
  23822. * @param scene Defines the scene to parse the data for
  23823. * @param container Defines the container attached to the parsing sequence
  23824. * @param rootUrl Defines the root url of the data
  23825. */
  23826. AbstractScene.Parse = function (jsonData, scene, container, rootUrl) {
  23827. for (var parserName in this._BabylonFileParsers) {
  23828. if (this._BabylonFileParsers.hasOwnProperty(parserName)) {
  23829. this._BabylonFileParsers[parserName](jsonData, scene, container, rootUrl);
  23830. }
  23831. }
  23832. };
  23833. /**
  23834. * Stores the list of available parsers in the application.
  23835. */
  23836. AbstractScene._BabylonFileParsers = {};
  23837. /**
  23838. * Stores the list of available individual parsers in the application.
  23839. */
  23840. AbstractScene._IndividualBabylonFileParsers = {};
  23841. return AbstractScene;
  23842. }());
  23843. BABYLON.AbstractScene = AbstractScene;
  23844. })(BABYLON || (BABYLON = {}));
  23845. //# sourceMappingURL=babylon.abstractScene.js.map
  23846. var BABYLON;
  23847. (function (BABYLON) {
  23848. /** @hidden */
  23849. var ClickInfo = /** @class */ (function () {
  23850. function ClickInfo() {
  23851. this._singleClick = false;
  23852. this._doubleClick = false;
  23853. this._hasSwiped = false;
  23854. this._ignore = false;
  23855. }
  23856. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  23857. get: function () {
  23858. return this._singleClick;
  23859. },
  23860. set: function (b) {
  23861. this._singleClick = b;
  23862. },
  23863. enumerable: true,
  23864. configurable: true
  23865. });
  23866. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  23867. get: function () {
  23868. return this._doubleClick;
  23869. },
  23870. set: function (b) {
  23871. this._doubleClick = b;
  23872. },
  23873. enumerable: true,
  23874. configurable: true
  23875. });
  23876. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  23877. get: function () {
  23878. return this._hasSwiped;
  23879. },
  23880. set: function (b) {
  23881. this._hasSwiped = b;
  23882. },
  23883. enumerable: true,
  23884. configurable: true
  23885. });
  23886. Object.defineProperty(ClickInfo.prototype, "ignore", {
  23887. get: function () {
  23888. return this._ignore;
  23889. },
  23890. set: function (b) {
  23891. this._ignore = b;
  23892. },
  23893. enumerable: true,
  23894. configurable: true
  23895. });
  23896. return ClickInfo;
  23897. }());
  23898. /**
  23899. * This class is used by the onRenderingGroupObservable
  23900. */
  23901. var RenderingGroupInfo = /** @class */ (function () {
  23902. function RenderingGroupInfo() {
  23903. }
  23904. return RenderingGroupInfo;
  23905. }());
  23906. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  23907. /**
  23908. * Represents a scene to be rendered by the engine.
  23909. * @see http://doc.babylonjs.com/features/scene
  23910. */
  23911. var Scene = /** @class */ (function (_super) {
  23912. __extends(Scene, _super);
  23913. /**
  23914. * Creates a new Scene
  23915. * @param engine defines the engine to use to render this scene
  23916. */
  23917. function Scene(engine) {
  23918. var _this = _super.call(this) || this;
  23919. // Members
  23920. /**
  23921. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  23922. */
  23923. _this.autoClear = true;
  23924. /**
  23925. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  23926. */
  23927. _this.autoClearDepthAndStencil = true;
  23928. /**
  23929. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  23930. */
  23931. _this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  23932. /**
  23933. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  23934. */
  23935. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  23936. _this._forceWireframe = false;
  23937. _this._forcePointsCloud = false;
  23938. /**
  23939. * Gets or sets a boolean indicating if animations are enabled
  23940. */
  23941. _this.animationsEnabled = true;
  23942. _this._animationPropertiesOverride = null;
  23943. /**
  23944. * Gets or sets a boolean indicating if a constant deltatime has to be used
  23945. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  23946. */
  23947. _this.useConstantAnimationDeltaTime = false;
  23948. /**
  23949. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  23950. * Please note that it requires to run a ray cast through the scene on every frame
  23951. */
  23952. _this.constantlyUpdateMeshUnderPointer = false;
  23953. /**
  23954. * Defines the HTML cursor to use when hovering over interactive elements
  23955. */
  23956. _this.hoverCursor = "pointer";
  23957. /**
  23958. * Defines the HTML default cursor to use (empty by default)
  23959. */
  23960. _this.defaultCursor = "";
  23961. /**
  23962. * This is used to call preventDefault() on pointer down
  23963. * in order to block unwanted artifacts like system double clicks
  23964. */
  23965. _this.preventDefaultOnPointerDown = true;
  23966. // Metadata
  23967. /**
  23968. * Gets or sets user defined metadata
  23969. */
  23970. _this.metadata = null;
  23971. /**
  23972. * Use this array to add regular expressions used to disable offline support for specific urls
  23973. */
  23974. _this.disableOfflineSupportExceptionRules = new Array();
  23975. /**
  23976. * An event triggered when the scene is disposed.
  23977. */
  23978. _this.onDisposeObservable = new BABYLON.Observable();
  23979. _this._onDisposeObserver = null;
  23980. /**
  23981. * An event triggered before rendering the scene (right after animations and physics)
  23982. */
  23983. _this.onBeforeRenderObservable = new BABYLON.Observable();
  23984. _this._onBeforeRenderObserver = null;
  23985. /**
  23986. * An event triggered after rendering the scene
  23987. */
  23988. _this.onAfterRenderObservable = new BABYLON.Observable();
  23989. _this._onAfterRenderObserver = null;
  23990. /**
  23991. * An event triggered before animating the scene
  23992. */
  23993. _this.onBeforeAnimationsObservable = new BABYLON.Observable();
  23994. /**
  23995. * An event triggered after animations processing
  23996. */
  23997. _this.onAfterAnimationsObservable = new BABYLON.Observable();
  23998. /**
  23999. * An event triggered before draw calls are ready to be sent
  24000. */
  24001. _this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  24002. /**
  24003. * An event triggered after draw calls have been sent
  24004. */
  24005. _this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  24006. /**
  24007. * An event triggered when physic simulation is about to be run
  24008. */
  24009. _this.onBeforePhysicsObservable = new BABYLON.Observable();
  24010. /**
  24011. * An event triggered when physic simulation has been done
  24012. */
  24013. _this.onAfterPhysicsObservable = new BABYLON.Observable();
  24014. /**
  24015. * An event triggered when the scene is ready
  24016. */
  24017. _this.onReadyObservable = new BABYLON.Observable();
  24018. /**
  24019. * An event triggered before rendering a camera
  24020. */
  24021. _this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  24022. _this._onBeforeCameraRenderObserver = null;
  24023. /**
  24024. * An event triggered after rendering a camera
  24025. */
  24026. _this.onAfterCameraRenderObservable = new BABYLON.Observable();
  24027. _this._onAfterCameraRenderObserver = null;
  24028. /**
  24029. * An event triggered when active meshes evaluation is about to start
  24030. */
  24031. _this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  24032. /**
  24033. * An event triggered when active meshes evaluation is done
  24034. */
  24035. _this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  24036. /**
  24037. * An event triggered when particles rendering is about to start
  24038. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  24039. */
  24040. _this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  24041. /**
  24042. * An event triggered when particles rendering is done
  24043. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  24044. */
  24045. _this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  24046. /**
  24047. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  24048. */
  24049. _this.onDataLoadedObservable = new BABYLON.Observable();
  24050. /**
  24051. * An event triggered when a camera is created
  24052. */
  24053. _this.onNewCameraAddedObservable = new BABYLON.Observable();
  24054. /**
  24055. * An event triggered when a camera is removed
  24056. */
  24057. _this.onCameraRemovedObservable = new BABYLON.Observable();
  24058. /**
  24059. * An event triggered when a light is created
  24060. */
  24061. _this.onNewLightAddedObservable = new BABYLON.Observable();
  24062. /**
  24063. * An event triggered when a light is removed
  24064. */
  24065. _this.onLightRemovedObservable = new BABYLON.Observable();
  24066. /**
  24067. * An event triggered when a geometry is created
  24068. */
  24069. _this.onNewGeometryAddedObservable = new BABYLON.Observable();
  24070. /**
  24071. * An event triggered when a geometry is removed
  24072. */
  24073. _this.onGeometryRemovedObservable = new BABYLON.Observable();
  24074. /**
  24075. * An event triggered when a transform node is created
  24076. */
  24077. _this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  24078. /**
  24079. * An event triggered when a transform node is removed
  24080. */
  24081. _this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  24082. /**
  24083. * An event triggered when a mesh is created
  24084. */
  24085. _this.onNewMeshAddedObservable = new BABYLON.Observable();
  24086. /**
  24087. * An event triggered when a mesh is removed
  24088. */
  24089. _this.onMeshRemovedObservable = new BABYLON.Observable();
  24090. /**
  24091. * An event triggered when render targets are about to be rendered
  24092. * Can happen multiple times per frame.
  24093. */
  24094. _this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  24095. /**
  24096. * An event triggered when render targets were rendered.
  24097. * Can happen multiple times per frame.
  24098. */
  24099. _this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  24100. /**
  24101. * An event triggered before calculating deterministic simulation step
  24102. */
  24103. _this.onBeforeStepObservable = new BABYLON.Observable();
  24104. /**
  24105. * An event triggered after calculating deterministic simulation step
  24106. */
  24107. _this.onAfterStepObservable = new BABYLON.Observable();
  24108. /**
  24109. * This Observable will be triggered before rendering each renderingGroup of each rendered camera.
  24110. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  24111. * 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)
  24112. */
  24113. _this.onBeforeRenderingGroupObservable = new BABYLON.Observable();
  24114. /**
  24115. * This Observable will be triggered after rendering each renderingGroup of each rendered camera.
  24116. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  24117. * 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)
  24118. */
  24119. _this.onAfterRenderingGroupObservable = new BABYLON.Observable();
  24120. /**
  24121. * This Observable will when a mesh has been imported into the scene.
  24122. */
  24123. _this.onMeshImportedObservable = new BABYLON.Observable();
  24124. // Animations
  24125. _this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  24126. /**
  24127. * 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).
  24128. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  24129. */
  24130. _this.onPrePointerObservable = new BABYLON.Observable();
  24131. /**
  24132. * Observable event triggered each time an input event is received from the rendering canvas
  24133. */
  24134. _this.onPointerObservable = new BABYLON.Observable();
  24135. _this._meshPickProceed = false;
  24136. _this._currentPickResult = null;
  24137. _this._previousPickResult = null;
  24138. _this._totalPointersPressed = 0;
  24139. _this._doubleClickOccured = false;
  24140. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  24141. _this.cameraToUseForPointers = null;
  24142. _this._pointerX = 0;
  24143. _this._pointerY = 0;
  24144. _this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  24145. _this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  24146. _this._startingPointerTime = 0;
  24147. _this._previousStartingPointerTime = 0;
  24148. _this._pointerCaptures = {};
  24149. // Deterministic lockstep
  24150. _this._timeAccumulator = 0;
  24151. _this._currentStepId = 0;
  24152. _this._currentInternalStep = 0;
  24153. // Keyboard
  24154. /**
  24155. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  24156. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  24157. */
  24158. _this.onPreKeyboardObservable = new BABYLON.Observable();
  24159. /**
  24160. * Observable event triggered each time an keyboard event is received from the hosting window
  24161. */
  24162. _this.onKeyboardObservable = new BABYLON.Observable();
  24163. // Coordinates system
  24164. _this._useRightHandedSystem = false;
  24165. // Fog
  24166. _this._fogEnabled = true;
  24167. _this._fogMode = Scene.FOGMODE_NONE;
  24168. /**
  24169. * Gets or sets the fog color to use
  24170. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24171. */
  24172. _this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  24173. /**
  24174. * Gets or sets the fog density to use
  24175. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24176. */
  24177. _this.fogDensity = 0.1;
  24178. /**
  24179. * Gets or sets the fog start distance to use
  24180. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24181. */
  24182. _this.fogStart = 0;
  24183. /**
  24184. * Gets or sets the fog end distance to use
  24185. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24186. */
  24187. _this.fogEnd = 1000.0;
  24188. // Lights
  24189. _this._shadowsEnabled = true;
  24190. _this._lightsEnabled = true;
  24191. /** All of the active cameras added to this scene. */
  24192. _this.activeCameras = new Array();
  24193. // Textures
  24194. _this._texturesEnabled = true;
  24195. // Particles
  24196. /**
  24197. * Gets or sets a boolean indicating if particles are enabled on this scene
  24198. */
  24199. _this.particlesEnabled = true;
  24200. // Sprites
  24201. /**
  24202. * Gets or sets a boolean indicating if sprites are enabled on this scene
  24203. */
  24204. _this.spritesEnabled = true;
  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. _this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  24256. // Procedural textures
  24257. /**
  24258. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  24259. */
  24260. _this.proceduralTexturesEnabled = true;
  24261. /**
  24262. * The list of sound tracks added to the scene
  24263. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  24264. */
  24265. _this.soundTracks = new Array();
  24266. _this._audioEnabled = true;
  24267. _this._headphone = false;
  24268. // Performance counters
  24269. _this._totalVertices = new BABYLON.PerfCounter();
  24270. /** @hidden */
  24271. _this._activeIndices = new BABYLON.PerfCounter();
  24272. /** @hidden */
  24273. _this._activeParticles = new BABYLON.PerfCounter();
  24274. /** @hidden */
  24275. _this._activeBones = new BABYLON.PerfCounter();
  24276. _this._animationTime = 0;
  24277. /**
  24278. * Gets or sets a general scale for animation speed
  24279. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  24280. */
  24281. _this.animationTimeScale = 1;
  24282. _this._renderId = 0;
  24283. _this._frameId = 0;
  24284. _this._executeWhenReadyTimeoutId = -1;
  24285. _this._intermediateRendering = false;
  24286. _this._viewUpdateFlag = -1;
  24287. _this._projectionUpdateFlag = -1;
  24288. _this._alternateViewUpdateFlag = -1;
  24289. _this._alternateProjectionUpdateFlag = -1;
  24290. /** @hidden */
  24291. _this._toBeDisposed = new BABYLON.SmartArray(256);
  24292. _this._activeRequests = new Array();
  24293. _this._pendingData = new Array();
  24294. _this._isDisposed = false;
  24295. /**
  24296. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  24297. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  24298. */
  24299. _this.dispatchAllSubMeshesOfActiveMeshes = false;
  24300. _this._activeMeshes = new BABYLON.SmartArray(256);
  24301. _this._processedMaterials = new BABYLON.SmartArray(256);
  24302. _this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  24303. /** @hidden */
  24304. _this._activeParticleSystems = new BABYLON.SmartArray(256);
  24305. _this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  24306. _this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  24307. /** @hidden */
  24308. _this._activeAnimatables = new Array();
  24309. _this._transformMatrix = BABYLON.Matrix.Zero();
  24310. _this._useAlternateCameraConfiguration = false;
  24311. _this._alternateRendering = false;
  24312. /**
  24313. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  24314. * This is useful if there are more lights that the maximum simulteanous authorized
  24315. */
  24316. _this.requireLightSorting = false;
  24317. /**
  24318. * @hidden
  24319. * Backing store of defined scene components.
  24320. */
  24321. _this._components = [];
  24322. /**
  24323. * @hidden
  24324. * Backing store of defined scene components.
  24325. */
  24326. _this._serializableComponents = [];
  24327. /**
  24328. * List of components to register on the next registration step.
  24329. */
  24330. _this._transientComponents = [];
  24331. /**
  24332. * @hidden
  24333. * Defines the actions happening before camera updates.
  24334. */
  24335. _this._beforeCameraUpdateStage = BABYLON.Stage.Create();
  24336. /**
  24337. * @hidden
  24338. * Defines the actions happening before clear the canvas.
  24339. */
  24340. _this._beforeClearStage = BABYLON.Stage.Create();
  24341. /**
  24342. * @hidden
  24343. * Defines the actions when collecting render targets for the frame.
  24344. */
  24345. _this._gatherRenderTargetsStage = BABYLON.Stage.Create();
  24346. /**
  24347. * @hidden
  24348. * Defines the actions happening for one camera in the frame.
  24349. */
  24350. _this._gatherActiveCameraRenderTargetsStage = BABYLON.Stage.Create();
  24351. /**
  24352. * @hidden
  24353. * Defines the actions happening during the per mesh ready checks.
  24354. */
  24355. _this._isReadyForMeshStage = BABYLON.Stage.Create();
  24356. /**
  24357. * @hidden
  24358. * Defines the actions happening before evaluate active mesh checks.
  24359. */
  24360. _this._beforeEvaluateActiveMeshStage = BABYLON.Stage.Create();
  24361. /**
  24362. * @hidden
  24363. * Defines the actions happening during the evaluate sub mesh checks.
  24364. */
  24365. _this._evaluateSubMeshStage = BABYLON.Stage.Create();
  24366. /**
  24367. * @hidden
  24368. * Defines the actions happening during the active mesh stage.
  24369. */
  24370. _this._activeMeshStage = BABYLON.Stage.Create();
  24371. /**
  24372. * @hidden
  24373. * Defines the actions happening during the per camera render target step.
  24374. */
  24375. _this._cameraDrawRenderTargetStage = BABYLON.Stage.Create();
  24376. /**
  24377. * @hidden
  24378. * Defines the actions happening just before the active camera is drawing.
  24379. */
  24380. _this._beforeCameraDrawStage = BABYLON.Stage.Create();
  24381. /**
  24382. * @hidden
  24383. * Defines the actions happening just before a rendering group is drawing.
  24384. */
  24385. _this._beforeRenderingGroupDrawStage = BABYLON.Stage.Create();
  24386. /**
  24387. * @hidden
  24388. * Defines the actions happening just before a mesh is drawing.
  24389. */
  24390. _this._beforeRenderingMeshStage = BABYLON.Stage.Create();
  24391. /**
  24392. * @hidden
  24393. * Defines the actions happening just after a mesh has been drawn.
  24394. */
  24395. _this._afterRenderingMeshStage = BABYLON.Stage.Create();
  24396. /**
  24397. * @hidden
  24398. * Defines the actions happening just after a rendering group has been drawn.
  24399. */
  24400. _this._afterRenderingGroupDrawStage = BABYLON.Stage.Create();
  24401. /**
  24402. * @hidden
  24403. * Defines the actions happening just after the active camera has been drawn.
  24404. */
  24405. _this._afterCameraDrawStage = BABYLON.Stage.Create();
  24406. /**
  24407. * @hidden
  24408. * Defines the actions happening when a pointer move event happens.
  24409. */
  24410. _this._pointerMoveStage = BABYLON.Stage.Create();
  24411. /**
  24412. * @hidden
  24413. * Defines the actions happening when a pointer down event happens.
  24414. */
  24415. _this._pointerDownStage = BABYLON.Stage.Create();
  24416. /**
  24417. * @hidden
  24418. * Defines the actions happening when a pointer up event happens.
  24419. */
  24420. _this._pointerUpStage = BABYLON.Stage.Create();
  24421. _this._defaultMeshCandidates = {
  24422. data: [],
  24423. length: 0
  24424. };
  24425. _this._defaultSubMeshCandidates = {
  24426. data: [],
  24427. length: 0
  24428. };
  24429. _this._activeMeshesFrozen = false;
  24430. /** @hidden */
  24431. _this._allowPostProcessClearColor = true;
  24432. _this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  24433. /** Gets or sets a boolean blocking all the calls to markAllMaterialsAsDirty (ie. the materials won't be updated if they are out of sync) */
  24434. _this.blockMaterialDirtyMechanism = false;
  24435. _this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24436. _this._engine.scenes.push(_this);
  24437. _this._uid = null;
  24438. _this._renderingManager = new BABYLON.RenderingManager(_this);
  24439. if (BABYLON.PostProcessManager) {
  24440. _this.postProcessManager = new BABYLON.PostProcessManager(_this);
  24441. }
  24442. if (BABYLON.Tools.IsWindowObjectExist()) {
  24443. _this.attachControl();
  24444. }
  24445. //collision coordinator initialization. For now legacy per default.
  24446. _this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24447. // Uniform Buffer
  24448. _this._createUbo();
  24449. // Default Image processing definition
  24450. if (BABYLON.ImageProcessingConfiguration) {
  24451. _this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24452. }
  24453. _this.setDefaultCandidateProviders();
  24454. return _this;
  24455. }
  24456. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24457. /**
  24458. * Texture used in all pbr material as the reflection texture.
  24459. * As in the majority of the scene they are the same (exception for multi room and so on),
  24460. * this is easier to reference from here than from all the materials.
  24461. */
  24462. get: function () {
  24463. return this._environmentTexture;
  24464. },
  24465. /**
  24466. * Texture used in all pbr material as the reflection texture.
  24467. * As in the majority of the scene they are the same (exception for multi room and so on),
  24468. * this is easier to set here than in all the materials.
  24469. */
  24470. set: function (value) {
  24471. if (this._environmentTexture === value) {
  24472. return;
  24473. }
  24474. this._environmentTexture = value;
  24475. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24476. },
  24477. enumerable: true,
  24478. configurable: true
  24479. });
  24480. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24481. /**
  24482. * Default image processing configuration used either in the rendering
  24483. * Forward main pass or through the imageProcessingPostProcess if present.
  24484. * As in the majority of the scene they are the same (exception for multi camera),
  24485. * this is easier to reference from here than from all the materials and post process.
  24486. *
  24487. * No setter as we it is a shared configuration, you can set the values instead.
  24488. */
  24489. get: function () {
  24490. return this._imageProcessingConfiguration;
  24491. },
  24492. enumerable: true,
  24493. configurable: true
  24494. });
  24495. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24496. get: function () {
  24497. return this._forceWireframe;
  24498. },
  24499. /**
  24500. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24501. */
  24502. set: function (value) {
  24503. if (this._forceWireframe === value) {
  24504. return;
  24505. }
  24506. this._forceWireframe = value;
  24507. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24508. },
  24509. enumerable: true,
  24510. configurable: true
  24511. });
  24512. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24513. get: function () {
  24514. return this._forcePointsCloud;
  24515. },
  24516. /**
  24517. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24518. */
  24519. set: function (value) {
  24520. if (this._forcePointsCloud === value) {
  24521. return;
  24522. }
  24523. this._forcePointsCloud = value;
  24524. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24525. },
  24526. enumerable: true,
  24527. configurable: true
  24528. });
  24529. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24530. /**
  24531. * Gets or sets the animation properties override
  24532. */
  24533. get: function () {
  24534. return this._animationPropertiesOverride;
  24535. },
  24536. set: function (value) {
  24537. this._animationPropertiesOverride = value;
  24538. },
  24539. enumerable: true,
  24540. configurable: true
  24541. });
  24542. Object.defineProperty(Scene.prototype, "onDispose", {
  24543. /** Sets a function to be executed when this scene is disposed. */
  24544. set: function (callback) {
  24545. if (this._onDisposeObserver) {
  24546. this.onDisposeObservable.remove(this._onDisposeObserver);
  24547. }
  24548. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24549. },
  24550. enumerable: true,
  24551. configurable: true
  24552. });
  24553. Object.defineProperty(Scene.prototype, "beforeRender", {
  24554. /** Sets a function to be executed before rendering this scene */
  24555. set: function (callback) {
  24556. if (this._onBeforeRenderObserver) {
  24557. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24558. }
  24559. if (callback) {
  24560. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24561. }
  24562. },
  24563. enumerable: true,
  24564. configurable: true
  24565. });
  24566. Object.defineProperty(Scene.prototype, "afterRender", {
  24567. /** Sets a function to be executed after rendering this scene */
  24568. set: function (callback) {
  24569. if (this._onAfterRenderObserver) {
  24570. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24571. }
  24572. if (callback) {
  24573. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24574. }
  24575. },
  24576. enumerable: true,
  24577. configurable: true
  24578. });
  24579. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24580. /** Sets a function to be executed before rendering a camera*/
  24581. set: function (callback) {
  24582. if (this._onBeforeCameraRenderObserver) {
  24583. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24584. }
  24585. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24586. },
  24587. enumerable: true,
  24588. configurable: true
  24589. });
  24590. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24591. /** Sets a function to be executed after rendering a camera*/
  24592. set: function (callback) {
  24593. if (this._onAfterCameraRenderObserver) {
  24594. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24595. }
  24596. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24597. },
  24598. enumerable: true,
  24599. configurable: true
  24600. });
  24601. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24602. /**
  24603. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24604. */
  24605. get: function () {
  24606. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24607. },
  24608. enumerable: true,
  24609. configurable: true
  24610. });
  24611. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24612. get: function () {
  24613. return this._useRightHandedSystem;
  24614. },
  24615. /**
  24616. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24617. */
  24618. set: function (value) {
  24619. if (this._useRightHandedSystem === value) {
  24620. return;
  24621. }
  24622. this._useRightHandedSystem = value;
  24623. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24624. },
  24625. enumerable: true,
  24626. configurable: true
  24627. });
  24628. /**
  24629. * Sets the step Id used by deterministic lock step
  24630. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24631. * @param newStepId defines the step Id
  24632. */
  24633. Scene.prototype.setStepId = function (newStepId) {
  24634. this._currentStepId = newStepId;
  24635. };
  24636. ;
  24637. /**
  24638. * Gets the step Id used by deterministic lock step
  24639. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24640. * @returns the step Id
  24641. */
  24642. Scene.prototype.getStepId = function () {
  24643. return this._currentStepId;
  24644. };
  24645. ;
  24646. /**
  24647. * Gets the internal step used by deterministic lock step
  24648. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24649. * @returns the internal step
  24650. */
  24651. Scene.prototype.getInternalStep = function () {
  24652. return this._currentInternalStep;
  24653. };
  24654. ;
  24655. Object.defineProperty(Scene.prototype, "fogEnabled", {
  24656. get: function () {
  24657. return this._fogEnabled;
  24658. },
  24659. /**
  24660. * Gets or sets a boolean indicating if fog is enabled on this scene
  24661. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24662. */
  24663. set: function (value) {
  24664. if (this._fogEnabled === value) {
  24665. return;
  24666. }
  24667. this._fogEnabled = value;
  24668. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24669. },
  24670. enumerable: true,
  24671. configurable: true
  24672. });
  24673. Object.defineProperty(Scene.prototype, "fogMode", {
  24674. get: function () {
  24675. return this._fogMode;
  24676. },
  24677. /**
  24678. * Gets or sets the fog mode to use
  24679. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24680. */
  24681. set: function (value) {
  24682. if (this._fogMode === value) {
  24683. return;
  24684. }
  24685. this._fogMode = value;
  24686. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24687. },
  24688. enumerable: true,
  24689. configurable: true
  24690. });
  24691. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24692. get: function () {
  24693. return this._shadowsEnabled;
  24694. },
  24695. /**
  24696. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24697. */
  24698. set: function (value) {
  24699. if (this._shadowsEnabled === value) {
  24700. return;
  24701. }
  24702. this._shadowsEnabled = value;
  24703. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24704. },
  24705. enumerable: true,
  24706. configurable: true
  24707. });
  24708. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24709. get: function () {
  24710. return this._lightsEnabled;
  24711. },
  24712. /**
  24713. * Gets or sets a boolean indicating if lights are enabled on this scene
  24714. */
  24715. set: function (value) {
  24716. if (this._lightsEnabled === value) {
  24717. return;
  24718. }
  24719. this._lightsEnabled = value;
  24720. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24721. },
  24722. enumerable: true,
  24723. configurable: true
  24724. });
  24725. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24726. /** The default material used on meshes when no material is affected */
  24727. get: function () {
  24728. if (!this._defaultMaterial) {
  24729. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24730. }
  24731. return this._defaultMaterial;
  24732. },
  24733. /** The default material used on meshes when no material is affected */
  24734. set: function (value) {
  24735. this._defaultMaterial = value;
  24736. },
  24737. enumerable: true,
  24738. configurable: true
  24739. });
  24740. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24741. get: function () {
  24742. return this._texturesEnabled;
  24743. },
  24744. /**
  24745. * Gets or sets a boolean indicating if textures are enabled on this scene
  24746. */
  24747. set: function (value) {
  24748. if (this._texturesEnabled === value) {
  24749. return;
  24750. }
  24751. this._texturesEnabled = value;
  24752. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24753. },
  24754. enumerable: true,
  24755. configurable: true
  24756. });
  24757. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24758. get: function () {
  24759. return this._skeletonsEnabled;
  24760. },
  24761. /**
  24762. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24763. */
  24764. set: function (value) {
  24765. if (this._skeletonsEnabled === value) {
  24766. return;
  24767. }
  24768. this._skeletonsEnabled = value;
  24769. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24770. },
  24771. enumerable: true,
  24772. configurable: true
  24773. });
  24774. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  24775. /**
  24776. * Gets the main soundtrack associated with the scene
  24777. */
  24778. get: function () {
  24779. if (!this._mainSoundTrack) {
  24780. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  24781. }
  24782. return this._mainSoundTrack;
  24783. },
  24784. enumerable: true,
  24785. configurable: true
  24786. });
  24787. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24788. /** @hidden */
  24789. get: function () {
  24790. return this._alternateRendering;
  24791. },
  24792. enumerable: true,
  24793. configurable: true
  24794. });
  24795. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24796. /**
  24797. * Gets the list of frustum planes (built from the active camera)
  24798. */
  24799. get: function () {
  24800. return this._frustumPlanes;
  24801. },
  24802. enumerable: true,
  24803. configurable: true
  24804. });
  24805. /**
  24806. * Registers the transient components if needed.
  24807. */
  24808. Scene.prototype._registerTransientComponents = function () {
  24809. // Register components that have been associated lately to the scene.
  24810. if (this._transientComponents.length > 0) {
  24811. for (var _i = 0, _a = this._transientComponents; _i < _a.length; _i++) {
  24812. var component = _a[_i];
  24813. component.register();
  24814. }
  24815. this._transientComponents = [];
  24816. }
  24817. };
  24818. /**
  24819. * @hidden
  24820. * Add a component to the scene.
  24821. * Note that the ccomponent could be registered on th next frame if this is called after
  24822. * the register component stage.
  24823. * @param component Defines the component to add to the scene
  24824. */
  24825. Scene.prototype._addComponent = function (component) {
  24826. this._components.push(component);
  24827. this._transientComponents.push(component);
  24828. var serializableComponent = component;
  24829. if (serializableComponent.addFromContainer) {
  24830. this._serializableComponents.push(serializableComponent);
  24831. }
  24832. };
  24833. /**
  24834. * @hidden
  24835. * Gets a component from the scene.
  24836. * @param name defines the name of the component to retrieve
  24837. * @returns the component or null if not present
  24838. */
  24839. Scene.prototype._getComponent = function (name) {
  24840. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  24841. var component = _a[_i];
  24842. if (component.name === name) {
  24843. return component;
  24844. }
  24845. }
  24846. return null;
  24847. };
  24848. /**
  24849. * @hidden
  24850. */
  24851. Scene.prototype._getDefaultMeshCandidates = function () {
  24852. this._defaultMeshCandidates.data = this.meshes;
  24853. this._defaultMeshCandidates.length = this.meshes.length;
  24854. return this._defaultMeshCandidates;
  24855. };
  24856. /**
  24857. * @hidden
  24858. */
  24859. Scene.prototype._getDefaultSubMeshCandidates = function (mesh) {
  24860. this._defaultSubMeshCandidates.data = mesh.subMeshes;
  24861. this._defaultSubMeshCandidates.length = mesh.subMeshes.length;
  24862. return this._defaultSubMeshCandidates;
  24863. };
  24864. /**
  24865. * Sets the default candidate providers for the scene.
  24866. * This sets the getActiveMeshCandidates, getActiveSubMeshCandidates, getIntersectingSubMeshCandidates
  24867. * and getCollidingSubMeshCandidates to their default function
  24868. */
  24869. Scene.prototype.setDefaultCandidateProviders = function () {
  24870. this.getActiveMeshCandidates = this._getDefaultMeshCandidates.bind(this);
  24871. this.getActiveSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  24872. this.getIntersectingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  24873. this.getCollidingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  24874. };
  24875. Object.defineProperty(Scene.prototype, "workerCollisions", {
  24876. /**
  24877. * Gets a boolean indicating if collisions are processed on a web worker
  24878. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  24879. */
  24880. get: function () {
  24881. return this._workerCollisions;
  24882. },
  24883. set: function (enabled) {
  24884. if (!BABYLON.CollisionCoordinatorLegacy) {
  24885. return;
  24886. }
  24887. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  24888. this._workerCollisions = enabled;
  24889. if (this.collisionCoordinator) {
  24890. this.collisionCoordinator.destroy();
  24891. }
  24892. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  24893. this.collisionCoordinator.init(this);
  24894. },
  24895. enumerable: true,
  24896. configurable: true
  24897. });
  24898. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  24899. /**
  24900. * Gets the mesh that is currently under the pointer
  24901. */
  24902. get: function () {
  24903. return this._pointerOverMesh;
  24904. },
  24905. enumerable: true,
  24906. configurable: true
  24907. });
  24908. Object.defineProperty(Scene.prototype, "pointerX", {
  24909. /**
  24910. * Gets the current on-screen X position of the pointer
  24911. */
  24912. get: function () {
  24913. return this._pointerX;
  24914. },
  24915. enumerable: true,
  24916. configurable: true
  24917. });
  24918. Object.defineProperty(Scene.prototype, "pointerY", {
  24919. /**
  24920. * Gets the current on-screen Y position of the pointer
  24921. */
  24922. get: function () {
  24923. return this._pointerY;
  24924. },
  24925. enumerable: true,
  24926. configurable: true
  24927. });
  24928. /**
  24929. * Gets the cached material (ie. the latest rendered one)
  24930. * @returns the cached material
  24931. */
  24932. Scene.prototype.getCachedMaterial = function () {
  24933. return this._cachedMaterial;
  24934. };
  24935. /**
  24936. * Gets the cached effect (ie. the latest rendered one)
  24937. * @returns the cached effect
  24938. */
  24939. Scene.prototype.getCachedEffect = function () {
  24940. return this._cachedEffect;
  24941. };
  24942. /**
  24943. * Gets the cached visibility state (ie. the latest rendered one)
  24944. * @returns the cached visibility state
  24945. */
  24946. Scene.prototype.getCachedVisibility = function () {
  24947. return this._cachedVisibility;
  24948. };
  24949. /**
  24950. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  24951. * @param material defines the current material
  24952. * @param effect defines the current effect
  24953. * @param visibility defines the current visibility state
  24954. * @returns true if one parameter is not cached
  24955. */
  24956. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  24957. if (visibility === void 0) { visibility = 1; }
  24958. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  24959. };
  24960. /**
  24961. * Gets the engine associated with the scene
  24962. * @returns an Engine
  24963. */
  24964. Scene.prototype.getEngine = function () {
  24965. return this._engine;
  24966. };
  24967. /**
  24968. * Gets the total number of vertices rendered per frame
  24969. * @returns the total number of vertices rendered per frame
  24970. */
  24971. Scene.prototype.getTotalVertices = function () {
  24972. return this._totalVertices.current;
  24973. };
  24974. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  24975. /**
  24976. * Gets the performance counter for total vertices
  24977. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24978. */
  24979. get: function () {
  24980. return this._totalVertices;
  24981. },
  24982. enumerable: true,
  24983. configurable: true
  24984. });
  24985. /**
  24986. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  24987. * @returns the total number of active indices rendered per frame
  24988. */
  24989. Scene.prototype.getActiveIndices = function () {
  24990. return this._activeIndices.current;
  24991. };
  24992. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  24993. /**
  24994. * Gets the performance counter for active indices
  24995. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24996. */
  24997. get: function () {
  24998. return this._activeIndices;
  24999. },
  25000. enumerable: true,
  25001. configurable: true
  25002. });
  25003. /**
  25004. * Gets the total number of active particles rendered per frame
  25005. * @returns the total number of active particles rendered per frame
  25006. */
  25007. Scene.prototype.getActiveParticles = function () {
  25008. return this._activeParticles.current;
  25009. };
  25010. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  25011. /**
  25012. * Gets the performance counter for active particles
  25013. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25014. */
  25015. get: function () {
  25016. return this._activeParticles;
  25017. },
  25018. enumerable: true,
  25019. configurable: true
  25020. });
  25021. /**
  25022. * Gets the total number of active bones rendered per frame
  25023. * @returns the total number of active bones rendered per frame
  25024. */
  25025. Scene.prototype.getActiveBones = function () {
  25026. return this._activeBones.current;
  25027. };
  25028. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  25029. /**
  25030. * Gets the performance counter for active bones
  25031. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25032. */
  25033. get: function () {
  25034. return this._activeBones;
  25035. },
  25036. enumerable: true,
  25037. configurable: true
  25038. });
  25039. /** @hidden */
  25040. Scene.prototype.getInterFramePerfCounter = function () {
  25041. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25042. return 0;
  25043. };
  25044. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  25045. /** @hidden */
  25046. get: function () {
  25047. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25048. return null;
  25049. },
  25050. enumerable: true,
  25051. configurable: true
  25052. });
  25053. /** @hidden */
  25054. Scene.prototype.getLastFrameDuration = function () {
  25055. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  25056. return 0;
  25057. };
  25058. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  25059. /** @hidden */
  25060. get: function () {
  25061. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25062. return null;
  25063. },
  25064. enumerable: true,
  25065. configurable: true
  25066. });
  25067. /** @hidden */
  25068. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  25069. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  25070. return 0;
  25071. };
  25072. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  25073. /** @hidden */
  25074. get: function () {
  25075. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25076. return null;
  25077. },
  25078. enumerable: true,
  25079. configurable: true
  25080. });
  25081. /**
  25082. * Gets the array of active meshes
  25083. * @returns an array of AbstractMesh
  25084. */
  25085. Scene.prototype.getActiveMeshes = function () {
  25086. return this._activeMeshes;
  25087. };
  25088. /** @hidden */
  25089. Scene.prototype.getRenderTargetsDuration = function () {
  25090. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  25091. return 0;
  25092. };
  25093. /** @hidden */
  25094. Scene.prototype.getRenderDuration = function () {
  25095. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  25096. return 0;
  25097. };
  25098. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  25099. /** @hidden */
  25100. get: function () {
  25101. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25102. return null;
  25103. },
  25104. enumerable: true,
  25105. configurable: true
  25106. });
  25107. /** @hidden */
  25108. Scene.prototype.getParticlesDuration = function () {
  25109. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  25110. return 0;
  25111. };
  25112. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  25113. /** @hidden */
  25114. get: function () {
  25115. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25116. return null;
  25117. },
  25118. enumerable: true,
  25119. configurable: true
  25120. });
  25121. /** @hidden */
  25122. Scene.prototype.getSpritesDuration = function () {
  25123. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  25124. return 0;
  25125. };
  25126. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  25127. /** @hidden */
  25128. get: function () {
  25129. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  25130. return null;
  25131. },
  25132. enumerable: true,
  25133. configurable: true
  25134. });
  25135. /**
  25136. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  25137. * @returns a number
  25138. */
  25139. Scene.prototype.getAnimationRatio = function () {
  25140. return this._animationRatio !== undefined ? this._animationRatio : 1;
  25141. };
  25142. /**
  25143. * Gets an unique Id for the current render phase
  25144. * @returns a number
  25145. */
  25146. Scene.prototype.getRenderId = function () {
  25147. return this._renderId;
  25148. };
  25149. /**
  25150. * Gets an unique Id for the current frame
  25151. * @returns a number
  25152. */
  25153. Scene.prototype.getFrameId = function () {
  25154. return this._frameId;
  25155. };
  25156. /** Call this function if you want to manually increment the render Id*/
  25157. Scene.prototype.incrementRenderId = function () {
  25158. this._renderId++;
  25159. };
  25160. Scene.prototype._updatePointerPosition = function (evt) {
  25161. var canvasRect = this._engine.getRenderingCanvasClientRect();
  25162. if (!canvasRect) {
  25163. return;
  25164. }
  25165. this._pointerX = evt.clientX - canvasRect.left;
  25166. this._pointerY = evt.clientY - canvasRect.top;
  25167. this._unTranslatedPointerX = this._pointerX;
  25168. this._unTranslatedPointerY = this._pointerY;
  25169. };
  25170. Scene.prototype._createUbo = function () {
  25171. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25172. this._sceneUbo.addUniform("viewProjection", 16);
  25173. this._sceneUbo.addUniform("view", 16);
  25174. };
  25175. Scene.prototype._createAlternateUbo = function () {
  25176. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25177. this._alternateSceneUbo.addUniform("viewProjection", 16);
  25178. this._alternateSceneUbo.addUniform("view", 16);
  25179. };
  25180. // Pointers handling
  25181. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  25182. if (pointerInfo.pickInfo) {
  25183. if (!pointerInfo.pickInfo.ray) {
  25184. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  25185. }
  25186. }
  25187. };
  25188. /**
  25189. * Use this method to simulate a pointer move on a mesh
  25190. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25191. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25192. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25193. * @returns the current scene
  25194. */
  25195. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  25196. var evt = new PointerEvent("pointermove", pointerEventInit);
  25197. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  25198. return this;
  25199. }
  25200. return this._processPointerMove(pickResult, evt);
  25201. };
  25202. Scene.prototype._processPointerMove = function (pickResult, evt) {
  25203. var canvas = this._engine.getRenderingCanvas();
  25204. if (!canvas) {
  25205. return this;
  25206. }
  25207. // Restore pointer
  25208. canvas.style.cursor = this.defaultCursor;
  25209. var isMeshPicked = (pickResult && pickResult.hit && pickResult.pickedMesh) ? true : false;
  25210. if (isMeshPicked) {
  25211. this.setPointerOverMesh(pickResult.pickedMesh);
  25212. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  25213. if (this._pointerOverMesh.actionManager.hoverCursor) {
  25214. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  25215. }
  25216. else {
  25217. canvas.style.cursor = this.hoverCursor;
  25218. }
  25219. }
  25220. }
  25221. else {
  25222. this.setPointerOverMesh(null);
  25223. }
  25224. for (var _i = 0, _a = this._pointerMoveStage; _i < _a.length; _i++) {
  25225. var step = _a[_i];
  25226. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, isMeshPicked, canvas);
  25227. }
  25228. if (pickResult) {
  25229. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  25230. if (this.onPointerMove) {
  25231. this.onPointerMove(evt, pickResult, type);
  25232. }
  25233. if (this.onPointerObservable.hasObservers()) {
  25234. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25235. this._setRayOnPointerInfo(pi);
  25236. this.onPointerObservable.notifyObservers(pi, type);
  25237. }
  25238. }
  25239. return this;
  25240. };
  25241. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  25242. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  25243. if (pickResult) {
  25244. pi.ray = pickResult.ray;
  25245. }
  25246. this.onPrePointerObservable.notifyObservers(pi, type);
  25247. if (pi.skipOnPointerObservable) {
  25248. return true;
  25249. }
  25250. else {
  25251. return false;
  25252. }
  25253. };
  25254. /**
  25255. * Use this method to simulate a pointer down on a mesh
  25256. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25257. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25258. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25259. * @returns the current scene
  25260. */
  25261. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  25262. var evt = new PointerEvent("pointerdown", pointerEventInit);
  25263. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25264. return this;
  25265. }
  25266. return this._processPointerDown(pickResult, evt);
  25267. };
  25268. Scene.prototype._processPointerDown = function (pickResult, evt) {
  25269. var _this = this;
  25270. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25271. this._pickedDownMesh = pickResult.pickedMesh;
  25272. var actionManager = pickResult.pickedMesh.actionManager;
  25273. if (actionManager) {
  25274. if (actionManager.hasPickTriggers) {
  25275. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25276. switch (evt.button) {
  25277. case 0:
  25278. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25279. break;
  25280. case 1:
  25281. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25282. break;
  25283. case 2:
  25284. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25285. break;
  25286. }
  25287. }
  25288. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  25289. window.setTimeout(function () {
  25290. 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);
  25291. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  25292. if (_this._totalPointersPressed !== 0 &&
  25293. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  25294. !_this._isPointerSwiping()) {
  25295. _this._startingPointerTime = 0;
  25296. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25297. }
  25298. }
  25299. }, Scene.LongPressDelay);
  25300. }
  25301. }
  25302. }
  25303. else {
  25304. for (var _i = 0, _a = this._pointerDownStage; _i < _a.length; _i++) {
  25305. var step = _a[_i];
  25306. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
  25307. }
  25308. }
  25309. if (pickResult) {
  25310. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25311. if (this.onPointerDown) {
  25312. this.onPointerDown(evt, pickResult, type);
  25313. }
  25314. if (this.onPointerObservable.hasObservers()) {
  25315. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25316. this._setRayOnPointerInfo(pi);
  25317. this.onPointerObservable.notifyObservers(pi, type);
  25318. }
  25319. }
  25320. return this;
  25321. };
  25322. /**
  25323. * Use this method to simulate a pointer up on a mesh
  25324. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25325. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25326. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25327. * @returns the current scene
  25328. */
  25329. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  25330. var evt = new PointerEvent("pointerup", pointerEventInit);
  25331. var clickInfo = new ClickInfo();
  25332. clickInfo.singleClick = true;
  25333. clickInfo.ignore = true;
  25334. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25335. return this;
  25336. }
  25337. return this._processPointerUp(pickResult, evt, clickInfo);
  25338. };
  25339. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  25340. if (pickResult && pickResult && pickResult.pickedMesh) {
  25341. this._pickedUpMesh = pickResult.pickedMesh;
  25342. if (this._pickedDownMesh === this._pickedUpMesh) {
  25343. if (this.onPointerPick) {
  25344. this.onPointerPick(evt, pickResult);
  25345. }
  25346. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  25347. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  25348. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  25349. this._setRayOnPointerInfo(pi);
  25350. this.onPointerObservable.notifyObservers(pi, type_1);
  25351. }
  25352. }
  25353. if (pickResult.pickedMesh.actionManager) {
  25354. if (clickInfo.ignore) {
  25355. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25356. }
  25357. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  25358. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25359. }
  25360. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25361. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25362. }
  25363. }
  25364. }
  25365. else {
  25366. if (!clickInfo.ignore) {
  25367. for (var _i = 0, _a = this._pointerUpStage; _i < _a.length; _i++) {
  25368. var step = _a[_i];
  25369. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
  25370. }
  25371. }
  25372. }
  25373. if (this._pickedDownMesh &&
  25374. this._pickedDownMesh.actionManager &&
  25375. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  25376. this._pickedDownMesh !== this._pickedUpMesh) {
  25377. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  25378. }
  25379. var type = BABYLON.PointerEventTypes.POINTERUP;
  25380. if (this.onPointerObservable.hasObservers()) {
  25381. if (!clickInfo.ignore) {
  25382. if (!clickInfo.hasSwiped) {
  25383. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25384. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  25385. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  25386. this._setRayOnPointerInfo(pi);
  25387. this.onPointerObservable.notifyObservers(pi, type_2);
  25388. }
  25389. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25390. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25391. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  25392. this._setRayOnPointerInfo(pi);
  25393. this.onPointerObservable.notifyObservers(pi, type_3);
  25394. }
  25395. }
  25396. }
  25397. else {
  25398. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25399. this._setRayOnPointerInfo(pi);
  25400. this.onPointerObservable.notifyObservers(pi, type);
  25401. }
  25402. }
  25403. if (this.onPointerUp) {
  25404. this.onPointerUp(evt, pickResult, type);
  25405. }
  25406. return this;
  25407. };
  25408. /**
  25409. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  25410. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  25411. * @returns true if the pointer was captured
  25412. */
  25413. Scene.prototype.isPointerCaptured = function (pointerId) {
  25414. if (pointerId === void 0) { pointerId = 0; }
  25415. return this._pointerCaptures[pointerId];
  25416. };
  25417. /** @hidden */
  25418. Scene.prototype._isPointerSwiping = function () {
  25419. return Math.abs(this._startingPointerPosition.x - this._pointerX) > Scene.DragMovementThreshold ||
  25420. Math.abs(this._startingPointerPosition.y - this._pointerY) > Scene.DragMovementThreshold;
  25421. };
  25422. /**
  25423. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  25424. * @param attachUp defines if you want to attach events to pointerup
  25425. * @param attachDown defines if you want to attach events to pointerdown
  25426. * @param attachMove defines if you want to attach events to pointermove
  25427. */
  25428. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  25429. var _this = this;
  25430. if (attachUp === void 0) { attachUp = true; }
  25431. if (attachDown === void 0) { attachDown = true; }
  25432. if (attachMove === void 0) { attachMove = true; }
  25433. this._initActionManager = function (act, clickInfo) {
  25434. if (!_this._meshPickProceed) {
  25435. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25436. _this._currentPickResult = pickResult;
  25437. if (pickResult) {
  25438. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25439. }
  25440. _this._meshPickProceed = true;
  25441. }
  25442. return act;
  25443. };
  25444. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25445. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25446. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25447. btn !== _this._previousButtonPressed) {
  25448. _this._doubleClickOccured = false;
  25449. clickInfo.singleClick = true;
  25450. clickInfo.ignore = false;
  25451. cb(clickInfo, _this._currentPickResult);
  25452. }
  25453. };
  25454. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25455. var clickInfo = new ClickInfo();
  25456. _this._currentPickResult = null;
  25457. var act = null;
  25458. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25459. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25460. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25461. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25462. act = _this._initActionManager(act, clickInfo);
  25463. if (act)
  25464. checkPicking = act.hasPickTriggers;
  25465. }
  25466. if (checkPicking) {
  25467. var btn = evt.button;
  25468. clickInfo.hasSwiped = _this._isPointerSwiping();
  25469. if (!clickInfo.hasSwiped) {
  25470. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25471. if (!checkSingleClickImmediately) {
  25472. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25473. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25474. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25475. act = _this._initActionManager(act, clickInfo);
  25476. if (act)
  25477. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25478. }
  25479. }
  25480. if (checkSingleClickImmediately) {
  25481. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25482. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25483. btn !== _this._previousButtonPressed) {
  25484. clickInfo.singleClick = true;
  25485. cb(clickInfo, _this._currentPickResult);
  25486. }
  25487. }
  25488. // at least one double click is required to be check and exclusive double click is enabled
  25489. else {
  25490. // wait that no double click has been raised during the double click delay
  25491. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25492. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25493. }
  25494. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25495. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25496. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25497. act = _this._initActionManager(act, clickInfo);
  25498. if (act)
  25499. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25500. }
  25501. if (checkDoubleClick) {
  25502. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25503. if (btn === _this._previousButtonPressed &&
  25504. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25505. !_this._doubleClickOccured) {
  25506. // pointer has not moved for 2 clicks, it's a double click
  25507. if (!clickInfo.hasSwiped &&
  25508. !_this._isPointerSwiping()) {
  25509. _this._previousStartingPointerTime = 0;
  25510. _this._doubleClickOccured = true;
  25511. clickInfo.doubleClick = true;
  25512. clickInfo.ignore = false;
  25513. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25514. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25515. }
  25516. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25517. cb(clickInfo, _this._currentPickResult);
  25518. }
  25519. // if the two successive clicks are too far, it's just two simple clicks
  25520. else {
  25521. _this._doubleClickOccured = false;
  25522. _this._previousStartingPointerTime = _this._startingPointerTime;
  25523. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25524. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25525. _this._previousButtonPressed = btn;
  25526. if (Scene.ExclusiveDoubleClickMode) {
  25527. if (_this._previousDelayedSimpleClickTimeout) {
  25528. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25529. }
  25530. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25531. cb(clickInfo, _this._previousPickResult);
  25532. }
  25533. else {
  25534. cb(clickInfo, _this._currentPickResult);
  25535. }
  25536. }
  25537. }
  25538. // just the first click of the double has been raised
  25539. else {
  25540. _this._doubleClickOccured = false;
  25541. _this._previousStartingPointerTime = _this._startingPointerTime;
  25542. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25543. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25544. _this._previousButtonPressed = btn;
  25545. }
  25546. }
  25547. }
  25548. }
  25549. clickInfo.ignore = true;
  25550. cb(clickInfo, _this._currentPickResult);
  25551. };
  25552. this._onPointerMove = function (evt) {
  25553. _this._updatePointerPosition(evt);
  25554. // PreObservable support
  25555. if (_this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  25556. return;
  25557. }
  25558. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25559. return;
  25560. }
  25561. if (!_this.pointerMovePredicate) {
  25562. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25563. }
  25564. // Meshes
  25565. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25566. _this._processPointerMove(pickResult, evt);
  25567. };
  25568. this._onPointerDown = function (evt) {
  25569. _this._totalPointersPressed++;
  25570. _this._pickedDownMesh = null;
  25571. _this._meshPickProceed = false;
  25572. _this._updatePointerPosition(evt);
  25573. if (_this.preventDefaultOnPointerDown && canvas) {
  25574. evt.preventDefault();
  25575. canvas.focus();
  25576. }
  25577. // PreObservable support
  25578. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25579. return;
  25580. }
  25581. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25582. return;
  25583. }
  25584. _this._pointerCaptures[evt.pointerId] = true;
  25585. _this._startingPointerPosition.x = _this._pointerX;
  25586. _this._startingPointerPosition.y = _this._pointerY;
  25587. _this._startingPointerTime = Date.now();
  25588. if (!_this.pointerDownPredicate) {
  25589. _this.pointerDownPredicate = function (mesh) {
  25590. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25591. };
  25592. }
  25593. // Meshes
  25594. _this._pickedDownMesh = null;
  25595. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25596. _this._processPointerDown(pickResult, evt);
  25597. };
  25598. this._onPointerUp = function (evt) {
  25599. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25600. return; // So we need to test it the pointer down was pressed before.
  25601. }
  25602. _this._totalPointersPressed--;
  25603. _this._pickedUpMesh = null;
  25604. _this._meshPickProceed = false;
  25605. _this._updatePointerPosition(evt);
  25606. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25607. // PreObservable support
  25608. if (_this.onPrePointerObservable.hasObservers()) {
  25609. if (!clickInfo.ignore) {
  25610. if (!clickInfo.hasSwiped) {
  25611. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25612. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  25613. return;
  25614. }
  25615. }
  25616. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25617. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25618. return;
  25619. }
  25620. }
  25621. }
  25622. }
  25623. else {
  25624. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25625. return;
  25626. }
  25627. }
  25628. }
  25629. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25630. return;
  25631. }
  25632. _this._pointerCaptures[evt.pointerId] = false;
  25633. if (!_this.pointerUpPredicate) {
  25634. _this.pointerUpPredicate = function (mesh) {
  25635. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25636. };
  25637. }
  25638. // Meshes
  25639. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25640. _this._initActionManager(null, clickInfo);
  25641. }
  25642. if (!pickResult) {
  25643. pickResult = _this._currentPickResult;
  25644. }
  25645. _this._processPointerUp(pickResult, evt, clickInfo);
  25646. _this._previousPickResult = _this._currentPickResult;
  25647. });
  25648. };
  25649. this._onKeyDown = function (evt) {
  25650. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  25651. if (_this.onPreKeyboardObservable.hasObservers()) {
  25652. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25653. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25654. if (pi.skipOnPointerObservable) {
  25655. return;
  25656. }
  25657. }
  25658. if (_this.onKeyboardObservable.hasObservers()) {
  25659. var pi = new BABYLON.KeyboardInfo(type, evt);
  25660. _this.onKeyboardObservable.notifyObservers(pi, type);
  25661. }
  25662. if (_this.actionManager) {
  25663. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25664. }
  25665. };
  25666. this._onKeyUp = function (evt) {
  25667. var type = BABYLON.KeyboardEventTypes.KEYUP;
  25668. if (_this.onPreKeyboardObservable.hasObservers()) {
  25669. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25670. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25671. if (pi.skipOnPointerObservable) {
  25672. return;
  25673. }
  25674. }
  25675. if (_this.onKeyboardObservable.hasObservers()) {
  25676. var pi = new BABYLON.KeyboardInfo(type, evt);
  25677. _this.onKeyboardObservable.notifyObservers(pi, type);
  25678. }
  25679. if (_this.actionManager) {
  25680. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25681. }
  25682. };
  25683. var engine = this.getEngine();
  25684. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25685. if (!canvas) {
  25686. return;
  25687. }
  25688. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25689. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25690. });
  25691. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25692. if (!canvas) {
  25693. return;
  25694. }
  25695. canvas.removeEventListener("keydown", _this._onKeyDown);
  25696. canvas.removeEventListener("keyup", _this._onKeyUp);
  25697. });
  25698. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25699. var canvas = this._engine.getRenderingCanvas();
  25700. if (!canvas) {
  25701. return;
  25702. }
  25703. if (attachMove) {
  25704. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25705. // Wheel
  25706. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25707. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25708. }
  25709. if (attachDown) {
  25710. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25711. }
  25712. if (attachUp) {
  25713. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25714. }
  25715. canvas.tabIndex = 1;
  25716. };
  25717. /** Detaches all event handlers*/
  25718. Scene.prototype.detachControl = function () {
  25719. var engine = this.getEngine();
  25720. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25721. var canvas = engine.getRenderingCanvas();
  25722. if (!canvas) {
  25723. return;
  25724. }
  25725. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25726. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25727. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25728. if (this._onCanvasBlurObserver) {
  25729. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25730. }
  25731. if (this._onCanvasFocusObserver) {
  25732. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  25733. }
  25734. // Wheel
  25735. canvas.removeEventListener('mousewheel', this._onPointerMove);
  25736. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  25737. // Keyboard
  25738. canvas.removeEventListener("keydown", this._onKeyDown);
  25739. canvas.removeEventListener("keyup", this._onKeyUp);
  25740. // Observables
  25741. this.onKeyboardObservable.clear();
  25742. this.onPreKeyboardObservable.clear();
  25743. this.onPointerObservable.clear();
  25744. this.onPrePointerObservable.clear();
  25745. };
  25746. /**
  25747. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  25748. * Delay loaded resources are not taking in account
  25749. * @return true if all required resources are ready
  25750. */
  25751. Scene.prototype.isReady = function () {
  25752. if (this._isDisposed) {
  25753. return false;
  25754. }
  25755. if (this._pendingData.length > 0) {
  25756. return false;
  25757. }
  25758. var index;
  25759. var engine = this.getEngine();
  25760. // Geometries
  25761. for (index = 0; index < this.geometries.length; index++) {
  25762. var geometry = this.geometries[index];
  25763. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25764. return false;
  25765. }
  25766. }
  25767. // Meshes
  25768. for (index = 0; index < this.meshes.length; index++) {
  25769. var mesh = this.meshes[index];
  25770. if (!mesh.isEnabled()) {
  25771. continue;
  25772. }
  25773. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25774. continue;
  25775. }
  25776. if (!mesh.isReady(true)) {
  25777. return false;
  25778. }
  25779. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  25780. // Is Ready For Mesh
  25781. for (var _i = 0, _a = this._isReadyForMeshStage; _i < _a.length; _i++) {
  25782. var step = _a[_i];
  25783. if (!step.action(mesh, hardwareInstancedRendering)) {
  25784. return false;
  25785. }
  25786. }
  25787. }
  25788. // Post-processes
  25789. if (this.activeCameras && this.activeCameras.length > 0) {
  25790. for (var _b = 0, _c = this.activeCameras; _b < _c.length; _b++) {
  25791. var camera = _c[_b];
  25792. if (!camera.isReady(true)) {
  25793. return false;
  25794. }
  25795. }
  25796. }
  25797. else if (this.activeCamera) {
  25798. if (!this.activeCamera.isReady(true)) {
  25799. return false;
  25800. }
  25801. }
  25802. // Particles
  25803. for (var _d = 0, _e = this.particleSystems; _d < _e.length; _d++) {
  25804. var particleSystem = _e[_d];
  25805. if (!particleSystem.isReady()) {
  25806. return false;
  25807. }
  25808. }
  25809. return true;
  25810. };
  25811. /** Resets all cached information relative to material (including effect and visibility) */
  25812. Scene.prototype.resetCachedMaterial = function () {
  25813. this._cachedMaterial = null;
  25814. this._cachedEffect = null;
  25815. this._cachedVisibility = null;
  25816. };
  25817. /**
  25818. * Registers a function to be called before every frame render
  25819. * @param func defines the function to register
  25820. */
  25821. Scene.prototype.registerBeforeRender = function (func) {
  25822. this.onBeforeRenderObservable.add(func);
  25823. };
  25824. /**
  25825. * Unregisters a function called before every frame render
  25826. * @param func defines the function to unregister
  25827. */
  25828. Scene.prototype.unregisterBeforeRender = function (func) {
  25829. this.onBeforeRenderObservable.removeCallback(func);
  25830. };
  25831. /**
  25832. * Registers a function to be called after every frame render
  25833. * @param func defines the function to register
  25834. */
  25835. Scene.prototype.registerAfterRender = function (func) {
  25836. this.onAfterRenderObservable.add(func);
  25837. };
  25838. /**
  25839. * Unregisters a function called after every frame render
  25840. * @param func defines the function to unregister
  25841. */
  25842. Scene.prototype.unregisterAfterRender = function (func) {
  25843. this.onAfterRenderObservable.removeCallback(func);
  25844. };
  25845. Scene.prototype._executeOnceBeforeRender = function (func) {
  25846. var _this = this;
  25847. var execFunc = function () {
  25848. func();
  25849. setTimeout(function () {
  25850. _this.unregisterBeforeRender(execFunc);
  25851. });
  25852. };
  25853. this.registerBeforeRender(execFunc);
  25854. };
  25855. /**
  25856. * The provided function will run before render once and will be disposed afterwards.
  25857. * A timeout delay can be provided so that the function will be executed in N ms.
  25858. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  25859. * @param func The function to be executed.
  25860. * @param timeout optional delay in ms
  25861. */
  25862. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  25863. var _this = this;
  25864. if (timeout !== undefined) {
  25865. setTimeout(function () {
  25866. _this._executeOnceBeforeRender(func);
  25867. }, timeout);
  25868. }
  25869. else {
  25870. this._executeOnceBeforeRender(func);
  25871. }
  25872. };
  25873. /** @hidden */
  25874. Scene.prototype._addPendingData = function (data) {
  25875. this._pendingData.push(data);
  25876. };
  25877. /** @hidden */
  25878. Scene.prototype._removePendingData = function (data) {
  25879. var wasLoading = this.isLoading;
  25880. var index = this._pendingData.indexOf(data);
  25881. if (index !== -1) {
  25882. this._pendingData.splice(index, 1);
  25883. }
  25884. if (wasLoading && !this.isLoading) {
  25885. this.onDataLoadedObservable.notifyObservers(this);
  25886. }
  25887. };
  25888. /**
  25889. * Returns the number of items waiting to be loaded
  25890. * @returns the number of items waiting to be loaded
  25891. */
  25892. Scene.prototype.getWaitingItemsCount = function () {
  25893. return this._pendingData.length;
  25894. };
  25895. Object.defineProperty(Scene.prototype, "isLoading", {
  25896. /**
  25897. * Returns a boolean indicating if the scene is still loading data
  25898. */
  25899. get: function () {
  25900. return this._pendingData.length > 0;
  25901. },
  25902. enumerable: true,
  25903. configurable: true
  25904. });
  25905. /**
  25906. * Registers a function to be executed when the scene is ready
  25907. * @param {Function} func - the function to be executed
  25908. */
  25909. Scene.prototype.executeWhenReady = function (func) {
  25910. var _this = this;
  25911. this.onReadyObservable.add(func);
  25912. if (this._executeWhenReadyTimeoutId !== -1) {
  25913. return;
  25914. }
  25915. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25916. _this._checkIsReady();
  25917. }, 150);
  25918. };
  25919. /**
  25920. * Returns a promise that resolves when the scene is ready
  25921. * @returns A promise that resolves when the scene is ready
  25922. */
  25923. Scene.prototype.whenReadyAsync = function () {
  25924. var _this = this;
  25925. return new Promise(function (resolve) {
  25926. _this.executeWhenReady(function () {
  25927. resolve();
  25928. });
  25929. });
  25930. };
  25931. /** @hidden */
  25932. Scene.prototype._checkIsReady = function () {
  25933. var _this = this;
  25934. this._registerTransientComponents();
  25935. if (this.isReady()) {
  25936. this.onReadyObservable.notifyObservers(this);
  25937. this.onReadyObservable.clear();
  25938. this._executeWhenReadyTimeoutId = -1;
  25939. return;
  25940. }
  25941. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25942. _this._checkIsReady();
  25943. }, 150);
  25944. };
  25945. // Animations
  25946. /**
  25947. * Will start the animation sequence of a given target
  25948. * @param target defines the target
  25949. * @param from defines from which frame should animation start
  25950. * @param to defines until which frame should animation run.
  25951. * @param weight defines the weight to apply to the animation (1.0 by default)
  25952. * @param loop defines if the animation loops
  25953. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25954. * @param onAnimationEnd defines the function to be executed when the animation ends
  25955. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25956. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  25957. * @returns the animatable object created for this animation
  25958. */
  25959. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable, targetMask) {
  25960. if (weight === void 0) { weight = 1.0; }
  25961. if (speedRatio === void 0) { speedRatio = 1.0; }
  25962. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false, targetMask);
  25963. returnedAnimatable.weight = weight;
  25964. return returnedAnimatable;
  25965. };
  25966. /**
  25967. * Will start the animation sequence of a given target
  25968. * @param target defines the target
  25969. * @param from defines from which frame should animation start
  25970. * @param to defines until which frame should animation run.
  25971. * @param loop defines if the animation loops
  25972. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25973. * @param onAnimationEnd defines the function to be executed when the animation ends
  25974. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25975. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  25976. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  25977. * @returns the animatable object created for this animation
  25978. */
  25979. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask) {
  25980. if (speedRatio === void 0) { speedRatio = 1.0; }
  25981. if (stopCurrent === void 0) { stopCurrent = true; }
  25982. if (from > to && speedRatio > 0) {
  25983. speedRatio *= -1;
  25984. }
  25985. if (stopCurrent) {
  25986. this.stopAnimation(target, undefined, targetMask);
  25987. }
  25988. if (!animatable) {
  25989. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  25990. }
  25991. var shouldRunTargetAnimations = targetMask ? targetMask(target) : true;
  25992. // Local animations
  25993. if (target.animations && shouldRunTargetAnimations) {
  25994. animatable.appendAnimations(target, target.animations);
  25995. }
  25996. // Children animations
  25997. if (target.getAnimatables) {
  25998. var animatables = target.getAnimatables();
  25999. for (var index = 0; index < animatables.length; index++) {
  26000. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask);
  26001. }
  26002. }
  26003. animatable.reset();
  26004. return animatable;
  26005. };
  26006. /**
  26007. * Begin a new animation on a given node
  26008. * @param target defines the target where the animation will take place
  26009. * @param animations defines the list of animations to start
  26010. * @param from defines the initial value
  26011. * @param to defines the final value
  26012. * @param loop defines if you want animation to loop (off by default)
  26013. * @param speedRatio defines the speed ratio to apply to all animations
  26014. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26015. * @returns the list of created animatables
  26016. */
  26017. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26018. if (speedRatio === undefined) {
  26019. speedRatio = 1.0;
  26020. }
  26021. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  26022. return animatable;
  26023. };
  26024. /**
  26025. * Begin a new animation on a given node and its hierarchy
  26026. * @param target defines the root node where the animation will take place
  26027. * @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.
  26028. * @param animations defines the list of animations to start
  26029. * @param from defines the initial value
  26030. * @param to defines the final value
  26031. * @param loop defines if you want animation to loop (off by default)
  26032. * @param speedRatio defines the speed ratio to apply to all animations
  26033. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26034. * @returns the list of animatables created for all nodes
  26035. */
  26036. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26037. var children = target.getDescendants(directDescendantsOnly);
  26038. var result = [];
  26039. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  26040. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  26041. var child = children_1[_i];
  26042. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  26043. }
  26044. return result;
  26045. };
  26046. /**
  26047. * Gets the animatable associated with a specific target
  26048. * @param target defines the target of the animatable
  26049. * @returns the required animatable if found
  26050. */
  26051. Scene.prototype.getAnimatableByTarget = function (target) {
  26052. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26053. if (this._activeAnimatables[index].target === target) {
  26054. return this._activeAnimatables[index];
  26055. }
  26056. }
  26057. return null;
  26058. };
  26059. /**
  26060. * Gets all animatables associated with a given target
  26061. * @param target defines the target to look animatables for
  26062. * @returns an array of Animatables
  26063. */
  26064. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  26065. var result = [];
  26066. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26067. if (this._activeAnimatables[index].target === target) {
  26068. result.push(this._activeAnimatables[index]);
  26069. }
  26070. }
  26071. return result;
  26072. };
  26073. Object.defineProperty(Scene.prototype, "animatables", {
  26074. /**
  26075. * Gets all animatable attached to the scene
  26076. */
  26077. get: function () {
  26078. return this._activeAnimatables;
  26079. },
  26080. enumerable: true,
  26081. configurable: true
  26082. });
  26083. /**
  26084. * Will stop the animation of the given target
  26085. * @param target - the target
  26086. * @param animationName - the name of the animation to stop (all animations will be stopped if both this and targetMask are empty)
  26087. * @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)
  26088. */
  26089. Scene.prototype.stopAnimation = function (target, animationName, targetMask) {
  26090. var animatables = this.getAllAnimatablesByTarget(target);
  26091. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  26092. var animatable = animatables_1[_i];
  26093. animatable.stop(animationName, targetMask);
  26094. }
  26095. };
  26096. /**
  26097. * Stops and removes all animations that have been applied to the scene
  26098. */
  26099. Scene.prototype.stopAllAnimations = function () {
  26100. if (this._activeAnimatables) {
  26101. for (var i = 0; i < this._activeAnimatables.length; i++) {
  26102. this._activeAnimatables[i].stop();
  26103. }
  26104. this._activeAnimatables = [];
  26105. }
  26106. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  26107. var group = _a[_i];
  26108. group.stop();
  26109. }
  26110. };
  26111. Scene.prototype._animate = function () {
  26112. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  26113. return;
  26114. }
  26115. // Getting time
  26116. var now = BABYLON.Tools.Now;
  26117. if (!this._animationTimeLast) {
  26118. if (this._pendingData.length > 0) {
  26119. return;
  26120. }
  26121. this._animationTimeLast = now;
  26122. }
  26123. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  26124. this._animationTime += deltaTime;
  26125. this._animationTimeLast = now;
  26126. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26127. this._activeAnimatables[index]._animate(this._animationTime);
  26128. }
  26129. // Late animation bindings
  26130. this._processLateAnimationBindings();
  26131. };
  26132. /** @hidden */
  26133. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  26134. var target = runtimeAnimation.target;
  26135. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  26136. if (!target._lateAnimationHolders) {
  26137. target._lateAnimationHolders = {};
  26138. }
  26139. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  26140. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  26141. totalWeight: 0,
  26142. animations: [],
  26143. originalValue: originalValue
  26144. };
  26145. }
  26146. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  26147. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  26148. };
  26149. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  26150. var normalizer = 1.0;
  26151. var finalPosition = BABYLON.Tmp.Vector3[0];
  26152. var finalScaling = BABYLON.Tmp.Vector3[1];
  26153. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  26154. var startIndex = 0;
  26155. var originalAnimation = holder.animations[0];
  26156. var originalValue = holder.originalValue;
  26157. var scale = 1;
  26158. if (holder.totalWeight < 1.0) {
  26159. // We need to mix the original value in
  26160. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26161. scale = 1.0 - holder.totalWeight;
  26162. }
  26163. else {
  26164. startIndex = 1;
  26165. // We need to normalize the weights
  26166. normalizer = holder.totalWeight;
  26167. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26168. scale = originalAnimation.weight / normalizer;
  26169. if (scale == 1) {
  26170. return originalAnimation.currentValue;
  26171. }
  26172. }
  26173. finalScaling.scaleInPlace(scale);
  26174. finalPosition.scaleInPlace(scale);
  26175. finalQuaternion.scaleInPlace(scale);
  26176. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26177. var runtimeAnimation = holder.animations[animIndex];
  26178. var scale = runtimeAnimation.weight / normalizer;
  26179. var currentPosition = BABYLON.Tmp.Vector3[2];
  26180. var currentScaling = BABYLON.Tmp.Vector3[3];
  26181. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  26182. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  26183. currentScaling.scaleAndAddToRef(scale, finalScaling);
  26184. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  26185. currentPosition.scaleAndAddToRef(scale, finalPosition);
  26186. }
  26187. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  26188. return originalAnimation._workValue;
  26189. };
  26190. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder, refQuaternion) {
  26191. var originalAnimation = holder.animations[0];
  26192. var originalValue = holder.originalValue;
  26193. if (holder.animations.length === 1) {
  26194. BABYLON.Quaternion.SlerpToRef(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight), refQuaternion);
  26195. return refQuaternion;
  26196. }
  26197. var normalizer = 1.0;
  26198. var quaternions;
  26199. var weights;
  26200. if (holder.totalWeight < 1.0) {
  26201. var scale = 1.0 - holder.totalWeight;
  26202. quaternions = [];
  26203. weights = [];
  26204. quaternions.push(originalValue);
  26205. weights.push(scale);
  26206. }
  26207. else {
  26208. if (holder.animations.length === 2) { // Slerp as soon as we can
  26209. BABYLON.Quaternion.SlerpToRef(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight, refQuaternion);
  26210. return refQuaternion;
  26211. }
  26212. quaternions = [];
  26213. weights = [];
  26214. normalizer = holder.totalWeight;
  26215. }
  26216. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  26217. var runtimeAnimation = holder.animations[animIndex];
  26218. quaternions.push(runtimeAnimation.currentValue);
  26219. weights.push(runtimeAnimation.weight / normalizer);
  26220. }
  26221. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  26222. var cumulativeAmount = 0;
  26223. var cumulativeQuaternion = null;
  26224. for (var index = 0; index < quaternions.length;) {
  26225. if (!cumulativeQuaternion) {
  26226. BABYLON.Quaternion.SlerpToRef(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]), refQuaternion);
  26227. cumulativeQuaternion = refQuaternion;
  26228. cumulativeAmount = weights[index] + weights[index + 1];
  26229. index += 2;
  26230. continue;
  26231. }
  26232. cumulativeAmount += weights[index];
  26233. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  26234. index++;
  26235. }
  26236. return cumulativeQuaternion;
  26237. };
  26238. Scene.prototype._processLateAnimationBindings = function () {
  26239. if (!this._registeredForLateAnimationBindings.length) {
  26240. return;
  26241. }
  26242. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  26243. var target = this._registeredForLateAnimationBindings.data[index];
  26244. for (var path in target._lateAnimationHolders) {
  26245. var holder = target._lateAnimationHolders[path];
  26246. var originalAnimation = holder.animations[0];
  26247. var originalValue = holder.originalValue;
  26248. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  26249. var finalValue = target[path];
  26250. if (matrixDecomposeMode) {
  26251. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  26252. }
  26253. else {
  26254. var quaternionMode = originalValue.w !== undefined;
  26255. if (quaternionMode) {
  26256. finalValue = this._processLateAnimationBindingsForQuaternions(holder, finalValue || BABYLON.Quaternion.Identity());
  26257. }
  26258. else {
  26259. var startIndex = 0;
  26260. var normalizer = 1.0;
  26261. if (holder.totalWeight < 1.0) {
  26262. // We need to mix the original value in
  26263. if (originalValue.scale) {
  26264. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  26265. }
  26266. else {
  26267. finalValue = originalValue * (1.0 - holder.totalWeight);
  26268. }
  26269. }
  26270. else {
  26271. // We need to normalize the weights
  26272. normalizer = holder.totalWeight;
  26273. var scale_1 = originalAnimation.weight / normalizer;
  26274. if (scale_1 !== 1) {
  26275. if (originalAnimation.currentValue.scale) {
  26276. finalValue = originalAnimation.currentValue.scale(scale_1);
  26277. }
  26278. else {
  26279. finalValue = originalAnimation.currentValue * scale_1;
  26280. }
  26281. }
  26282. else {
  26283. finalValue = originalAnimation.currentValue;
  26284. }
  26285. startIndex = 1;
  26286. }
  26287. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26288. var runtimeAnimation = holder.animations[animIndex];
  26289. var scale = runtimeAnimation.weight / normalizer;
  26290. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  26291. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  26292. }
  26293. else {
  26294. finalValue += runtimeAnimation.currentValue * scale;
  26295. }
  26296. }
  26297. }
  26298. }
  26299. target[path] = finalValue;
  26300. }
  26301. target._lateAnimationHolders = {};
  26302. }
  26303. this._registeredForLateAnimationBindings.reset();
  26304. };
  26305. // Matrix
  26306. /** @hidden */
  26307. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  26308. this._useAlternateCameraConfiguration = active;
  26309. };
  26310. /**
  26311. * Gets the current view matrix
  26312. * @returns a Matrix
  26313. */
  26314. Scene.prototype.getViewMatrix = function () {
  26315. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  26316. };
  26317. /**
  26318. * Gets the current projection matrix
  26319. * @returns a Matrix
  26320. */
  26321. Scene.prototype.getProjectionMatrix = function () {
  26322. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  26323. };
  26324. /**
  26325. * Gets the current transform matrix
  26326. * @returns a Matrix made of View * Projection
  26327. */
  26328. Scene.prototype.getTransformMatrix = function () {
  26329. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  26330. };
  26331. /**
  26332. * Sets the current transform matrix
  26333. * @param view defines the View matrix to use
  26334. * @param projection defines the Projection matrix to use
  26335. */
  26336. Scene.prototype.setTransformMatrix = function (view, projection) {
  26337. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  26338. return;
  26339. }
  26340. this._viewUpdateFlag = view.updateFlag;
  26341. this._projectionUpdateFlag = projection.updateFlag;
  26342. this._viewMatrix = view;
  26343. this._projectionMatrix = projection;
  26344. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  26345. // Update frustum
  26346. if (!this._frustumPlanes) {
  26347. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  26348. }
  26349. else {
  26350. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  26351. }
  26352. if (this.activeCamera && this.activeCamera._alternateCamera) {
  26353. var otherCamera = this.activeCamera._alternateCamera;
  26354. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  26355. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  26356. }
  26357. if (this._sceneUbo.useUbo) {
  26358. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  26359. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  26360. this._sceneUbo.update();
  26361. }
  26362. };
  26363. /** @hidden */
  26364. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  26365. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  26366. return;
  26367. }
  26368. this._alternateViewUpdateFlag = view.updateFlag;
  26369. this._alternateProjectionUpdateFlag = projection.updateFlag;
  26370. this._alternateViewMatrix = view;
  26371. this._alternateProjectionMatrix = projection;
  26372. if (!this._alternateTransformMatrix) {
  26373. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  26374. }
  26375. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  26376. if (!this._alternateSceneUbo) {
  26377. this._createAlternateUbo();
  26378. }
  26379. if (this._alternateSceneUbo.useUbo) {
  26380. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  26381. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  26382. this._alternateSceneUbo.update();
  26383. }
  26384. };
  26385. /**
  26386. * Gets the uniform buffer used to store scene data
  26387. * @returns a UniformBuffer
  26388. */
  26389. Scene.prototype.getSceneUniformBuffer = function () {
  26390. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  26391. };
  26392. /**
  26393. * Gets an unique (relatively to the current scene) Id
  26394. * @returns an unique number for the scene
  26395. */
  26396. Scene.prototype.getUniqueId = function () {
  26397. var result = Scene._uniqueIdCounter;
  26398. Scene._uniqueIdCounter++;
  26399. return result;
  26400. };
  26401. /**
  26402. * Add a mesh to the list of scene's meshes
  26403. * @param newMesh defines the mesh to add
  26404. * @param recursive if all child meshes should also be added to the scene
  26405. */
  26406. Scene.prototype.addMesh = function (newMesh, recursive) {
  26407. var _this = this;
  26408. if (recursive === void 0) { recursive = false; }
  26409. this.meshes.push(newMesh);
  26410. //notify the collision coordinator
  26411. if (this.collisionCoordinator) {
  26412. this.collisionCoordinator.onMeshAdded(newMesh);
  26413. }
  26414. newMesh._resyncLightSources();
  26415. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26416. if (recursive) {
  26417. newMesh.getChildMeshes().forEach(function (m) {
  26418. _this.addMesh(m);
  26419. });
  26420. }
  26421. };
  26422. /**
  26423. * Remove a mesh for the list of scene's meshes
  26424. * @param toRemove defines the mesh to remove
  26425. * @param recursive if all child meshes should also be removed from the scene
  26426. * @returns the index where the mesh was in the mesh list
  26427. */
  26428. Scene.prototype.removeMesh = function (toRemove, recursive) {
  26429. var _this = this;
  26430. if (recursive === void 0) { recursive = false; }
  26431. var index = this.meshes.indexOf(toRemove);
  26432. if (index !== -1) {
  26433. // Remove from the scene if mesh found
  26434. this.meshes.splice(index, 1);
  26435. }
  26436. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26437. if (recursive) {
  26438. toRemove.getChildMeshes().forEach(function (m) {
  26439. _this.removeMesh(m);
  26440. });
  26441. }
  26442. return index;
  26443. };
  26444. /**
  26445. * Add a transform node to the list of scene's transform nodes
  26446. * @param newTransformNode defines the transform node to add
  26447. */
  26448. Scene.prototype.addTransformNode = function (newTransformNode) {
  26449. this.transformNodes.push(newTransformNode);
  26450. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26451. };
  26452. /**
  26453. * Remove a transform node for the list of scene's transform nodes
  26454. * @param toRemove defines the transform node to remove
  26455. * @returns the index where the transform node was in the transform node list
  26456. */
  26457. Scene.prototype.removeTransformNode = function (toRemove) {
  26458. var index = this.transformNodes.indexOf(toRemove);
  26459. if (index !== -1) {
  26460. // Remove from the scene if found
  26461. this.transformNodes.splice(index, 1);
  26462. }
  26463. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26464. return index;
  26465. };
  26466. /**
  26467. * Remove a skeleton for the list of scene's skeletons
  26468. * @param toRemove defines the skeleton to remove
  26469. * @returns the index where the skeleton was in the skeleton list
  26470. */
  26471. Scene.prototype.removeSkeleton = function (toRemove) {
  26472. var index = this.skeletons.indexOf(toRemove);
  26473. if (index !== -1) {
  26474. // Remove from the scene if found
  26475. this.skeletons.splice(index, 1);
  26476. }
  26477. return index;
  26478. };
  26479. /**
  26480. * Remove a morph target for the list of scene's morph targets
  26481. * @param toRemove defines the morph target to remove
  26482. * @returns the index where the morph target was in the morph target list
  26483. */
  26484. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26485. var index = this.morphTargetManagers.indexOf(toRemove);
  26486. if (index !== -1) {
  26487. // Remove from the scene if found
  26488. this.morphTargetManagers.splice(index, 1);
  26489. }
  26490. return index;
  26491. };
  26492. /**
  26493. * Remove a light for the list of scene's lights
  26494. * @param toRemove defines the light to remove
  26495. * @returns the index where the light was in the light list
  26496. */
  26497. Scene.prototype.removeLight = function (toRemove) {
  26498. var index = this.lights.indexOf(toRemove);
  26499. if (index !== -1) {
  26500. // Remove from meshes
  26501. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26502. var mesh = _a[_i];
  26503. mesh._removeLightSource(toRemove);
  26504. }
  26505. // Remove from the scene if mesh found
  26506. this.lights.splice(index, 1);
  26507. this.sortLightsByPriority();
  26508. }
  26509. this.onLightRemovedObservable.notifyObservers(toRemove);
  26510. return index;
  26511. };
  26512. /**
  26513. * Remove a camera for the list of scene's cameras
  26514. * @param toRemove defines the camera to remove
  26515. * @returns the index where the camera was in the camera list
  26516. */
  26517. Scene.prototype.removeCamera = function (toRemove) {
  26518. var index = this.cameras.indexOf(toRemove);
  26519. if (index !== -1) {
  26520. // Remove from the scene if mesh found
  26521. this.cameras.splice(index, 1);
  26522. }
  26523. // Remove from activeCameras
  26524. var index2 = this.activeCameras.indexOf(toRemove);
  26525. if (index2 !== -1) {
  26526. // Remove from the scene if mesh found
  26527. this.activeCameras.splice(index2, 1);
  26528. }
  26529. // Reset the activeCamera
  26530. if (this.activeCamera === toRemove) {
  26531. if (this.cameras.length > 0) {
  26532. this.activeCamera = this.cameras[0];
  26533. }
  26534. else {
  26535. this.activeCamera = null;
  26536. }
  26537. }
  26538. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26539. return index;
  26540. };
  26541. /**
  26542. * Remove a particle system for the list of scene's particle systems
  26543. * @param toRemove defines the particle system to remove
  26544. * @returns the index where the particle system was in the particle system list
  26545. */
  26546. Scene.prototype.removeParticleSystem = function (toRemove) {
  26547. var index = this.particleSystems.indexOf(toRemove);
  26548. if (index !== -1) {
  26549. this.particleSystems.splice(index, 1);
  26550. }
  26551. return index;
  26552. };
  26553. /**
  26554. * Remove a animation for the list of scene's animations
  26555. * @param toRemove defines the animation to remove
  26556. * @returns the index where the animation was in the animation list
  26557. */
  26558. Scene.prototype.removeAnimation = function (toRemove) {
  26559. var index = this.animations.indexOf(toRemove);
  26560. if (index !== -1) {
  26561. this.animations.splice(index, 1);
  26562. }
  26563. return index;
  26564. };
  26565. /**
  26566. * Removes the given animation group from this scene.
  26567. * @param toRemove The animation group to remove
  26568. * @returns The index of the removed animation group
  26569. */
  26570. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26571. var index = this.animationGroups.indexOf(toRemove);
  26572. if (index !== -1) {
  26573. this.animationGroups.splice(index, 1);
  26574. }
  26575. return index;
  26576. };
  26577. /**
  26578. * Removes the given multi-material from this scene.
  26579. * @param toRemove The multi-material to remove
  26580. * @returns The index of the removed multi-material
  26581. */
  26582. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26583. var index = this.multiMaterials.indexOf(toRemove);
  26584. if (index !== -1) {
  26585. this.multiMaterials.splice(index, 1);
  26586. }
  26587. return index;
  26588. };
  26589. /**
  26590. * Removes the given material from this scene.
  26591. * @param toRemove The material to remove
  26592. * @returns The index of the removed material
  26593. */
  26594. Scene.prototype.removeMaterial = function (toRemove) {
  26595. var index = this.materials.indexOf(toRemove);
  26596. if (index !== -1) {
  26597. this.materials.splice(index, 1);
  26598. }
  26599. return index;
  26600. };
  26601. /**
  26602. * Removes the given action manager from this scene.
  26603. * @param toRemove The action manager to remove
  26604. * @returns The index of the removed action manager
  26605. */
  26606. Scene.prototype.removeActionManager = function (toRemove) {
  26607. var index = this.actionManagers.indexOf(toRemove);
  26608. if (index !== -1) {
  26609. this.actionManagers.splice(index, 1);
  26610. }
  26611. return index;
  26612. };
  26613. /**
  26614. * Removes the given texture from this scene.
  26615. * @param toRemove The texture to remove
  26616. * @returns The index of the removed texture
  26617. */
  26618. Scene.prototype.removeTexture = function (toRemove) {
  26619. var index = this.textures.indexOf(toRemove);
  26620. if (index !== -1) {
  26621. this.textures.splice(index, 1);
  26622. }
  26623. return index;
  26624. };
  26625. /**
  26626. * Adds the given light to this scene
  26627. * @param newLight The light to add
  26628. */
  26629. Scene.prototype.addLight = function (newLight) {
  26630. this.lights.push(newLight);
  26631. this.sortLightsByPriority();
  26632. // Add light to all meshes (To support if the light is removed and then readded)
  26633. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26634. var mesh = _a[_i];
  26635. if (mesh._lightSources.indexOf(newLight) === -1) {
  26636. mesh._lightSources.push(newLight);
  26637. mesh._resyncLightSources();
  26638. }
  26639. }
  26640. this.onNewLightAddedObservable.notifyObservers(newLight);
  26641. };
  26642. /**
  26643. * Sorts the list list based on light priorities
  26644. */
  26645. Scene.prototype.sortLightsByPriority = function () {
  26646. if (this.requireLightSorting) {
  26647. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  26648. }
  26649. };
  26650. /**
  26651. * Adds the given camera to this scene
  26652. * @param newCamera The camera to add
  26653. */
  26654. Scene.prototype.addCamera = function (newCamera) {
  26655. this.cameras.push(newCamera);
  26656. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  26657. };
  26658. /**
  26659. * Adds the given skeleton to this scene
  26660. * @param newSkeleton The skeleton to add
  26661. */
  26662. Scene.prototype.addSkeleton = function (newSkeleton) {
  26663. this.skeletons.push(newSkeleton);
  26664. };
  26665. /**
  26666. * Adds the given particle system to this scene
  26667. * @param newParticleSystem The particle system to add
  26668. */
  26669. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  26670. this.particleSystems.push(newParticleSystem);
  26671. };
  26672. /**
  26673. * Adds the given animation to this scene
  26674. * @param newAnimation The animation to add
  26675. */
  26676. Scene.prototype.addAnimation = function (newAnimation) {
  26677. this.animations.push(newAnimation);
  26678. };
  26679. /**
  26680. * Adds the given animation group to this scene.
  26681. * @param newAnimationGroup The animation group to add
  26682. */
  26683. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  26684. this.animationGroups.push(newAnimationGroup);
  26685. };
  26686. /**
  26687. * Adds the given multi-material to this scene
  26688. * @param newMultiMaterial The multi-material to add
  26689. */
  26690. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  26691. this.multiMaterials.push(newMultiMaterial);
  26692. };
  26693. /**
  26694. * Adds the given material to this scene
  26695. * @param newMaterial The material to add
  26696. */
  26697. Scene.prototype.addMaterial = function (newMaterial) {
  26698. this.materials.push(newMaterial);
  26699. };
  26700. /**
  26701. * Adds the given morph target to this scene
  26702. * @param newMorphTargetManager The morph target to add
  26703. */
  26704. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  26705. this.morphTargetManagers.push(newMorphTargetManager);
  26706. };
  26707. /**
  26708. * Adds the given geometry to this scene
  26709. * @param newGeometry The geometry to add
  26710. */
  26711. Scene.prototype.addGeometry = function (newGeometry) {
  26712. this.geometries.push(newGeometry);
  26713. };
  26714. /**
  26715. * Adds the given action manager to this scene
  26716. * @param newActionManager The action manager to add
  26717. */
  26718. Scene.prototype.addActionManager = function (newActionManager) {
  26719. this.actionManagers.push(newActionManager);
  26720. };
  26721. /**
  26722. * Adds the given texture to this scene.
  26723. * @param newTexture The texture to add
  26724. */
  26725. Scene.prototype.addTexture = function (newTexture) {
  26726. this.textures.push(newTexture);
  26727. };
  26728. /**
  26729. * Switch active camera
  26730. * @param newCamera defines the new active camera
  26731. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  26732. */
  26733. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26734. if (attachControl === void 0) { attachControl = true; }
  26735. var canvas = this._engine.getRenderingCanvas();
  26736. if (!canvas) {
  26737. return;
  26738. }
  26739. if (this.activeCamera) {
  26740. this.activeCamera.detachControl(canvas);
  26741. }
  26742. this.activeCamera = newCamera;
  26743. if (attachControl) {
  26744. newCamera.attachControl(canvas);
  26745. }
  26746. };
  26747. /**
  26748. * sets the active camera of the scene using its ID
  26749. * @param id defines the camera's ID
  26750. * @return the new active camera or null if none found.
  26751. */
  26752. Scene.prototype.setActiveCameraByID = function (id) {
  26753. var camera = this.getCameraByID(id);
  26754. if (camera) {
  26755. this.activeCamera = camera;
  26756. return camera;
  26757. }
  26758. return null;
  26759. };
  26760. /**
  26761. * sets the active camera of the scene using its name
  26762. * @param name defines the camera's name
  26763. * @returns the new active camera or null if none found.
  26764. */
  26765. Scene.prototype.setActiveCameraByName = function (name) {
  26766. var camera = this.getCameraByName(name);
  26767. if (camera) {
  26768. this.activeCamera = camera;
  26769. return camera;
  26770. }
  26771. return null;
  26772. };
  26773. /**
  26774. * get an animation group using its name
  26775. * @param name defines the material's name
  26776. * @return the animation group or null if none found.
  26777. */
  26778. Scene.prototype.getAnimationGroupByName = function (name) {
  26779. for (var index = 0; index < this.animationGroups.length; index++) {
  26780. if (this.animationGroups[index].name === name) {
  26781. return this.animationGroups[index];
  26782. }
  26783. }
  26784. return null;
  26785. };
  26786. /**
  26787. * get a material using its id
  26788. * @param id defines the material's ID
  26789. * @return the material or null if none found.
  26790. */
  26791. Scene.prototype.getMaterialByID = function (id) {
  26792. for (var index = 0; index < this.materials.length; index++) {
  26793. if (this.materials[index].id === id) {
  26794. return this.materials[index];
  26795. }
  26796. }
  26797. return null;
  26798. };
  26799. /**
  26800. * Gets a material using its name
  26801. * @param name defines the material's name
  26802. * @return the material or null if none found.
  26803. */
  26804. Scene.prototype.getMaterialByName = function (name) {
  26805. for (var index = 0; index < this.materials.length; index++) {
  26806. if (this.materials[index].name === name) {
  26807. return this.materials[index];
  26808. }
  26809. }
  26810. return null;
  26811. };
  26812. /**
  26813. * Gets a camera using its id
  26814. * @param id defines the id to look for
  26815. * @returns the camera or null if not found
  26816. */
  26817. Scene.prototype.getCameraByID = function (id) {
  26818. for (var index = 0; index < this.cameras.length; index++) {
  26819. if (this.cameras[index].id === id) {
  26820. return this.cameras[index];
  26821. }
  26822. }
  26823. return null;
  26824. };
  26825. /**
  26826. * Gets a camera using its unique id
  26827. * @param uniqueId defines the unique id to look for
  26828. * @returns the camera or null if not found
  26829. */
  26830. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  26831. for (var index = 0; index < this.cameras.length; index++) {
  26832. if (this.cameras[index].uniqueId === uniqueId) {
  26833. return this.cameras[index];
  26834. }
  26835. }
  26836. return null;
  26837. };
  26838. /**
  26839. * Gets a camera using its name
  26840. * @param name defines the camera's name
  26841. * @return the camera or null if none found.
  26842. */
  26843. Scene.prototype.getCameraByName = function (name) {
  26844. for (var index = 0; index < this.cameras.length; index++) {
  26845. if (this.cameras[index].name === name) {
  26846. return this.cameras[index];
  26847. }
  26848. }
  26849. return null;
  26850. };
  26851. /**
  26852. * Gets a bone using its id
  26853. * @param id defines the bone's id
  26854. * @return the bone or null if not found
  26855. */
  26856. Scene.prototype.getBoneByID = function (id) {
  26857. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26858. var skeleton = this.skeletons[skeletonIndex];
  26859. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26860. if (skeleton.bones[boneIndex].id === id) {
  26861. return skeleton.bones[boneIndex];
  26862. }
  26863. }
  26864. }
  26865. return null;
  26866. };
  26867. /**
  26868. * Gets a bone using its id
  26869. * @param name defines the bone's name
  26870. * @return the bone or null if not found
  26871. */
  26872. Scene.prototype.getBoneByName = function (name) {
  26873. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26874. var skeleton = this.skeletons[skeletonIndex];
  26875. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26876. if (skeleton.bones[boneIndex].name === name) {
  26877. return skeleton.bones[boneIndex];
  26878. }
  26879. }
  26880. }
  26881. return null;
  26882. };
  26883. /**
  26884. * Gets a light node using its name
  26885. * @param name defines the the light's name
  26886. * @return the light or null if none found.
  26887. */
  26888. Scene.prototype.getLightByName = function (name) {
  26889. for (var index = 0; index < this.lights.length; index++) {
  26890. if (this.lights[index].name === name) {
  26891. return this.lights[index];
  26892. }
  26893. }
  26894. return null;
  26895. };
  26896. /**
  26897. * Gets a light node using its id
  26898. * @param id defines the light's id
  26899. * @return the light or null if none found.
  26900. */
  26901. Scene.prototype.getLightByID = function (id) {
  26902. for (var index = 0; index < this.lights.length; index++) {
  26903. if (this.lights[index].id === id) {
  26904. return this.lights[index];
  26905. }
  26906. }
  26907. return null;
  26908. };
  26909. /**
  26910. * Gets a light node using its scene-generated unique ID
  26911. * @param uniqueId defines the light's unique id
  26912. * @return the light or null if none found.
  26913. */
  26914. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  26915. for (var index = 0; index < this.lights.length; index++) {
  26916. if (this.lights[index].uniqueId === uniqueId) {
  26917. return this.lights[index];
  26918. }
  26919. }
  26920. return null;
  26921. };
  26922. /**
  26923. * Gets a particle system by id
  26924. * @param id defines the particle system id
  26925. * @return the corresponding system or null if none found
  26926. */
  26927. Scene.prototype.getParticleSystemByID = function (id) {
  26928. for (var index = 0; index < this.particleSystems.length; index++) {
  26929. if (this.particleSystems[index].id === id) {
  26930. return this.particleSystems[index];
  26931. }
  26932. }
  26933. return null;
  26934. };
  26935. /**
  26936. * Gets a geometry using its ID
  26937. * @param id defines the geometry's id
  26938. * @return the geometry or null if none found.
  26939. */
  26940. Scene.prototype.getGeometryByID = function (id) {
  26941. for (var index = 0; index < this.geometries.length; index++) {
  26942. if (this.geometries[index].id === id) {
  26943. return this.geometries[index];
  26944. }
  26945. }
  26946. return null;
  26947. };
  26948. /**
  26949. * Add a new geometry to this scene
  26950. * @param geometry defines the geometry to be added to the scene.
  26951. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  26952. * @return a boolean defining if the geometry was added or not
  26953. */
  26954. Scene.prototype.pushGeometry = function (geometry, force) {
  26955. if (!force && this.getGeometryByID(geometry.id)) {
  26956. return false;
  26957. }
  26958. this.geometries.push(geometry);
  26959. //notify the collision coordinator
  26960. if (this.collisionCoordinator) {
  26961. this.collisionCoordinator.onGeometryAdded(geometry);
  26962. }
  26963. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  26964. return true;
  26965. };
  26966. /**
  26967. * Removes an existing geometry
  26968. * @param geometry defines the geometry to be removed from the scene
  26969. * @return a boolean defining if the geometry was removed or not
  26970. */
  26971. Scene.prototype.removeGeometry = function (geometry) {
  26972. var index = this.geometries.indexOf(geometry);
  26973. if (index > -1) {
  26974. this.geometries.splice(index, 1);
  26975. //notify the collision coordinator
  26976. if (this.collisionCoordinator) {
  26977. this.collisionCoordinator.onGeometryDeleted(geometry);
  26978. }
  26979. this.onGeometryRemovedObservable.notifyObservers(geometry);
  26980. return true;
  26981. }
  26982. return false;
  26983. };
  26984. /**
  26985. * Gets the list of geometries attached to the scene
  26986. * @returns an array of Geometry
  26987. */
  26988. Scene.prototype.getGeometries = function () {
  26989. return this.geometries;
  26990. };
  26991. /**
  26992. * Gets the first added mesh found of a given ID
  26993. * @param id defines the id to search for
  26994. * @return the mesh found or null if not found at all
  26995. */
  26996. Scene.prototype.getMeshByID = function (id) {
  26997. for (var index = 0; index < this.meshes.length; index++) {
  26998. if (this.meshes[index].id === id) {
  26999. return this.meshes[index];
  27000. }
  27001. }
  27002. return null;
  27003. };
  27004. /**
  27005. * Gets a list of meshes using their id
  27006. * @param id defines the id to search for
  27007. * @returns a list of meshes
  27008. */
  27009. Scene.prototype.getMeshesByID = function (id) {
  27010. return this.meshes.filter(function (m) {
  27011. return m.id === id;
  27012. });
  27013. };
  27014. /**
  27015. * Gets the first added transform node found of a given ID
  27016. * @param id defines the id to search for
  27017. * @return the found transform node or null if not found at all.
  27018. */
  27019. Scene.prototype.getTransformNodeByID = function (id) {
  27020. for (var index = 0; index < this.transformNodes.length; index++) {
  27021. if (this.transformNodes[index].id === id) {
  27022. return this.transformNodes[index];
  27023. }
  27024. }
  27025. return null;
  27026. };
  27027. /**
  27028. * Gets a list of transform nodes using their id
  27029. * @param id defines the id to search for
  27030. * @returns a list of transform nodes
  27031. */
  27032. Scene.prototype.getTransformNodesByID = function (id) {
  27033. return this.transformNodes.filter(function (m) {
  27034. return m.id === id;
  27035. });
  27036. };
  27037. /**
  27038. * Gets a mesh with its auto-generated unique id
  27039. * @param uniqueId defines the unique id to search for
  27040. * @return the found mesh or null if not found at all.
  27041. */
  27042. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  27043. for (var index = 0; index < this.meshes.length; index++) {
  27044. if (this.meshes[index].uniqueId === uniqueId) {
  27045. return this.meshes[index];
  27046. }
  27047. }
  27048. return null;
  27049. };
  27050. /**
  27051. * Gets a the last added mesh using a given id
  27052. * @param id defines the id to search for
  27053. * @return the found mesh or null if not found at all.
  27054. */
  27055. Scene.prototype.getLastMeshByID = function (id) {
  27056. for (var index = this.meshes.length - 1; index >= 0; index--) {
  27057. if (this.meshes[index].id === id) {
  27058. return this.meshes[index];
  27059. }
  27060. }
  27061. return null;
  27062. };
  27063. /**
  27064. * Gets a the last added node (Mesh, Camera, Light) using a given id
  27065. * @param id defines the id to search for
  27066. * @return the found node or null if not found at all
  27067. */
  27068. Scene.prototype.getLastEntryByID = function (id) {
  27069. var index;
  27070. for (index = this.meshes.length - 1; index >= 0; index--) {
  27071. if (this.meshes[index].id === id) {
  27072. return this.meshes[index];
  27073. }
  27074. }
  27075. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  27076. if (this.transformNodes[index].id === id) {
  27077. return this.transformNodes[index];
  27078. }
  27079. }
  27080. for (index = this.cameras.length - 1; index >= 0; index--) {
  27081. if (this.cameras[index].id === id) {
  27082. return this.cameras[index];
  27083. }
  27084. }
  27085. for (index = this.lights.length - 1; index >= 0; index--) {
  27086. if (this.lights[index].id === id) {
  27087. return this.lights[index];
  27088. }
  27089. }
  27090. return null;
  27091. };
  27092. /**
  27093. * Gets a node (Mesh, Camera, Light) using a given id
  27094. * @param id defines the id to search for
  27095. * @return the found node or null if not found at all
  27096. */
  27097. Scene.prototype.getNodeByID = function (id) {
  27098. var mesh = this.getMeshByID(id);
  27099. if (mesh) {
  27100. return mesh;
  27101. }
  27102. var light = this.getLightByID(id);
  27103. if (light) {
  27104. return light;
  27105. }
  27106. var camera = this.getCameraByID(id);
  27107. if (camera) {
  27108. return camera;
  27109. }
  27110. var bone = this.getBoneByID(id);
  27111. return bone;
  27112. };
  27113. /**
  27114. * Gets a node (Mesh, Camera, Light) using a given name
  27115. * @param name defines the name to search for
  27116. * @return the found node or null if not found at all.
  27117. */
  27118. Scene.prototype.getNodeByName = function (name) {
  27119. var mesh = this.getMeshByName(name);
  27120. if (mesh) {
  27121. return mesh;
  27122. }
  27123. var light = this.getLightByName(name);
  27124. if (light) {
  27125. return light;
  27126. }
  27127. var camera = this.getCameraByName(name);
  27128. if (camera) {
  27129. return camera;
  27130. }
  27131. var bone = this.getBoneByName(name);
  27132. return bone;
  27133. };
  27134. /**
  27135. * Gets a mesh using a given name
  27136. * @param name defines the name to search for
  27137. * @return the found mesh or null if not found at all.
  27138. */
  27139. Scene.prototype.getMeshByName = function (name) {
  27140. for (var index = 0; index < this.meshes.length; index++) {
  27141. if (this.meshes[index].name === name) {
  27142. return this.meshes[index];
  27143. }
  27144. }
  27145. return null;
  27146. };
  27147. /**
  27148. * Gets a transform node using a given name
  27149. * @param name defines the name to search for
  27150. * @return the found transform node or null if not found at all.
  27151. */
  27152. Scene.prototype.getTransformNodeByName = function (name) {
  27153. for (var index = 0; index < this.transformNodes.length; index++) {
  27154. if (this.transformNodes[index].name === name) {
  27155. return this.transformNodes[index];
  27156. }
  27157. }
  27158. return null;
  27159. };
  27160. /**
  27161. * Gets a sound using a given name
  27162. * @param name defines the name to search for
  27163. * @return the found sound or null if not found at all.
  27164. */
  27165. Scene.prototype.getSoundByName = function (name) {
  27166. var index;
  27167. if (BABYLON.AudioEngine) {
  27168. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  27169. if (this.mainSoundTrack.soundCollection[index].name === name) {
  27170. return this.mainSoundTrack.soundCollection[index];
  27171. }
  27172. }
  27173. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  27174. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  27175. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  27176. return this.soundTracks[sdIndex].soundCollection[index];
  27177. }
  27178. }
  27179. }
  27180. }
  27181. return null;
  27182. };
  27183. /**
  27184. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  27185. * @param id defines the id to search for
  27186. * @return the found skeleton or null if not found at all.
  27187. */
  27188. Scene.prototype.getLastSkeletonByID = function (id) {
  27189. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  27190. if (this.skeletons[index].id === id) {
  27191. return this.skeletons[index];
  27192. }
  27193. }
  27194. return null;
  27195. };
  27196. /**
  27197. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  27198. * @param id defines the id to search for
  27199. * @return the found skeleton or null if not found at all.
  27200. */
  27201. Scene.prototype.getSkeletonById = function (id) {
  27202. for (var index = 0; index < this.skeletons.length; index++) {
  27203. if (this.skeletons[index].id === id) {
  27204. return this.skeletons[index];
  27205. }
  27206. }
  27207. return null;
  27208. };
  27209. /**
  27210. * Gets a skeleton using a given name
  27211. * @param name defines the name to search for
  27212. * @return the found skeleton or null if not found at all.
  27213. */
  27214. Scene.prototype.getSkeletonByName = function (name) {
  27215. for (var index = 0; index < this.skeletons.length; index++) {
  27216. if (this.skeletons[index].name === name) {
  27217. return this.skeletons[index];
  27218. }
  27219. }
  27220. return null;
  27221. };
  27222. /**
  27223. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  27224. * @param id defines the id to search for
  27225. * @return the found morph target manager or null if not found at all.
  27226. */
  27227. Scene.prototype.getMorphTargetManagerById = function (id) {
  27228. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  27229. if (this.morphTargetManagers[index].uniqueId === id) {
  27230. return this.morphTargetManagers[index];
  27231. }
  27232. }
  27233. return null;
  27234. };
  27235. /**
  27236. * Gets a boolean indicating if the given mesh is active
  27237. * @param mesh defines the mesh to look for
  27238. * @returns true if the mesh is in the active list
  27239. */
  27240. Scene.prototype.isActiveMesh = function (mesh) {
  27241. return (this._activeMeshes.indexOf(mesh) !== -1);
  27242. };
  27243. Object.defineProperty(Scene.prototype, "uid", {
  27244. /**
  27245. * Return a unique id as a string which can serve as an identifier for the scene
  27246. */
  27247. get: function () {
  27248. if (!this._uid) {
  27249. this._uid = BABYLON.Tools.RandomId();
  27250. }
  27251. return this._uid;
  27252. },
  27253. enumerable: true,
  27254. configurable: true
  27255. });
  27256. /**
  27257. * Add an externaly attached data from its key.
  27258. * This method call will fail and return false, if such key already exists.
  27259. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  27260. * @param key the unique key that identifies the data
  27261. * @param data the data object to associate to the key for this Engine instance
  27262. * @return true if no such key were already present and the data was added successfully, false otherwise
  27263. */
  27264. Scene.prototype.addExternalData = function (key, data) {
  27265. if (!this._externalData) {
  27266. this._externalData = new BABYLON.StringDictionary();
  27267. }
  27268. return this._externalData.add(key, data);
  27269. };
  27270. /**
  27271. * Get an externaly attached data from its key
  27272. * @param key the unique key that identifies the data
  27273. * @return the associated data, if present (can be null), or undefined if not present
  27274. */
  27275. Scene.prototype.getExternalData = function (key) {
  27276. if (!this._externalData) {
  27277. return null;
  27278. }
  27279. return this._externalData.get(key);
  27280. };
  27281. /**
  27282. * Get an externaly attached data from its key, create it using a factory if it's not already present
  27283. * @param key the unique key that identifies the data
  27284. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  27285. * @return the associated data, can be null if the factory returned null.
  27286. */
  27287. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  27288. if (!this._externalData) {
  27289. this._externalData = new BABYLON.StringDictionary();
  27290. }
  27291. return this._externalData.getOrAddWithFactory(key, factory);
  27292. };
  27293. /**
  27294. * Remove an externaly attached data from the Engine instance
  27295. * @param key the unique key that identifies the data
  27296. * @return true if the data was successfully removed, false if it doesn't exist
  27297. */
  27298. Scene.prototype.removeExternalData = function (key) {
  27299. return this._externalData.remove(key);
  27300. };
  27301. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  27302. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  27303. for (var _i = 0, _a = this._evaluateSubMeshStage; _i < _a.length; _i++) {
  27304. var step = _a[_i];
  27305. step.action(mesh, subMesh);
  27306. }
  27307. var material = subMesh.getMaterial();
  27308. if (material !== null && material !== undefined) {
  27309. // Render targets
  27310. if (material.hasRenderTargetTextures && material.getRenderTargetTextures !== undefined) {
  27311. if (this._processedMaterials.indexOf(material) === -1) {
  27312. this._processedMaterials.push(material);
  27313. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  27314. }
  27315. }
  27316. // Dispatch
  27317. this._activeIndices.addCount(subMesh.indexCount, false);
  27318. this._renderingManager.dispatch(subMesh, mesh, material);
  27319. }
  27320. }
  27321. };
  27322. /**
  27323. * Clear the processed materials smart array preventing retention point in material dispose.
  27324. */
  27325. Scene.prototype.freeProcessedMaterials = function () {
  27326. this._processedMaterials.dispose();
  27327. };
  27328. /**
  27329. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27330. */
  27331. Scene.prototype.freeActiveMeshes = function () {
  27332. this._activeMeshes.dispose();
  27333. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27334. this.activeCamera._activeMeshes.dispose();
  27335. }
  27336. if (this.activeCameras) {
  27337. for (var i = 0; i < this.activeCameras.length; i++) {
  27338. var activeCamera = this.activeCameras[i];
  27339. if (activeCamera && activeCamera._activeMeshes) {
  27340. activeCamera._activeMeshes.dispose();
  27341. }
  27342. }
  27343. }
  27344. };
  27345. /**
  27346. * Clear the info related to rendering groups preventing retention points during dispose.
  27347. */
  27348. Scene.prototype.freeRenderingGroups = function () {
  27349. if (this._renderingManager) {
  27350. this._renderingManager.freeRenderingGroups();
  27351. }
  27352. if (this.textures) {
  27353. for (var i = 0; i < this.textures.length; i++) {
  27354. var texture = this.textures[i];
  27355. if (texture && texture.renderList) {
  27356. texture.freeRenderingGroups();
  27357. }
  27358. }
  27359. }
  27360. };
  27361. /** @hidden */
  27362. Scene.prototype._isInIntermediateRendering = function () {
  27363. return this._intermediateRendering;
  27364. };
  27365. /**
  27366. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27367. * @returns the current scene
  27368. */
  27369. Scene.prototype.freezeActiveMeshes = function () {
  27370. if (!this.activeCamera) {
  27371. return this;
  27372. }
  27373. if (!this._frustumPlanes) {
  27374. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27375. }
  27376. this._evaluateActiveMeshes();
  27377. this._activeMeshesFrozen = true;
  27378. return this;
  27379. };
  27380. /**
  27381. * Use this function to restart evaluating active meshes on every frame
  27382. * @returns the current scene
  27383. */
  27384. Scene.prototype.unfreezeActiveMeshes = function () {
  27385. this._activeMeshesFrozen = false;
  27386. return this;
  27387. };
  27388. Scene.prototype._evaluateActiveMeshes = function () {
  27389. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27390. return;
  27391. }
  27392. if (!this.activeCamera) {
  27393. return;
  27394. }
  27395. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27396. this.activeCamera._activeMeshes.reset();
  27397. this._activeMeshes.reset();
  27398. this._renderingManager.reset();
  27399. this._processedMaterials.reset();
  27400. this._activeParticleSystems.reset();
  27401. this._activeSkeletons.reset();
  27402. this._softwareSkinnedMeshes.reset();
  27403. for (var _i = 0, _a = this._beforeEvaluateActiveMeshStage; _i < _a.length; _i++) {
  27404. var step = _a[_i];
  27405. step.action();
  27406. }
  27407. // Determine mesh candidates
  27408. var meshes = this.getActiveMeshCandidates();
  27409. // Check each mesh
  27410. var len = meshes.length;
  27411. for (var i = 0; i < len; i++) {
  27412. var mesh = meshes.data[i];
  27413. if (mesh.isBlocked) {
  27414. continue;
  27415. }
  27416. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27417. if (!mesh.isReady() || !mesh.isEnabled()) {
  27418. continue;
  27419. }
  27420. mesh.computeWorldMatrix();
  27421. // Intersections
  27422. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers2(BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger)) {
  27423. this._meshesForIntersections.pushNoDuplicate(mesh);
  27424. }
  27425. // Switch to current LOD
  27426. var meshLOD = mesh.getLOD(this.activeCamera);
  27427. if (meshLOD === undefined || meshLOD === null) {
  27428. continue;
  27429. }
  27430. mesh._preActivate();
  27431. if (mesh.isVisible && mesh.visibility > 0 && (mesh.alwaysSelectAsActiveMesh || ((mesh.layerMask & this.activeCamera.layerMask) !== 0 && mesh.isInFrustum(this._frustumPlanes)))) {
  27432. this._activeMeshes.push(mesh);
  27433. this.activeCamera._activeMeshes.push(mesh);
  27434. mesh._activate(this._renderId);
  27435. if (meshLOD !== mesh) {
  27436. meshLOD._activate(this._renderId);
  27437. }
  27438. this._activeMesh(mesh, meshLOD);
  27439. }
  27440. }
  27441. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27442. // Particle systems
  27443. if (this.particlesEnabled) {
  27444. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27445. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27446. var particleSystem = this.particleSystems[particleIndex];
  27447. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27448. continue;
  27449. }
  27450. var emitter = particleSystem.emitter;
  27451. if (!emitter.position || emitter.isEnabled()) {
  27452. this._activeParticleSystems.push(particleSystem);
  27453. particleSystem.animate();
  27454. this._renderingManager.dispatchParticles(particleSystem);
  27455. }
  27456. }
  27457. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27458. }
  27459. };
  27460. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27461. if (this._skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27462. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27463. mesh.skeleton.prepare();
  27464. }
  27465. if (!mesh.computeBonesUsingShaders) {
  27466. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27467. }
  27468. }
  27469. for (var _i = 0, _a = this._activeMeshStage; _i < _a.length; _i++) {
  27470. var step = _a[_i];
  27471. step.action(sourceMesh, mesh);
  27472. }
  27473. if (mesh !== undefined && mesh !== null
  27474. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27475. var subMeshes = this.getActiveSubMeshCandidates(mesh);
  27476. var len = subMeshes.length;
  27477. for (var i = 0; i < len; i++) {
  27478. var subMesh = subMeshes.data[i];
  27479. this._evaluateSubMesh(subMesh, mesh);
  27480. }
  27481. }
  27482. };
  27483. /**
  27484. * Update the transform matrix to update from the current active camera
  27485. * @param force defines a boolean used to force the update even if cache is up to date
  27486. */
  27487. Scene.prototype.updateTransformMatrix = function (force) {
  27488. if (!this.activeCamera) {
  27489. return;
  27490. }
  27491. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27492. };
  27493. /**
  27494. * 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)
  27495. * @param alternateCamera defines the camera to use
  27496. */
  27497. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27498. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27499. };
  27500. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27501. if (camera && camera._skipRendering) {
  27502. return;
  27503. }
  27504. var engine = this._engine;
  27505. this.activeCamera = camera;
  27506. if (!this.activeCamera)
  27507. throw new Error("Active camera not set");
  27508. // Viewport
  27509. engine.setViewport(this.activeCamera.viewport);
  27510. // Camera
  27511. this.resetCachedMaterial();
  27512. this._renderId++;
  27513. this.updateTransformMatrix();
  27514. if (camera._alternateCamera) {
  27515. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27516. this._alternateRendering = true;
  27517. }
  27518. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27519. // Meshes
  27520. this._evaluateActiveMeshes();
  27521. // Software skinning
  27522. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27523. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27524. mesh.applySkeleton(mesh.skeleton);
  27525. }
  27526. // Render targets
  27527. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27528. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27529. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27530. }
  27531. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27532. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27533. }
  27534. // Collects render targets from external components.
  27535. for (var _i = 0, _a = this._gatherActiveCameraRenderTargetsStage; _i < _a.length; _i++) {
  27536. var step = _a[_i];
  27537. step.action(this._renderTargets);
  27538. }
  27539. if (this.renderTargetsEnabled) {
  27540. this._intermediateRendering = true;
  27541. if (this._renderTargets.length > 0) {
  27542. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27543. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27544. var renderTarget = this._renderTargets.data[renderIndex];
  27545. if (renderTarget._shouldRender()) {
  27546. this._renderId++;
  27547. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27548. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27549. }
  27550. }
  27551. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27552. this._renderId++;
  27553. }
  27554. for (var _b = 0, _c = this._cameraDrawRenderTargetStage; _b < _c.length; _b++) {
  27555. var step = _c[_b];
  27556. step.action(this.activeCamera);
  27557. }
  27558. this._intermediateRendering = false;
  27559. engine.restoreDefaultFramebuffer(); // Restore back buffer if needed
  27560. }
  27561. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27562. // Prepare Frame
  27563. if (this.postProcessManager) {
  27564. this.postProcessManager._prepareFrame();
  27565. }
  27566. // Before Camera Draw
  27567. for (var _d = 0, _e = this._beforeCameraDrawStage; _d < _e.length; _d++) {
  27568. var step = _e[_d];
  27569. step.action(this.activeCamera);
  27570. }
  27571. // Render
  27572. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27573. this._renderingManager.render(null, null, true, true);
  27574. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27575. // After Camera Draw
  27576. for (var _f = 0, _g = this._afterCameraDrawStage; _f < _g.length; _f++) {
  27577. var step = _g[_f];
  27578. step.action(this.activeCamera);
  27579. }
  27580. // Finalize frame
  27581. if (this.postProcessManager) {
  27582. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27583. }
  27584. // Reset some special arrays
  27585. this._renderTargets.reset();
  27586. this._alternateRendering = false;
  27587. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27588. };
  27589. Scene.prototype._processSubCameras = function (camera) {
  27590. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27591. this._renderForCamera(camera);
  27592. return;
  27593. }
  27594. // rig cameras
  27595. for (var index = 0; index < camera._rigCameras.length; index++) {
  27596. this._renderForCamera(camera._rigCameras[index], camera);
  27597. }
  27598. this.activeCamera = camera;
  27599. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27600. };
  27601. Scene.prototype._checkIntersections = function () {
  27602. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27603. var sourceMesh = this._meshesForIntersections.data[index];
  27604. if (!sourceMesh.actionManager) {
  27605. continue;
  27606. }
  27607. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27608. var action = sourceMesh.actionManager.actions[actionIndex];
  27609. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27610. var parameters = action.getTriggerParameter();
  27611. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27612. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27613. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27614. if (areIntersecting && currentIntersectionInProgress === -1) {
  27615. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27616. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27617. sourceMesh._intersectionsInProgress.push(otherMesh);
  27618. }
  27619. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27620. sourceMesh._intersectionsInProgress.push(otherMesh);
  27621. }
  27622. }
  27623. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27624. //They intersected, and now they don't.
  27625. //is this trigger an exit trigger? execute an event.
  27626. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27627. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27628. }
  27629. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27630. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27631. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27632. return otherMesh === parameterMesh;
  27633. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27634. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27635. }
  27636. }
  27637. }
  27638. }
  27639. }
  27640. };
  27641. /**
  27642. * Render the scene
  27643. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  27644. */
  27645. Scene.prototype.render = function (updateCameras) {
  27646. if (updateCameras === void 0) { updateCameras = true; }
  27647. if (this.isDisposed) {
  27648. return;
  27649. }
  27650. this._frameId++;
  27651. // Register components that have been associated lately to the scene.
  27652. this._registerTransientComponents();
  27653. this._activeParticles.fetchNewFrame();
  27654. this._totalVertices.fetchNewFrame();
  27655. this._activeIndices.fetchNewFrame();
  27656. this._activeBones.fetchNewFrame();
  27657. this._meshesForIntersections.reset();
  27658. this.resetCachedMaterial();
  27659. this.onBeforeAnimationsObservable.notifyObservers(this);
  27660. // Actions
  27661. if (this.actionManager) {
  27662. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27663. }
  27664. if (this._engine.isDeterministicLockStep()) {
  27665. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27666. var defaultFPS = (60.0 / 1000.0);
  27667. var defaultFrameTime = 1000 / 60; // frame time in MS
  27668. if (this._physicsEngine) {
  27669. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  27670. }
  27671. var stepsTaken = 0;
  27672. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27673. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27674. internalSteps = Math.min(internalSteps, maxSubSteps);
  27675. do {
  27676. this.onBeforeStepObservable.notifyObservers(this);
  27677. // Animations
  27678. this._animationRatio = defaultFrameTime * defaultFPS;
  27679. this._animate();
  27680. this.onAfterAnimationsObservable.notifyObservers(this);
  27681. // Physics
  27682. if (this._physicsEngine) {
  27683. this.onBeforePhysicsObservable.notifyObservers(this);
  27684. this._physicsEngine._step(defaultFrameTime / 1000);
  27685. this.onAfterPhysicsObservable.notifyObservers(this);
  27686. }
  27687. this.onAfterStepObservable.notifyObservers(this);
  27688. this._currentStepId++;
  27689. stepsTaken++;
  27690. deltaTime -= defaultFrameTime;
  27691. } while (deltaTime > 0 && stepsTaken < internalSteps);
  27692. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  27693. }
  27694. else {
  27695. // Animations
  27696. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  27697. this._animationRatio = deltaTime * (60.0 / 1000.0);
  27698. this._animate();
  27699. this.onAfterAnimationsObservable.notifyObservers(this);
  27700. // Physics
  27701. if (this._physicsEngine) {
  27702. this.onBeforePhysicsObservable.notifyObservers(this);
  27703. this._physicsEngine._step(deltaTime / 1000.0);
  27704. this.onAfterPhysicsObservable.notifyObservers(this);
  27705. }
  27706. }
  27707. // Before camera update steps
  27708. for (var _i = 0, _a = this._beforeCameraUpdateStage; _i < _a.length; _i++) {
  27709. var step = _a[_i];
  27710. step.action();
  27711. }
  27712. // Update Cameras
  27713. if (updateCameras) {
  27714. if (this.activeCameras.length > 0) {
  27715. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27716. var camera = this.activeCameras[cameraIndex];
  27717. camera.update();
  27718. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27719. // rig cameras
  27720. for (var index = 0; index < camera._rigCameras.length; index++) {
  27721. camera._rigCameras[index].update();
  27722. }
  27723. }
  27724. }
  27725. }
  27726. else if (this.activeCamera) {
  27727. this.activeCamera.update();
  27728. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27729. // rig cameras
  27730. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  27731. this.activeCamera._rigCameras[index].update();
  27732. }
  27733. }
  27734. }
  27735. }
  27736. // Before render
  27737. this.onBeforeRenderObservable.notifyObservers(this);
  27738. // Customs render targets
  27739. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27740. var engine = this.getEngine();
  27741. var currentActiveCamera = this.activeCamera;
  27742. if (this.renderTargetsEnabled) {
  27743. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27744. this._intermediateRendering = true;
  27745. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  27746. var renderTarget = this.customRenderTargets[customIndex];
  27747. if (renderTarget._shouldRender()) {
  27748. this._renderId++;
  27749. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  27750. if (!this.activeCamera)
  27751. throw new Error("Active camera not set");
  27752. // Viewport
  27753. engine.setViewport(this.activeCamera.viewport);
  27754. // Camera
  27755. this.updateTransformMatrix();
  27756. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  27757. }
  27758. }
  27759. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27760. this._intermediateRendering = false;
  27761. this._renderId++;
  27762. }
  27763. // Restore back buffer
  27764. if (this.customRenderTargets.length > 0) {
  27765. engine.restoreDefaultFramebuffer();
  27766. }
  27767. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27768. this.activeCamera = currentActiveCamera;
  27769. for (var _b = 0, _c = this._beforeClearStage; _b < _c.length; _b++) {
  27770. var step = _c[_b];
  27771. step.action();
  27772. }
  27773. // Clear
  27774. if (this.autoClearDepthAndStencil || this.autoClear) {
  27775. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  27776. }
  27777. // Collects render targets from external components.
  27778. for (var _d = 0, _e = this._gatherRenderTargetsStage; _d < _e.length; _d++) {
  27779. var step = _e[_d];
  27780. step.action(this._renderTargets);
  27781. }
  27782. // Multi-cameras?
  27783. if (this.activeCameras.length > 0) {
  27784. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27785. if (cameraIndex > 0) {
  27786. this._engine.clear(null, false, true, true);
  27787. }
  27788. this._processSubCameras(this.activeCameras[cameraIndex]);
  27789. }
  27790. }
  27791. else {
  27792. if (!this.activeCamera) {
  27793. throw new Error("No camera defined");
  27794. }
  27795. this._processSubCameras(this.activeCamera);
  27796. }
  27797. // Intersection checks
  27798. this._checkIntersections();
  27799. // Update the audio listener attached to the camera
  27800. if (BABYLON.AudioEngine) {
  27801. this._updateAudioParameters();
  27802. }
  27803. // After render
  27804. if (this.afterRender) {
  27805. this.afterRender();
  27806. }
  27807. this.onAfterRenderObservable.notifyObservers(this);
  27808. // Cleaning
  27809. for (var index = 0; index < this._toBeDisposed.length; index++) {
  27810. var data = this._toBeDisposed.data[index];
  27811. if (data) {
  27812. data.dispose();
  27813. }
  27814. }
  27815. this._toBeDisposed.reset();
  27816. if (this.dumpNextRenderTargets) {
  27817. this.dumpNextRenderTargets = false;
  27818. }
  27819. this._activeBones.addCount(0, true);
  27820. this._activeIndices.addCount(0, true);
  27821. this._activeParticles.addCount(0, true);
  27822. };
  27823. Scene.prototype._updateAudioParameters = function () {
  27824. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  27825. return;
  27826. }
  27827. var listeningCamera;
  27828. var audioEngine = BABYLON.Engine.audioEngine;
  27829. if (this.activeCameras.length > 0) {
  27830. listeningCamera = this.activeCameras[0];
  27831. }
  27832. else {
  27833. listeningCamera = this.activeCamera;
  27834. }
  27835. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  27836. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  27837. // for VR cameras
  27838. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  27839. listeningCamera = listeningCamera.rigCameras[0];
  27840. }
  27841. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  27842. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  27843. cameraDirection.normalize();
  27844. // To avoid some errors on GearVR
  27845. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  27846. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  27847. }
  27848. var i;
  27849. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27850. var sound = this.mainSoundTrack.soundCollection[i];
  27851. if (sound.useCustomAttenuation) {
  27852. sound.updateDistanceFromListener();
  27853. }
  27854. }
  27855. for (i = 0; i < this.soundTracks.length; i++) {
  27856. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27857. sound = this.soundTracks[i].soundCollection[j];
  27858. if (sound.useCustomAttenuation) {
  27859. sound.updateDistanceFromListener();
  27860. }
  27861. }
  27862. }
  27863. }
  27864. };
  27865. Object.defineProperty(Scene.prototype, "audioEnabled", {
  27866. // Audio
  27867. /**
  27868. * Gets or sets if audio support is enabled
  27869. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27870. */
  27871. get: function () {
  27872. return this._audioEnabled;
  27873. },
  27874. set: function (value) {
  27875. this._audioEnabled = value;
  27876. if (BABYLON.AudioEngine) {
  27877. if (this._audioEnabled) {
  27878. this._enableAudio();
  27879. }
  27880. else {
  27881. this._disableAudio();
  27882. }
  27883. }
  27884. },
  27885. enumerable: true,
  27886. configurable: true
  27887. });
  27888. Scene.prototype._disableAudio = function () {
  27889. var i;
  27890. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27891. this.mainSoundTrack.soundCollection[i].pause();
  27892. }
  27893. for (i = 0; i < this.soundTracks.length; i++) {
  27894. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27895. this.soundTracks[i].soundCollection[j].pause();
  27896. }
  27897. }
  27898. };
  27899. Scene.prototype._enableAudio = function () {
  27900. var i;
  27901. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27902. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  27903. this.mainSoundTrack.soundCollection[i].play();
  27904. }
  27905. }
  27906. for (i = 0; i < this.soundTracks.length; i++) {
  27907. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27908. if (this.soundTracks[i].soundCollection[j].isPaused) {
  27909. this.soundTracks[i].soundCollection[j].play();
  27910. }
  27911. }
  27912. }
  27913. };
  27914. Object.defineProperty(Scene.prototype, "headphone", {
  27915. /**
  27916. * Gets or sets if audio will be output to headphones
  27917. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27918. */
  27919. get: function () {
  27920. return this._headphone;
  27921. },
  27922. set: function (value) {
  27923. this._headphone = value;
  27924. if (BABYLON.AudioEngine) {
  27925. if (this._headphone) {
  27926. this._switchAudioModeForHeadphones();
  27927. }
  27928. else {
  27929. this._switchAudioModeForNormalSpeakers();
  27930. }
  27931. }
  27932. },
  27933. enumerable: true,
  27934. configurable: true
  27935. });
  27936. Scene.prototype._switchAudioModeForHeadphones = function () {
  27937. this.mainSoundTrack.switchPanningModelToHRTF();
  27938. for (var i = 0; i < this.soundTracks.length; i++) {
  27939. this.soundTracks[i].switchPanningModelToHRTF();
  27940. }
  27941. };
  27942. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  27943. this.mainSoundTrack.switchPanningModelToEqualPower();
  27944. for (var i = 0; i < this.soundTracks.length; i++) {
  27945. this.soundTracks[i].switchPanningModelToEqualPower();
  27946. }
  27947. };
  27948. /**
  27949. * Freeze all materials
  27950. * A frozen material will not be updatable but should be faster to render
  27951. */
  27952. Scene.prototype.freezeMaterials = function () {
  27953. for (var i = 0; i < this.materials.length; i++) {
  27954. this.materials[i].freeze();
  27955. }
  27956. };
  27957. /**
  27958. * Unfreeze all materials
  27959. * A frozen material will not be updatable but should be faster to render
  27960. */
  27961. Scene.prototype.unfreezeMaterials = function () {
  27962. for (var i = 0; i < this.materials.length; i++) {
  27963. this.materials[i].unfreeze();
  27964. }
  27965. };
  27966. /**
  27967. * Releases all held ressources
  27968. */
  27969. Scene.prototype.dispose = function () {
  27970. this.beforeRender = null;
  27971. this.afterRender = null;
  27972. this.skeletons = [];
  27973. this.morphTargetManagers = [];
  27974. this._transientComponents = [];
  27975. this._isReadyForMeshStage.clear();
  27976. this._beforeEvaluateActiveMeshStage.clear();
  27977. this._evaluateSubMeshStage.clear();
  27978. this._activeMeshStage.clear();
  27979. this._cameraDrawRenderTargetStage.clear();
  27980. this._beforeCameraDrawStage.clear();
  27981. this._beforeRenderingGroupDrawStage.clear();
  27982. this._beforeRenderingMeshStage.clear();
  27983. this._afterRenderingMeshStage.clear();
  27984. this._afterRenderingGroupDrawStage.clear();
  27985. this._afterCameraDrawStage.clear();
  27986. this._beforeCameraUpdateStage.clear();
  27987. this._beforeClearStage.clear();
  27988. this._gatherRenderTargetsStage.clear();
  27989. this._gatherActiveCameraRenderTargetsStage.clear();
  27990. this._pointerMoveStage.clear();
  27991. this._pointerDownStage.clear();
  27992. this._pointerUpStage.clear();
  27993. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  27994. var component = _a[_i];
  27995. component.dispose();
  27996. }
  27997. this.importedMeshesFiles = new Array();
  27998. this.stopAllAnimations();
  27999. this.resetCachedMaterial();
  28000. // Smart arrays
  28001. if (this.activeCamera) {
  28002. this.activeCamera._activeMeshes.dispose();
  28003. this.activeCamera = null;
  28004. }
  28005. this._activeMeshes.dispose();
  28006. this._renderingManager.dispose();
  28007. this._processedMaterials.dispose();
  28008. this._activeParticleSystems.dispose();
  28009. this._activeSkeletons.dispose();
  28010. this._softwareSkinnedMeshes.dispose();
  28011. this._renderTargets.dispose();
  28012. this._registeredForLateAnimationBindings.dispose();
  28013. this._meshesForIntersections.dispose();
  28014. this._toBeDisposed.dispose();
  28015. // Abort active requests
  28016. for (var _b = 0, _c = this._activeRequests; _b < _c.length; _b++) {
  28017. var request = _c[_b];
  28018. request.abort();
  28019. }
  28020. // Events
  28021. this.onDisposeObservable.notifyObservers(this);
  28022. this.onDisposeObservable.clear();
  28023. this.onBeforeRenderObservable.clear();
  28024. this.onAfterRenderObservable.clear();
  28025. this.onBeforeRenderTargetsRenderObservable.clear();
  28026. this.onAfterRenderTargetsRenderObservable.clear();
  28027. this.onAfterStepObservable.clear();
  28028. this.onBeforeStepObservable.clear();
  28029. this.onBeforeActiveMeshesEvaluationObservable.clear();
  28030. this.onAfterActiveMeshesEvaluationObservable.clear();
  28031. this.onBeforeParticlesRenderingObservable.clear();
  28032. this.onAfterParticlesRenderingObservable.clear();
  28033. this.onBeforeDrawPhaseObservable.clear();
  28034. this.onAfterDrawPhaseObservable.clear();
  28035. this.onBeforePhysicsObservable.clear();
  28036. this.onAfterPhysicsObservable.clear();
  28037. this.onBeforeAnimationsObservable.clear();
  28038. this.onAfterAnimationsObservable.clear();
  28039. this.onDataLoadedObservable.clear();
  28040. this.onBeforeRenderingGroupObservable.clear();
  28041. this.onAfterRenderingGroupObservable.clear();
  28042. this.onMeshImportedObservable.clear();
  28043. this.detachControl();
  28044. // Release sounds & sounds tracks
  28045. if (BABYLON.AudioEngine) {
  28046. this.disposeSounds();
  28047. }
  28048. // Detach cameras
  28049. var canvas = this._engine.getRenderingCanvas();
  28050. if (canvas) {
  28051. var index;
  28052. for (index = 0; index < this.cameras.length; index++) {
  28053. this.cameras[index].detachControl(canvas);
  28054. }
  28055. }
  28056. // Release animation groups
  28057. while (this.animationGroups.length) {
  28058. this.animationGroups[0].dispose();
  28059. }
  28060. // Release lights
  28061. while (this.lights.length) {
  28062. this.lights[0].dispose();
  28063. }
  28064. // Release meshes
  28065. while (this.meshes.length) {
  28066. this.meshes[0].dispose(true);
  28067. }
  28068. while (this.transformNodes.length) {
  28069. this.removeTransformNode(this.transformNodes[0]);
  28070. }
  28071. // Release cameras
  28072. while (this.cameras.length) {
  28073. this.cameras[0].dispose();
  28074. }
  28075. // Release materials
  28076. if (this.defaultMaterial) {
  28077. this.defaultMaterial.dispose();
  28078. }
  28079. while (this.multiMaterials.length) {
  28080. this.multiMaterials[0].dispose();
  28081. }
  28082. while (this.materials.length) {
  28083. this.materials[0].dispose();
  28084. }
  28085. // Release particles
  28086. while (this.particleSystems.length) {
  28087. this.particleSystems[0].dispose();
  28088. }
  28089. // Release postProcesses
  28090. while (this.postProcesses.length) {
  28091. this.postProcesses[0].dispose();
  28092. }
  28093. // Release textures
  28094. while (this.textures.length) {
  28095. this.textures[0].dispose();
  28096. }
  28097. // Release UBO
  28098. this._sceneUbo.dispose();
  28099. if (this._alternateSceneUbo) {
  28100. this._alternateSceneUbo.dispose();
  28101. }
  28102. // Post-processes
  28103. this.postProcessManager.dispose();
  28104. // Physics
  28105. if (this._physicsEngine) {
  28106. this.disablePhysicsEngine();
  28107. }
  28108. // Remove from engine
  28109. index = this._engine.scenes.indexOf(this);
  28110. if (index > -1) {
  28111. this._engine.scenes.splice(index, 1);
  28112. }
  28113. this._engine.wipeCaches(true);
  28114. this._isDisposed = true;
  28115. };
  28116. Object.defineProperty(Scene.prototype, "isDisposed", {
  28117. /**
  28118. * Gets if the scene is already disposed
  28119. */
  28120. get: function () {
  28121. return this._isDisposed;
  28122. },
  28123. enumerable: true,
  28124. configurable: true
  28125. });
  28126. /**
  28127. * Releases sounds & soundtracks
  28128. */
  28129. Scene.prototype.disposeSounds = function () {
  28130. if (!this._mainSoundTrack) {
  28131. return;
  28132. }
  28133. this.mainSoundTrack.dispose();
  28134. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  28135. this.soundTracks[scIndex].dispose();
  28136. }
  28137. };
  28138. /**
  28139. * Call this function to reduce memory footprint of the scene.
  28140. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  28141. */
  28142. Scene.prototype.clearCachedVertexData = function () {
  28143. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28144. var mesh = this.meshes[meshIndex];
  28145. var geometry = mesh.geometry;
  28146. if (geometry) {
  28147. geometry._indices = [];
  28148. for (var vbName in geometry._vertexBuffers) {
  28149. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  28150. continue;
  28151. }
  28152. geometry._vertexBuffers[vbName]._buffer._data = null;
  28153. }
  28154. }
  28155. }
  28156. };
  28157. /**
  28158. * This function will remove the local cached buffer data from texture.
  28159. * It will save memory but will prevent the texture from being rebuilt
  28160. */
  28161. Scene.prototype.cleanCachedTextureBuffer = function () {
  28162. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28163. var baseTexture = _a[_i];
  28164. var buffer = baseTexture._buffer;
  28165. if (buffer) {
  28166. baseTexture._buffer = null;
  28167. }
  28168. }
  28169. };
  28170. /**
  28171. * Get the world extend vectors with an optional filter
  28172. *
  28173. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28174. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28175. */
  28176. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28177. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28178. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28179. filterPredicate = filterPredicate || (function () { return true; });
  28180. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28181. mesh.computeWorldMatrix(true);
  28182. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28183. return;
  28184. }
  28185. var boundingInfo = mesh.getBoundingInfo();
  28186. var minBox = boundingInfo.boundingBox.minimumWorld;
  28187. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28188. BABYLON.Tools.CheckExtends(minBox, min, max);
  28189. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28190. });
  28191. return {
  28192. min: min,
  28193. max: max
  28194. };
  28195. };
  28196. // Picking
  28197. /**
  28198. * Creates a ray that can be used to pick in the scene
  28199. * @param x defines the x coordinate of the origin (on-screen)
  28200. * @param y defines the y coordinate of the origin (on-screen)
  28201. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28202. * @param camera defines the camera to use for the picking
  28203. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28204. * @returns a Ray
  28205. */
  28206. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28207. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28208. var result = BABYLON.Ray.Zero();
  28209. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28210. return result;
  28211. };
  28212. /**
  28213. * Creates a ray that can be used to pick in the scene
  28214. * @param x defines the x coordinate of the origin (on-screen)
  28215. * @param y defines the y coordinate of the origin (on-screen)
  28216. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28217. * @param result defines the ray where to store the picking ray
  28218. * @param camera defines the camera to use for the picking
  28219. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28220. * @returns the current scene
  28221. */
  28222. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28223. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28224. var engine = this._engine;
  28225. if (!camera) {
  28226. if (!this.activeCamera)
  28227. throw new Error("Active camera not set");
  28228. camera = this.activeCamera;
  28229. }
  28230. var cameraViewport = camera.viewport;
  28231. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28232. // Moving coordinates to local viewport world
  28233. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28234. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28235. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28236. return this;
  28237. };
  28238. /**
  28239. * Creates a ray that can be used to pick in the scene
  28240. * @param x defines the x coordinate of the origin (on-screen)
  28241. * @param y defines the y coordinate of the origin (on-screen)
  28242. * @param camera defines the camera to use for the picking
  28243. * @returns a Ray
  28244. */
  28245. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28246. var result = BABYLON.Ray.Zero();
  28247. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28248. return result;
  28249. };
  28250. /**
  28251. * Creates a ray that can be used to pick in the scene
  28252. * @param x defines the x coordinate of the origin (on-screen)
  28253. * @param y defines the y coordinate of the origin (on-screen)
  28254. * @param result defines the ray where to store the picking ray
  28255. * @param camera defines the camera to use for the picking
  28256. * @returns the current scene
  28257. */
  28258. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28259. if (!BABYLON.PickingInfo) {
  28260. return this;
  28261. }
  28262. var engine = this._engine;
  28263. if (!camera) {
  28264. if (!this.activeCamera)
  28265. throw new Error("Active camera not set");
  28266. camera = this.activeCamera;
  28267. }
  28268. var cameraViewport = camera.viewport;
  28269. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28270. var identity = BABYLON.Matrix.Identity();
  28271. // Moving coordinates to local viewport world
  28272. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28273. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28274. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28275. return this;
  28276. };
  28277. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28278. if (!BABYLON.PickingInfo) {
  28279. return null;
  28280. }
  28281. var pickingInfo = null;
  28282. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28283. var mesh = this.meshes[meshIndex];
  28284. if (predicate) {
  28285. if (!predicate(mesh)) {
  28286. continue;
  28287. }
  28288. }
  28289. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28290. continue;
  28291. }
  28292. var world = mesh.getWorldMatrix();
  28293. var ray = rayFunction(world);
  28294. var result = mesh.intersects(ray, fastCheck);
  28295. if (!result || !result.hit)
  28296. continue;
  28297. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28298. continue;
  28299. pickingInfo = result;
  28300. if (fastCheck) {
  28301. break;
  28302. }
  28303. }
  28304. return pickingInfo || new BABYLON.PickingInfo();
  28305. };
  28306. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28307. if (!BABYLON.PickingInfo) {
  28308. return null;
  28309. }
  28310. var pickingInfos = new Array();
  28311. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28312. var mesh = this.meshes[meshIndex];
  28313. if (predicate) {
  28314. if (!predicate(mesh)) {
  28315. continue;
  28316. }
  28317. }
  28318. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28319. continue;
  28320. }
  28321. var world = mesh.getWorldMatrix();
  28322. var ray = rayFunction(world);
  28323. var result = mesh.intersects(ray, false);
  28324. if (!result || !result.hit)
  28325. continue;
  28326. pickingInfos.push(result);
  28327. }
  28328. return pickingInfos;
  28329. };
  28330. /** Launch a ray to try to pick a mesh in the scene
  28331. * @param x position on screen
  28332. * @param y position on screen
  28333. * @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
  28334. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28335. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28336. * @returns a PickingInfo
  28337. */
  28338. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28339. var _this = this;
  28340. if (!BABYLON.PickingInfo) {
  28341. return null;
  28342. }
  28343. var result = this._internalPick(function (world) {
  28344. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28345. return _this._tempPickingRay;
  28346. }, predicate, fastCheck);
  28347. if (result) {
  28348. result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null);
  28349. }
  28350. return result;
  28351. };
  28352. /** Use the given ray to pick a mesh in the scene
  28353. * @param ray The ray to use to pick meshes
  28354. * @param predicate Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must have isPickable set to true
  28355. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28356. * @returns a PickingInfo
  28357. */
  28358. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28359. var _this = this;
  28360. var result = this._internalPick(function (world) {
  28361. if (!_this._pickWithRayInverseMatrix) {
  28362. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28363. }
  28364. world.invertToRef(_this._pickWithRayInverseMatrix);
  28365. if (!_this._cachedRayForTransform) {
  28366. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28367. }
  28368. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28369. return _this._cachedRayForTransform;
  28370. }, predicate, fastCheck);
  28371. if (result) {
  28372. result.ray = ray;
  28373. }
  28374. return result;
  28375. };
  28376. /**
  28377. * Launch a ray to try to pick a mesh in the scene
  28378. * @param x X position on screen
  28379. * @param y Y position on screen
  28380. * @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
  28381. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28382. * @returns an array of PickingInfo
  28383. */
  28384. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28385. var _this = this;
  28386. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28387. };
  28388. /**
  28389. * Launch a ray to try to pick a mesh in the scene
  28390. * @param ray Ray to use
  28391. * @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
  28392. * @returns an array of PickingInfo
  28393. */
  28394. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28395. var _this = this;
  28396. return this._internalMultiPick(function (world) {
  28397. if (!_this._pickWithRayInverseMatrix) {
  28398. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28399. }
  28400. world.invertToRef(_this._pickWithRayInverseMatrix);
  28401. if (!_this._cachedRayForTransform) {
  28402. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28403. }
  28404. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28405. return _this._cachedRayForTransform;
  28406. }, predicate);
  28407. };
  28408. /**
  28409. * Force the value of meshUnderPointer
  28410. * @param mesh defines the mesh to use
  28411. */
  28412. Scene.prototype.setPointerOverMesh = function (mesh) {
  28413. if (this._pointerOverMesh === mesh) {
  28414. return;
  28415. }
  28416. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28417. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28418. }
  28419. this._pointerOverMesh = mesh;
  28420. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28421. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28422. }
  28423. };
  28424. /**
  28425. * Gets the mesh under the pointer
  28426. * @returns a Mesh or null if no mesh is under the pointer
  28427. */
  28428. Scene.prototype.getPointerOverMesh = function () {
  28429. return this._pointerOverMesh;
  28430. };
  28431. // Physics
  28432. /**
  28433. * Gets the current physics engine
  28434. * @returns a PhysicsEngine or null if none attached
  28435. */
  28436. Scene.prototype.getPhysicsEngine = function () {
  28437. return this._physicsEngine;
  28438. };
  28439. /**
  28440. * Enables physics to the current scene
  28441. * @param gravity defines the scene's gravity for the physics engine
  28442. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  28443. * @return a boolean indicating if the physics engine was initialized
  28444. */
  28445. Scene.prototype.enablePhysics = function (gravity, plugin) {
  28446. if (gravity === void 0) { gravity = null; }
  28447. if (this._physicsEngine) {
  28448. return true;
  28449. }
  28450. try {
  28451. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  28452. return true;
  28453. }
  28454. catch (e) {
  28455. BABYLON.Tools.Error(e.message);
  28456. return false;
  28457. }
  28458. };
  28459. /**
  28460. * Disables and disposes the physics engine associated with the scene
  28461. */
  28462. Scene.prototype.disablePhysicsEngine = function () {
  28463. if (!this._physicsEngine) {
  28464. return;
  28465. }
  28466. this._physicsEngine.dispose();
  28467. this._physicsEngine = null;
  28468. };
  28469. /**
  28470. * Gets a boolean indicating if there is an active physics engine
  28471. * @returns a boolean indicating if there is an active physics engine
  28472. */
  28473. Scene.prototype.isPhysicsEnabled = function () {
  28474. return this._physicsEngine !== undefined;
  28475. };
  28476. /**
  28477. * Deletes a physics compound impostor
  28478. * @param compound defines the compound to delete
  28479. */
  28480. Scene.prototype.deleteCompoundImpostor = function (compound) {
  28481. var mesh = compound.parts[0].mesh;
  28482. if (mesh.physicsImpostor) {
  28483. mesh.physicsImpostor.dispose( /*true*/);
  28484. mesh.physicsImpostor = null;
  28485. }
  28486. };
  28487. // Misc.
  28488. /** @hidden */
  28489. Scene.prototype._rebuildGeometries = function () {
  28490. for (var _i = 0, _a = this.geometries; _i < _a.length; _i++) {
  28491. var geometry = _a[_i];
  28492. geometry._rebuild();
  28493. }
  28494. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28495. var mesh = _c[_b];
  28496. mesh._rebuild();
  28497. }
  28498. if (this.postProcessManager) {
  28499. this.postProcessManager._rebuild();
  28500. }
  28501. for (var _d = 0, _e = this._components; _d < _e.length; _d++) {
  28502. var component = _e[_d];
  28503. component.rebuild();
  28504. }
  28505. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  28506. var system = _g[_f];
  28507. system.rebuild();
  28508. }
  28509. };
  28510. /** @hidden */
  28511. Scene.prototype._rebuildTextures = function () {
  28512. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28513. var texture = _a[_i];
  28514. texture._rebuild();
  28515. }
  28516. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28517. };
  28518. // Tags
  28519. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  28520. if (tagsQuery === undefined) {
  28521. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  28522. return list;
  28523. }
  28524. var listByTags = [];
  28525. forEach = forEach || (function (item) { return; });
  28526. for (var i in list) {
  28527. var item = list[i];
  28528. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  28529. listByTags.push(item);
  28530. forEach(item);
  28531. }
  28532. }
  28533. return listByTags;
  28534. };
  28535. /**
  28536. * Get a list of meshes by tags
  28537. * @param tagsQuery defines the tags query to use
  28538. * @param forEach defines a predicate used to filter results
  28539. * @returns an array of Mesh
  28540. */
  28541. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  28542. return this._getByTags(this.meshes, tagsQuery, forEach);
  28543. };
  28544. /**
  28545. * Get a list of cameras by tags
  28546. * @param tagsQuery defines the tags query to use
  28547. * @param forEach defines a predicate used to filter results
  28548. * @returns an array of Camera
  28549. */
  28550. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  28551. return this._getByTags(this.cameras, tagsQuery, forEach);
  28552. };
  28553. /**
  28554. * Get a list of lights by tags
  28555. * @param tagsQuery defines the tags query to use
  28556. * @param forEach defines a predicate used to filter results
  28557. * @returns an array of Light
  28558. */
  28559. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  28560. return this._getByTags(this.lights, tagsQuery, forEach);
  28561. };
  28562. /**
  28563. * Get a list of materials by tags
  28564. * @param tagsQuery defines the tags query to use
  28565. * @param forEach defines a predicate used to filter results
  28566. * @returns an array of Material
  28567. */
  28568. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  28569. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  28570. };
  28571. /**
  28572. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  28573. * This allowed control for front to back rendering or reversly depending of the special needs.
  28574. *
  28575. * @param renderingGroupId The rendering group id corresponding to its index
  28576. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  28577. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  28578. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  28579. */
  28580. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  28581. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  28582. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  28583. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  28584. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  28585. };
  28586. /**
  28587. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  28588. *
  28589. * @param renderingGroupId The rendering group id corresponding to its index
  28590. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  28591. * @param depth Automatically clears depth between groups if true and autoClear is true.
  28592. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  28593. */
  28594. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  28595. if (depth === void 0) { depth = true; }
  28596. if (stencil === void 0) { stencil = true; }
  28597. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  28598. };
  28599. /**
  28600. * Gets the current auto clear configuration for one rendering group of the rendering
  28601. * manager.
  28602. * @param index the rendering group index to get the information for
  28603. * @returns The auto clear setup for the requested rendering group
  28604. */
  28605. Scene.prototype.getAutoClearDepthStencilSetup = function (index) {
  28606. return this._renderingManager.getAutoClearDepthStencilSetup(index);
  28607. };
  28608. /**
  28609. * Will flag all materials as dirty to trigger new shader compilation
  28610. * @param flag defines the flag used to specify which material part must be marked as dirty
  28611. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  28612. */
  28613. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  28614. if (this.blockMaterialDirtyMechanism) {
  28615. return;
  28616. }
  28617. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  28618. var material = _a[_i];
  28619. if (predicate && !predicate(material)) {
  28620. continue;
  28621. }
  28622. material.markAsDirty(flag);
  28623. }
  28624. };
  28625. /** @hidden */
  28626. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  28627. var _this = this;
  28628. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  28629. this._activeRequests.push(request);
  28630. request.onCompleteObservable.add(function (request) {
  28631. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  28632. });
  28633. return request;
  28634. };
  28635. /** @hidden */
  28636. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  28637. var _this = this;
  28638. return new Promise(function (resolve, reject) {
  28639. _this._loadFile(url, function (data) {
  28640. resolve(data);
  28641. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  28642. reject(exception);
  28643. });
  28644. });
  28645. };
  28646. // Statics
  28647. Scene._uniqueIdCounter = 0;
  28648. /** The fog is deactivated */
  28649. Scene.FOGMODE_NONE = 0;
  28650. /** The fog density is following an exponential function */
  28651. Scene.FOGMODE_EXP = 1;
  28652. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  28653. Scene.FOGMODE_EXP2 = 2;
  28654. /** The fog density is following a linear function. */
  28655. Scene.FOGMODE_LINEAR = 3;
  28656. /**
  28657. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  28658. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28659. */
  28660. Scene.MinDeltaTime = 1.0;
  28661. /**
  28662. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  28663. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28664. */
  28665. Scene.MaxDeltaTime = 1000.0;
  28666. /** The distance in pixel that you have to move to prevent some events */
  28667. Scene.DragMovementThreshold = 10; // in pixels
  28668. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  28669. Scene.LongPressDelay = 500; // in milliseconds
  28670. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  28671. Scene.DoubleClickDelay = 300; // in milliseconds
  28672. /** If you need to check double click without raising a single click at first click, enable this flag */
  28673. Scene.ExclusiveDoubleClickMode = false;
  28674. return Scene;
  28675. }(BABYLON.AbstractScene));
  28676. BABYLON.Scene = Scene;
  28677. })(BABYLON || (BABYLON = {}));
  28678. //# sourceMappingURL=babylon.scene.js.map
  28679. var BABYLON;
  28680. (function (BABYLON) {
  28681. /**
  28682. * Set of assets to keep when moving a scene into an asset container.
  28683. */
  28684. var KeepAssets = /** @class */ (function (_super) {
  28685. __extends(KeepAssets, _super);
  28686. function KeepAssets() {
  28687. return _super !== null && _super.apply(this, arguments) || this;
  28688. }
  28689. return KeepAssets;
  28690. }(BABYLON.AbstractScene));
  28691. BABYLON.KeepAssets = KeepAssets;
  28692. /**
  28693. * Container with a set of assets that can be added or removed from a scene.
  28694. */
  28695. var AssetContainer = /** @class */ (function (_super) {
  28696. __extends(AssetContainer, _super);
  28697. /**
  28698. * Instantiates an AssetContainer.
  28699. * @param scene The scene the AssetContainer belongs to.
  28700. */
  28701. function AssetContainer(scene) {
  28702. var _this = _super.call(this) || this;
  28703. _this.scene = scene;
  28704. return _this;
  28705. }
  28706. /**
  28707. * Adds all the assets from the container to the scene.
  28708. */
  28709. AssetContainer.prototype.addAllToScene = function () {
  28710. var _this = this;
  28711. this.cameras.forEach(function (o) {
  28712. _this.scene.addCamera(o);
  28713. });
  28714. this.lights.forEach(function (o) {
  28715. _this.scene.addLight(o);
  28716. });
  28717. this.meshes.forEach(function (o) {
  28718. _this.scene.addMesh(o);
  28719. });
  28720. this.skeletons.forEach(function (o) {
  28721. _this.scene.addSkeleton(o);
  28722. });
  28723. this.animations.forEach(function (o) {
  28724. _this.scene.addAnimation(o);
  28725. });
  28726. this.animationGroups.forEach(function (o) {
  28727. _this.scene.addAnimationGroup(o);
  28728. });
  28729. this.multiMaterials.forEach(function (o) {
  28730. _this.scene.addMultiMaterial(o);
  28731. });
  28732. this.materials.forEach(function (o) {
  28733. _this.scene.addMaterial(o);
  28734. });
  28735. this.morphTargetManagers.forEach(function (o) {
  28736. _this.scene.addMorphTargetManager(o);
  28737. });
  28738. this.geometries.forEach(function (o) {
  28739. _this.scene.addGeometry(o);
  28740. });
  28741. this.transformNodes.forEach(function (o) {
  28742. _this.scene.addTransformNode(o);
  28743. });
  28744. this.actionManagers.forEach(function (o) {
  28745. _this.scene.addActionManager(o);
  28746. });
  28747. this.sounds.forEach(function (o) {
  28748. o.play();
  28749. o.autoplay = true;
  28750. _this.scene.mainSoundTrack.AddSound(o);
  28751. });
  28752. this.textures.forEach(function (o) {
  28753. _this.scene.addTexture(o);
  28754. });
  28755. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  28756. var component = _a[_i];
  28757. component.addFromContainer(this.scene);
  28758. }
  28759. };
  28760. /**
  28761. * Removes all the assets in the container from the scene
  28762. */
  28763. AssetContainer.prototype.removeAllFromScene = function () {
  28764. var _this = this;
  28765. this.cameras.forEach(function (o) {
  28766. _this.scene.removeCamera(o);
  28767. });
  28768. this.lights.forEach(function (o) {
  28769. _this.scene.removeLight(o);
  28770. });
  28771. this.meshes.forEach(function (o) {
  28772. _this.scene.removeMesh(o);
  28773. });
  28774. this.skeletons.forEach(function (o) {
  28775. _this.scene.removeSkeleton(o);
  28776. });
  28777. this.animations.forEach(function (o) {
  28778. _this.scene.removeAnimation(o);
  28779. });
  28780. this.animationGroups.forEach(function (o) {
  28781. _this.scene.removeAnimationGroup(o);
  28782. });
  28783. this.multiMaterials.forEach(function (o) {
  28784. _this.scene.removeMultiMaterial(o);
  28785. });
  28786. this.materials.forEach(function (o) {
  28787. _this.scene.removeMaterial(o);
  28788. });
  28789. this.morphTargetManagers.forEach(function (o) {
  28790. _this.scene.removeMorphTargetManager(o);
  28791. });
  28792. this.geometries.forEach(function (o) {
  28793. _this.scene.removeGeometry(o);
  28794. });
  28795. this.transformNodes.forEach(function (o) {
  28796. _this.scene.removeTransformNode(o);
  28797. });
  28798. this.actionManagers.forEach(function (o) {
  28799. _this.scene.removeActionManager(o);
  28800. });
  28801. this.sounds.forEach(function (o) {
  28802. o.stop();
  28803. o.autoplay = false;
  28804. _this.scene.mainSoundTrack.RemoveSound(o);
  28805. });
  28806. this.textures.forEach(function (o) {
  28807. _this.scene.removeTexture(o);
  28808. });
  28809. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  28810. var component = _a[_i];
  28811. component.removeFromContainer(this.scene);
  28812. }
  28813. };
  28814. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  28815. if (!sourceAssets) {
  28816. return;
  28817. }
  28818. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  28819. var asset = sourceAssets_1[_i];
  28820. var move = true;
  28821. if (keepAssets) {
  28822. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  28823. var keepAsset = keepAssets_1[_a];
  28824. if (asset === keepAsset) {
  28825. move = false;
  28826. break;
  28827. }
  28828. }
  28829. }
  28830. if (move) {
  28831. targetAssets.push(asset);
  28832. }
  28833. }
  28834. };
  28835. /**
  28836. * Removes all the assets contained in the scene and adds them to the container.
  28837. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  28838. */
  28839. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  28840. if (keepAssets === undefined) {
  28841. keepAssets = new KeepAssets();
  28842. }
  28843. for (var key in this) {
  28844. if (this.hasOwnProperty(key)) {
  28845. this[key] = this[key] || [];
  28846. this._moveAssets(this.scene[key], this[key], keepAssets[key]);
  28847. }
  28848. }
  28849. this.removeAllFromScene();
  28850. };
  28851. /**
  28852. * 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.
  28853. * @returns the root mesh
  28854. */
  28855. AssetContainer.prototype.createRootMesh = function () {
  28856. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  28857. this.meshes.forEach(function (m) {
  28858. if (!m.parent) {
  28859. rootMesh.addChild(m);
  28860. }
  28861. });
  28862. this.meshes.unshift(rootMesh);
  28863. return rootMesh;
  28864. };
  28865. return AssetContainer;
  28866. }(BABYLON.AbstractScene));
  28867. BABYLON.AssetContainer = AssetContainer;
  28868. })(BABYLON || (BABYLON = {}));
  28869. //# sourceMappingURL=babylon.assetContainer.js.map
  28870. var BABYLON;
  28871. (function (BABYLON) {
  28872. var Buffer = /** @class */ (function () {
  28873. /**
  28874. * Constructor
  28875. * @param engine the engine
  28876. * @param data the data to use for this buffer
  28877. * @param updatable whether the data is updatable
  28878. * @param stride the stride (optional)
  28879. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  28880. * @param instanced whether the buffer is instanced (optional)
  28881. * @param useBytes set to true if the stride in in bytes (optional)
  28882. */
  28883. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  28884. if (stride === void 0) { stride = 0; }
  28885. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  28886. if (instanced === void 0) { instanced = false; }
  28887. if (useBytes === void 0) { useBytes = false; }
  28888. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  28889. this._engine = engine.getScene().getEngine();
  28890. }
  28891. else {
  28892. this._engine = engine;
  28893. }
  28894. this._updatable = updatable;
  28895. this._instanced = instanced;
  28896. this._data = data;
  28897. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  28898. if (!postponeInternalCreation) { // by default
  28899. this.create();
  28900. }
  28901. }
  28902. /**
  28903. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  28904. * @param kind defines the vertex buffer kind (position, normal, etc.)
  28905. * @param offset defines offset in the buffer (0 by default)
  28906. * @param size defines the size in floats of attributes (position is 3 for instance)
  28907. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  28908. * @param instanced defines if the vertex buffer contains indexed data
  28909. * @param useBytes defines if the offset and stride are in bytes
  28910. * @returns the new vertex buffer
  28911. */
  28912. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  28913. if (useBytes === void 0) { useBytes = false; }
  28914. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  28915. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  28916. // a lot of these parameters are ignored as they are overriden by the buffer
  28917. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  28918. };
  28919. // Properties
  28920. Buffer.prototype.isUpdatable = function () {
  28921. return this._updatable;
  28922. };
  28923. Buffer.prototype.getData = function () {
  28924. return this._data;
  28925. };
  28926. Buffer.prototype.getBuffer = function () {
  28927. return this._buffer;
  28928. };
  28929. /**
  28930. * Gets the stride in float32 units (i.e. byte stride / 4).
  28931. * May not be an integer if the byte stride is not divisible by 4.
  28932. * DEPRECATED. Use byteStride instead.
  28933. * @returns the stride in float32 units
  28934. */
  28935. Buffer.prototype.getStrideSize = function () {
  28936. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  28937. };
  28938. // Methods
  28939. Buffer.prototype.create = function (data) {
  28940. if (data === void 0) { data = null; }
  28941. if (!data && this._buffer) {
  28942. return; // nothing to do
  28943. }
  28944. data = data || this._data;
  28945. if (!data) {
  28946. return;
  28947. }
  28948. if (!this._buffer) { // create buffer
  28949. if (this._updatable) {
  28950. this._buffer = this._engine.createDynamicVertexBuffer(data);
  28951. this._data = data;
  28952. }
  28953. else {
  28954. this._buffer = this._engine.createVertexBuffer(data);
  28955. }
  28956. }
  28957. else if (this._updatable) { // update buffer
  28958. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  28959. this._data = data;
  28960. }
  28961. };
  28962. /** @hidden */
  28963. Buffer.prototype._rebuild = function () {
  28964. this._buffer = null;
  28965. this.create(this._data);
  28966. };
  28967. Buffer.prototype.update = function (data) {
  28968. this.create(data);
  28969. };
  28970. /**
  28971. * Updates the data directly.
  28972. * @param data the new data
  28973. * @param offset the new offset
  28974. * @param vertexCount the vertex count (optional)
  28975. * @param useBytes set to true if the offset is in bytes
  28976. */
  28977. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  28978. if (useBytes === void 0) { useBytes = false; }
  28979. if (!this._buffer) {
  28980. return;
  28981. }
  28982. if (this._updatable) { // update buffer
  28983. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  28984. this._data = null;
  28985. }
  28986. };
  28987. Buffer.prototype.dispose = function () {
  28988. if (!this._buffer) {
  28989. return;
  28990. }
  28991. if (this._engine._releaseBuffer(this._buffer)) {
  28992. this._buffer = null;
  28993. }
  28994. };
  28995. return Buffer;
  28996. }());
  28997. BABYLON.Buffer = Buffer;
  28998. })(BABYLON || (BABYLON = {}));
  28999. //# sourceMappingURL=babylon.buffer.js.map
  29000. var BABYLON;
  29001. (function (BABYLON) {
  29002. var VertexBuffer = /** @class */ (function () {
  29003. /**
  29004. * Constructor
  29005. * @param engine the engine
  29006. * @param data the data to use for this vertex buffer
  29007. * @param kind the vertex buffer kind
  29008. * @param updatable whether the data is updatable
  29009. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29010. * @param stride the stride (optional)
  29011. * @param instanced whether the buffer is instanced (optional)
  29012. * @param offset the offset of the data (optional)
  29013. * @param size the number of components (optional)
  29014. * @param type the type of the component (optional)
  29015. * @param normalized whether the data contains normalized data (optional)
  29016. * @param useBytes set to true if stride and offset are in bytes (optional)
  29017. */
  29018. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29019. if (normalized === void 0) { normalized = false; }
  29020. if (useBytes === void 0) { useBytes = false; }
  29021. if (data instanceof BABYLON.Buffer) {
  29022. this._buffer = data;
  29023. this._ownsBuffer = false;
  29024. }
  29025. else {
  29026. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29027. this._ownsBuffer = true;
  29028. }
  29029. this._kind = kind;
  29030. if (type == undefined) {
  29031. var data_1 = this.getData();
  29032. this.type = VertexBuffer.FLOAT;
  29033. if (data_1 instanceof Int8Array)
  29034. this.type = VertexBuffer.BYTE;
  29035. else if (data_1 instanceof Uint8Array)
  29036. this.type = VertexBuffer.UNSIGNED_BYTE;
  29037. else if (data_1 instanceof Int16Array)
  29038. this.type = VertexBuffer.SHORT;
  29039. else if (data_1 instanceof Uint16Array)
  29040. this.type = VertexBuffer.UNSIGNED_SHORT;
  29041. else if (data_1 instanceof Int32Array)
  29042. this.type = VertexBuffer.INT;
  29043. else if (data_1 instanceof Uint32Array)
  29044. this.type = VertexBuffer.UNSIGNED_INT;
  29045. }
  29046. else {
  29047. this.type = type;
  29048. }
  29049. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29050. if (useBytes) {
  29051. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29052. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29053. this.byteOffset = offset || 0;
  29054. }
  29055. else {
  29056. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29057. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29058. this.byteOffset = (offset || 0) * typeByteLength;
  29059. }
  29060. this.normalized = normalized;
  29061. this._instanced = instanced !== undefined ? instanced : false;
  29062. this._instanceDivisor = instanced ? 1 : 0;
  29063. }
  29064. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29065. /**
  29066. * Gets or sets the instance divisor when in instanced mode
  29067. */
  29068. get: function () {
  29069. return this._instanceDivisor;
  29070. },
  29071. set: function (value) {
  29072. this._instanceDivisor = value;
  29073. if (value == 0) {
  29074. this._instanced = false;
  29075. }
  29076. else {
  29077. this._instanced = true;
  29078. }
  29079. },
  29080. enumerable: true,
  29081. configurable: true
  29082. });
  29083. /** @hidden */
  29084. VertexBuffer.prototype._rebuild = function () {
  29085. if (!this._buffer) {
  29086. return;
  29087. }
  29088. this._buffer._rebuild();
  29089. };
  29090. /**
  29091. * Returns the kind of the VertexBuffer (string).
  29092. */
  29093. VertexBuffer.prototype.getKind = function () {
  29094. return this._kind;
  29095. };
  29096. // Properties
  29097. /**
  29098. * Boolean : is the VertexBuffer updatable ?
  29099. */
  29100. VertexBuffer.prototype.isUpdatable = function () {
  29101. return this._buffer.isUpdatable();
  29102. };
  29103. /**
  29104. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29105. */
  29106. VertexBuffer.prototype.getData = function () {
  29107. return this._buffer.getData();
  29108. };
  29109. /**
  29110. * Returns the WebGLBuffer associated to the VertexBuffer.
  29111. */
  29112. VertexBuffer.prototype.getBuffer = function () {
  29113. return this._buffer.getBuffer();
  29114. };
  29115. /**
  29116. * Returns the stride as a multiple of the type byte length.
  29117. * DEPRECATED. Use byteStride instead.
  29118. */
  29119. VertexBuffer.prototype.getStrideSize = function () {
  29120. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29121. };
  29122. /**
  29123. * Returns the offset as a multiple of the type byte length.
  29124. * DEPRECATED. Use byteOffset instead.
  29125. */
  29126. VertexBuffer.prototype.getOffset = function () {
  29127. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29128. };
  29129. /**
  29130. * Returns the number of components per vertex attribute (integer).
  29131. */
  29132. VertexBuffer.prototype.getSize = function () {
  29133. return this._size;
  29134. };
  29135. /**
  29136. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29137. */
  29138. VertexBuffer.prototype.getIsInstanced = function () {
  29139. return this._instanced;
  29140. };
  29141. /**
  29142. * Returns the instancing divisor, zero for non-instanced (integer).
  29143. */
  29144. VertexBuffer.prototype.getInstanceDivisor = function () {
  29145. return this._instanceDivisor;
  29146. };
  29147. // Methods
  29148. /**
  29149. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29150. * Returns the created WebGLBuffer.
  29151. */
  29152. VertexBuffer.prototype.create = function (data) {
  29153. return this._buffer.create(data);
  29154. };
  29155. /**
  29156. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29157. * This function will create a new buffer if the current one is not updatable
  29158. * Returns the updated WebGLBuffer.
  29159. */
  29160. VertexBuffer.prototype.update = function (data) {
  29161. return this._buffer.update(data);
  29162. };
  29163. /**
  29164. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29165. * Returns the directly updated WebGLBuffer.
  29166. * @param data the new data
  29167. * @param offset the new offset
  29168. * @param useBytes set to true if the offset is in bytes
  29169. */
  29170. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29171. if (useBytes === void 0) { useBytes = false; }
  29172. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29173. };
  29174. /**
  29175. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29176. */
  29177. VertexBuffer.prototype.dispose = function () {
  29178. if (this._ownsBuffer) {
  29179. this._buffer.dispose();
  29180. }
  29181. };
  29182. /**
  29183. * Enumerates each value of this vertex buffer as numbers.
  29184. * @param count the number of values to enumerate
  29185. * @param callback the callback function called for each value
  29186. */
  29187. VertexBuffer.prototype.forEach = function (count, callback) {
  29188. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29189. };
  29190. Object.defineProperty(VertexBuffer, "PositionKind", {
  29191. get: function () {
  29192. return VertexBuffer._PositionKind;
  29193. },
  29194. enumerable: true,
  29195. configurable: true
  29196. });
  29197. Object.defineProperty(VertexBuffer, "NormalKind", {
  29198. get: function () {
  29199. return VertexBuffer._NormalKind;
  29200. },
  29201. enumerable: true,
  29202. configurable: true
  29203. });
  29204. Object.defineProperty(VertexBuffer, "TangentKind", {
  29205. get: function () {
  29206. return VertexBuffer._TangentKind;
  29207. },
  29208. enumerable: true,
  29209. configurable: true
  29210. });
  29211. Object.defineProperty(VertexBuffer, "UVKind", {
  29212. get: function () {
  29213. return VertexBuffer._UVKind;
  29214. },
  29215. enumerable: true,
  29216. configurable: true
  29217. });
  29218. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29219. get: function () {
  29220. return VertexBuffer._UV2Kind;
  29221. },
  29222. enumerable: true,
  29223. configurable: true
  29224. });
  29225. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29226. get: function () {
  29227. return VertexBuffer._UV3Kind;
  29228. },
  29229. enumerable: true,
  29230. configurable: true
  29231. });
  29232. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29233. get: function () {
  29234. return VertexBuffer._UV4Kind;
  29235. },
  29236. enumerable: true,
  29237. configurable: true
  29238. });
  29239. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29240. get: function () {
  29241. return VertexBuffer._UV5Kind;
  29242. },
  29243. enumerable: true,
  29244. configurable: true
  29245. });
  29246. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29247. get: function () {
  29248. return VertexBuffer._UV6Kind;
  29249. },
  29250. enumerable: true,
  29251. configurable: true
  29252. });
  29253. Object.defineProperty(VertexBuffer, "ColorKind", {
  29254. get: function () {
  29255. return VertexBuffer._ColorKind;
  29256. },
  29257. enumerable: true,
  29258. configurable: true
  29259. });
  29260. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29261. get: function () {
  29262. return VertexBuffer._MatricesIndicesKind;
  29263. },
  29264. enumerable: true,
  29265. configurable: true
  29266. });
  29267. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29268. get: function () {
  29269. return VertexBuffer._MatricesWeightsKind;
  29270. },
  29271. enumerable: true,
  29272. configurable: true
  29273. });
  29274. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29275. get: function () {
  29276. return VertexBuffer._MatricesIndicesExtraKind;
  29277. },
  29278. enumerable: true,
  29279. configurable: true
  29280. });
  29281. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29282. get: function () {
  29283. return VertexBuffer._MatricesWeightsExtraKind;
  29284. },
  29285. enumerable: true,
  29286. configurable: true
  29287. });
  29288. /**
  29289. * Deduces the stride given a kind.
  29290. * @param kind The kind string to deduce
  29291. * @returns The deduced stride
  29292. */
  29293. VertexBuffer.DeduceStride = function (kind) {
  29294. switch (kind) {
  29295. case VertexBuffer.UVKind:
  29296. case VertexBuffer.UV2Kind:
  29297. case VertexBuffer.UV3Kind:
  29298. case VertexBuffer.UV4Kind:
  29299. case VertexBuffer.UV5Kind:
  29300. case VertexBuffer.UV6Kind:
  29301. return 2;
  29302. case VertexBuffer.NormalKind:
  29303. case VertexBuffer.PositionKind:
  29304. return 3;
  29305. case VertexBuffer.ColorKind:
  29306. case VertexBuffer.MatricesIndicesKind:
  29307. case VertexBuffer.MatricesIndicesExtraKind:
  29308. case VertexBuffer.MatricesWeightsKind:
  29309. case VertexBuffer.MatricesWeightsExtraKind:
  29310. case VertexBuffer.TangentKind:
  29311. return 4;
  29312. default:
  29313. throw new Error("Invalid kind '" + kind + "'");
  29314. }
  29315. };
  29316. /**
  29317. * Gets the byte length of the given type.
  29318. * @param type the type
  29319. * @returns the number of bytes
  29320. */
  29321. VertexBuffer.GetTypeByteLength = function (type) {
  29322. switch (type) {
  29323. case VertexBuffer.BYTE:
  29324. case VertexBuffer.UNSIGNED_BYTE:
  29325. return 1;
  29326. case VertexBuffer.SHORT:
  29327. case VertexBuffer.UNSIGNED_SHORT:
  29328. return 2;
  29329. case VertexBuffer.INT:
  29330. case VertexBuffer.FLOAT:
  29331. return 4;
  29332. default:
  29333. throw new Error("Invalid type '" + type + "'");
  29334. }
  29335. };
  29336. /**
  29337. * Enumerates each value of the given parameters as numbers.
  29338. * @param data the data to enumerate
  29339. * @param byteOffset the byte offset of the data
  29340. * @param byteStride the byte stride of the data
  29341. * @param componentCount the number of components per element
  29342. * @param componentType the type of the component
  29343. * @param count the total number of components
  29344. * @param normalized whether the data is normalized
  29345. * @param callback the callback function called for each value
  29346. */
  29347. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  29348. if (data instanceof Array) {
  29349. var offset = byteOffset / 4;
  29350. var stride = byteStride / 4;
  29351. for (var index = 0; index < count; index += componentCount) {
  29352. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29353. callback(data[offset + componentIndex], index + componentIndex);
  29354. }
  29355. offset += stride;
  29356. }
  29357. }
  29358. else {
  29359. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  29360. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  29361. for (var index = 0; index < count; index += componentCount) {
  29362. var componentByteOffset = byteOffset;
  29363. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29364. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  29365. callback(value, index + componentIndex);
  29366. componentByteOffset += componentByteLength;
  29367. }
  29368. byteOffset += byteStride;
  29369. }
  29370. }
  29371. };
  29372. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  29373. switch (type) {
  29374. case VertexBuffer.BYTE: {
  29375. var value = dataView.getInt8(byteOffset);
  29376. if (normalized) {
  29377. value = Math.max(value / 127, -1);
  29378. }
  29379. return value;
  29380. }
  29381. case VertexBuffer.UNSIGNED_BYTE: {
  29382. var value = dataView.getUint8(byteOffset);
  29383. if (normalized) {
  29384. value = value / 255;
  29385. }
  29386. return value;
  29387. }
  29388. case VertexBuffer.SHORT: {
  29389. var value = dataView.getInt16(byteOffset, true);
  29390. if (normalized) {
  29391. value = Math.max(value / 16383, -1);
  29392. }
  29393. return value;
  29394. }
  29395. case VertexBuffer.UNSIGNED_SHORT: {
  29396. var value = dataView.getUint16(byteOffset, true);
  29397. if (normalized) {
  29398. value = value / 65535;
  29399. }
  29400. return value;
  29401. }
  29402. case VertexBuffer.FLOAT: {
  29403. return dataView.getFloat32(byteOffset, true);
  29404. }
  29405. default: {
  29406. throw new Error("Invalid component type " + type);
  29407. }
  29408. }
  29409. };
  29410. /**
  29411. * The byte type.
  29412. */
  29413. VertexBuffer.BYTE = 5120;
  29414. /**
  29415. * The unsigned byte type.
  29416. */
  29417. VertexBuffer.UNSIGNED_BYTE = 5121;
  29418. /**
  29419. * The short type.
  29420. */
  29421. VertexBuffer.SHORT = 5122;
  29422. /**
  29423. * The unsigned short type.
  29424. */
  29425. VertexBuffer.UNSIGNED_SHORT = 5123;
  29426. /**
  29427. * The integer type.
  29428. */
  29429. VertexBuffer.INT = 5124;
  29430. /**
  29431. * The unsigned integer type.
  29432. */
  29433. VertexBuffer.UNSIGNED_INT = 5125;
  29434. /**
  29435. * The float type.
  29436. */
  29437. VertexBuffer.FLOAT = 5126;
  29438. // Enums
  29439. VertexBuffer._PositionKind = "position";
  29440. VertexBuffer._NormalKind = "normal";
  29441. VertexBuffer._TangentKind = "tangent";
  29442. VertexBuffer._UVKind = "uv";
  29443. VertexBuffer._UV2Kind = "uv2";
  29444. VertexBuffer._UV3Kind = "uv3";
  29445. VertexBuffer._UV4Kind = "uv4";
  29446. VertexBuffer._UV5Kind = "uv5";
  29447. VertexBuffer._UV6Kind = "uv6";
  29448. VertexBuffer._ColorKind = "color";
  29449. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  29450. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  29451. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  29452. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  29453. return VertexBuffer;
  29454. }());
  29455. BABYLON.VertexBuffer = VertexBuffer;
  29456. })(BABYLON || (BABYLON = {}));
  29457. //# sourceMappingURL=babylon.vertexBuffer.js.map
  29458. //# sourceMappingURL=babylon.internalTextureLoader.js.map
  29459. var BABYLON;
  29460. (function (BABYLON) {
  29461. /**
  29462. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  29463. */
  29464. var DummyInternalTextureTracker = /** @class */ (function () {
  29465. function DummyInternalTextureTracker() {
  29466. /**
  29467. * Gets or set the previous tracker in the list
  29468. */
  29469. this.previous = null;
  29470. /**
  29471. * Gets or set the next tracker in the list
  29472. */
  29473. this.next = null;
  29474. }
  29475. return DummyInternalTextureTracker;
  29476. }());
  29477. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  29478. })(BABYLON || (BABYLON = {}));
  29479. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  29480. var BABYLON;
  29481. (function (BABYLON) {
  29482. /**
  29483. * Class used to store data associated with WebGL texture data for the engine
  29484. * This class should not be used directly
  29485. */
  29486. var InternalTexture = /** @class */ (function () {
  29487. /**
  29488. * Creates a new InternalTexture
  29489. * @param engine defines the engine to use
  29490. * @param dataSource defines the type of data that will be used
  29491. */
  29492. function InternalTexture(engine, dataSource) {
  29493. /**
  29494. * Observable called when the texture is loaded
  29495. */
  29496. this.onLoadedObservable = new BABYLON.Observable();
  29497. /**
  29498. * Gets or set the previous tracker in the list
  29499. */
  29500. this.previous = null;
  29501. /**
  29502. * Gets or set the next tracker in the list
  29503. */
  29504. this.next = null;
  29505. // Private
  29506. /** @hidden */
  29507. this._initialSlot = -1;
  29508. /** @hidden */
  29509. this._designatedSlot = -1;
  29510. /** @hidden */
  29511. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  29512. /** @hidden */
  29513. this._comparisonFunction = 0;
  29514. /** @hidden */
  29515. this._sphericalPolynomial = null;
  29516. /** @hidden */
  29517. this._lodGenerationScale = 0;
  29518. /** @hidden */
  29519. this._lodGenerationOffset = 0;
  29520. /** @hidden */
  29521. this._isRGBD = false;
  29522. /** @hidden */
  29523. this._references = 1;
  29524. this._engine = engine;
  29525. this._dataSource = dataSource;
  29526. this._webGLTexture = engine._createTexture();
  29527. }
  29528. /**
  29529. * Gets the Engine the texture belongs to.
  29530. * @returns The babylon engine
  29531. */
  29532. InternalTexture.prototype.getEngine = function () {
  29533. return this._engine;
  29534. };
  29535. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  29536. /**
  29537. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  29538. */
  29539. get: function () {
  29540. return this._dataSource;
  29541. },
  29542. enumerable: true,
  29543. configurable: true
  29544. });
  29545. /**
  29546. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  29547. */
  29548. InternalTexture.prototype.incrementReferences = function () {
  29549. this._references++;
  29550. };
  29551. /**
  29552. * Change the size of the texture (not the size of the content)
  29553. * @param width defines the new width
  29554. * @param height defines the new height
  29555. * @param depth defines the new depth (1 by default)
  29556. */
  29557. InternalTexture.prototype.updateSize = function (width, height, depth) {
  29558. if (depth === void 0) { depth = 1; }
  29559. this.width = width;
  29560. this.height = height;
  29561. this.depth = depth;
  29562. this.baseWidth = width;
  29563. this.baseHeight = height;
  29564. this.baseDepth = depth;
  29565. this._size = width * height * depth;
  29566. };
  29567. /** @hidden */
  29568. InternalTexture.prototype._rebuild = function () {
  29569. var _this = this;
  29570. var proxy;
  29571. this.isReady = false;
  29572. this._cachedCoordinatesMode = null;
  29573. this._cachedWrapU = null;
  29574. this._cachedWrapV = null;
  29575. this._cachedAnisotropicFilteringLevel = null;
  29576. switch (this._dataSource) {
  29577. case InternalTexture.DATASOURCE_TEMP:
  29578. return;
  29579. case InternalTexture.DATASOURCE_URL:
  29580. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  29581. _this.isReady = true;
  29582. }, null, this._buffer, undefined, this.format);
  29583. proxy._swapAndDie(this);
  29584. return;
  29585. case InternalTexture.DATASOURCE_RAW:
  29586. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29587. proxy._swapAndDie(this);
  29588. this.isReady = true;
  29589. return;
  29590. case InternalTexture.DATASOURCE_RAW3D:
  29591. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29592. proxy._swapAndDie(this);
  29593. this.isReady = true;
  29594. return;
  29595. case InternalTexture.DATASOURCE_DYNAMIC:
  29596. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  29597. proxy._swapAndDie(this);
  29598. // The engine will make sure to update content so no need to flag it as isReady = true
  29599. return;
  29600. case InternalTexture.DATASOURCE_RENDERTARGET:
  29601. var options = new BABYLON.RenderTargetCreationOptions();
  29602. options.generateDepthBuffer = this._generateDepthBuffer;
  29603. options.generateMipMaps = this.generateMipMaps;
  29604. options.generateStencilBuffer = this._generateStencilBuffer;
  29605. options.samplingMode = this.samplingMode;
  29606. options.type = this.type;
  29607. if (this.isCube) {
  29608. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  29609. }
  29610. else {
  29611. var size = {
  29612. width: this.width,
  29613. height: this.height
  29614. };
  29615. proxy = this._engine.createRenderTargetTexture(size, options);
  29616. }
  29617. proxy._swapAndDie(this);
  29618. this.isReady = true;
  29619. return;
  29620. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  29621. var depthTextureOptions = {
  29622. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  29623. comparisonFunction: this._comparisonFunction,
  29624. generateStencil: this._generateStencilBuffer,
  29625. isCube: this.isCube
  29626. };
  29627. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  29628. proxy._swapAndDie(this);
  29629. this.isReady = true;
  29630. return;
  29631. case InternalTexture.DATASOURCE_CUBE:
  29632. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  29633. _this.isReady = true;
  29634. }, null, this.format, this._extension);
  29635. proxy._swapAndDie(this);
  29636. return;
  29637. case InternalTexture.DATASOURCE_CUBERAW:
  29638. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29639. proxy._swapAndDie(this);
  29640. this.isReady = true;
  29641. return;
  29642. case InternalTexture.DATASOURCE_CUBERAW_RGBD:
  29643. proxy = this._engine.createRawCubeTexture(null, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29644. BABYLON.RawCubeTexture._UpdateRGBDAsync(proxy, this._bufferViewArrayArray, this._sphericalPolynomial, this._lodGenerationScale, this._lodGenerationOffset).then(function () {
  29645. _this.isReady = true;
  29646. });
  29647. proxy._swapAndDie(this);
  29648. return;
  29649. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  29650. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  29651. if (proxy) {
  29652. proxy._swapAndDie(_this);
  29653. }
  29654. _this.isReady = true;
  29655. }, null, this.format, this._extension);
  29656. proxy._sphericalPolynomial = this._sphericalPolynomial;
  29657. return;
  29658. }
  29659. };
  29660. /** @hidden */
  29661. InternalTexture.prototype._swapAndDie = function (target) {
  29662. target._webGLTexture = this._webGLTexture;
  29663. if (this._framebuffer) {
  29664. target._framebuffer = this._framebuffer;
  29665. }
  29666. if (this._depthStencilBuffer) {
  29667. target._depthStencilBuffer = this._depthStencilBuffer;
  29668. }
  29669. if (this._lodTextureHigh) {
  29670. if (target._lodTextureHigh) {
  29671. target._lodTextureHigh.dispose();
  29672. }
  29673. target._lodTextureHigh = this._lodTextureHigh;
  29674. }
  29675. if (this._lodTextureMid) {
  29676. if (target._lodTextureMid) {
  29677. target._lodTextureMid.dispose();
  29678. }
  29679. target._lodTextureMid = this._lodTextureMid;
  29680. }
  29681. if (this._lodTextureLow) {
  29682. if (target._lodTextureLow) {
  29683. target._lodTextureLow.dispose();
  29684. }
  29685. target._lodTextureLow = this._lodTextureLow;
  29686. }
  29687. var cache = this._engine.getLoadedTexturesCache();
  29688. var index = cache.indexOf(this);
  29689. if (index !== -1) {
  29690. cache.splice(index, 1);
  29691. }
  29692. };
  29693. /**
  29694. * Dispose the current allocated resources
  29695. */
  29696. InternalTexture.prototype.dispose = function () {
  29697. if (!this._webGLTexture) {
  29698. return;
  29699. }
  29700. this._references--;
  29701. if (this._references === 0) {
  29702. this._engine._releaseTexture(this);
  29703. this._webGLTexture = null;
  29704. this.previous = null;
  29705. this.next = null;
  29706. }
  29707. };
  29708. /**
  29709. * The source of the texture data is unknown
  29710. */
  29711. InternalTexture.DATASOURCE_UNKNOWN = 0;
  29712. /**
  29713. * Texture data comes from an URL
  29714. */
  29715. InternalTexture.DATASOURCE_URL = 1;
  29716. /**
  29717. * Texture data is only used for temporary storage
  29718. */
  29719. InternalTexture.DATASOURCE_TEMP = 2;
  29720. /**
  29721. * Texture data comes from raw data (ArrayBuffer)
  29722. */
  29723. InternalTexture.DATASOURCE_RAW = 3;
  29724. /**
  29725. * Texture content is dynamic (video or dynamic texture)
  29726. */
  29727. InternalTexture.DATASOURCE_DYNAMIC = 4;
  29728. /**
  29729. * Texture content is generated by rendering to it
  29730. */
  29731. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  29732. /**
  29733. * Texture content is part of a multi render target process
  29734. */
  29735. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  29736. /**
  29737. * Texture data comes from a cube data file
  29738. */
  29739. InternalTexture.DATASOURCE_CUBE = 7;
  29740. /**
  29741. * Texture data comes from a raw cube data
  29742. */
  29743. InternalTexture.DATASOURCE_CUBERAW = 8;
  29744. /**
  29745. * Texture data come from a prefiltered cube data file
  29746. */
  29747. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  29748. /**
  29749. * Texture content is raw 3D data
  29750. */
  29751. InternalTexture.DATASOURCE_RAW3D = 10;
  29752. /**
  29753. * Texture content is a depth texture
  29754. */
  29755. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  29756. /**
  29757. * Texture data comes from a raw cube data encoded with RGBD
  29758. */
  29759. InternalTexture.DATASOURCE_CUBERAW_RGBD = 12;
  29760. return InternalTexture;
  29761. }());
  29762. BABYLON.InternalTexture = InternalTexture;
  29763. })(BABYLON || (BABYLON = {}));
  29764. //# sourceMappingURL=babylon.internalTexture.js.map
  29765. var BABYLON;
  29766. (function (BABYLON) {
  29767. var BaseTexture = /** @class */ (function () {
  29768. function BaseTexture(scene) {
  29769. this._hasAlpha = false;
  29770. this.getAlphaFromRGB = false;
  29771. this.level = 1;
  29772. this.coordinatesIndex = 0;
  29773. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  29774. /**
  29775. * | Value | Type | Description |
  29776. * | ----- | ------------------ | ----------- |
  29777. * | 0 | CLAMP_ADDRESSMODE | |
  29778. * | 1 | WRAP_ADDRESSMODE | |
  29779. * | 2 | MIRROR_ADDRESSMODE | |
  29780. */
  29781. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  29782. /**
  29783. * | Value | Type | Description |
  29784. * | ----- | ------------------ | ----------- |
  29785. * | 0 | CLAMP_ADDRESSMODE | |
  29786. * | 1 | WRAP_ADDRESSMODE | |
  29787. * | 2 | MIRROR_ADDRESSMODE | |
  29788. */
  29789. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  29790. /**
  29791. * | Value | Type | Description |
  29792. * | ----- | ------------------ | ----------- |
  29793. * | 0 | CLAMP_ADDRESSMODE | |
  29794. * | 1 | WRAP_ADDRESSMODE | |
  29795. * | 2 | MIRROR_ADDRESSMODE | |
  29796. */
  29797. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  29798. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  29799. this.isCube = false;
  29800. this.is3D = false;
  29801. this.gammaSpace = true;
  29802. this.invertZ = false;
  29803. this.lodLevelInAlpha = false;
  29804. this.isRenderTarget = false;
  29805. this.animations = new Array();
  29806. /**
  29807. * An event triggered when the texture is disposed.
  29808. */
  29809. this.onDisposeObservable = new BABYLON.Observable();
  29810. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  29811. this._cachedSize = BABYLON.Size.Zero();
  29812. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  29813. if (this._scene) {
  29814. this._scene.textures.push(this);
  29815. }
  29816. this._uid = null;
  29817. }
  29818. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  29819. get: function () {
  29820. return this._hasAlpha;
  29821. },
  29822. set: function (value) {
  29823. if (this._hasAlpha === value) {
  29824. return;
  29825. }
  29826. this._hasAlpha = value;
  29827. if (this._scene) {
  29828. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  29829. }
  29830. },
  29831. enumerable: true,
  29832. configurable: true
  29833. });
  29834. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  29835. get: function () {
  29836. return this._coordinatesMode;
  29837. },
  29838. /**
  29839. * How a texture is mapped.
  29840. *
  29841. * | Value | Type | Description |
  29842. * | ----- | ----------------------------------- | ----------- |
  29843. * | 0 | EXPLICIT_MODE | |
  29844. * | 1 | SPHERICAL_MODE | |
  29845. * | 2 | PLANAR_MODE | |
  29846. * | 3 | CUBIC_MODE | |
  29847. * | 4 | PROJECTION_MODE | |
  29848. * | 5 | SKYBOX_MODE | |
  29849. * | 6 | INVCUBIC_MODE | |
  29850. * | 7 | EQUIRECTANGULAR_MODE | |
  29851. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  29852. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  29853. */
  29854. set: function (value) {
  29855. if (this._coordinatesMode === value) {
  29856. return;
  29857. }
  29858. this._coordinatesMode = value;
  29859. if (this._scene) {
  29860. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29861. }
  29862. },
  29863. enumerable: true,
  29864. configurable: true
  29865. });
  29866. Object.defineProperty(BaseTexture.prototype, "isRGBD", {
  29867. /**
  29868. * Gets whether or not the texture contains RGBD data.
  29869. */
  29870. get: function () {
  29871. return this._texture != null && this._texture._isRGBD;
  29872. },
  29873. enumerable: true,
  29874. configurable: true
  29875. });
  29876. Object.defineProperty(BaseTexture.prototype, "lodGenerationOffset", {
  29877. get: function () {
  29878. if (this._texture)
  29879. return this._texture._lodGenerationOffset;
  29880. return 0.0;
  29881. },
  29882. set: function (value) {
  29883. if (this._texture)
  29884. this._texture._lodGenerationOffset = value;
  29885. },
  29886. enumerable: true,
  29887. configurable: true
  29888. });
  29889. Object.defineProperty(BaseTexture.prototype, "lodGenerationScale", {
  29890. get: function () {
  29891. if (this._texture)
  29892. return this._texture._lodGenerationScale;
  29893. return 0.0;
  29894. },
  29895. set: function (value) {
  29896. if (this._texture)
  29897. this._texture._lodGenerationScale = value;
  29898. },
  29899. enumerable: true,
  29900. configurable: true
  29901. });
  29902. Object.defineProperty(BaseTexture.prototype, "uid", {
  29903. get: function () {
  29904. if (!this._uid) {
  29905. this._uid = BABYLON.Tools.RandomId();
  29906. }
  29907. return this._uid;
  29908. },
  29909. enumerable: true,
  29910. configurable: true
  29911. });
  29912. BaseTexture.prototype.toString = function () {
  29913. return this.name;
  29914. };
  29915. BaseTexture.prototype.getClassName = function () {
  29916. return "BaseTexture";
  29917. };
  29918. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  29919. set: function (callback) {
  29920. if (this._onDisposeObserver) {
  29921. this.onDisposeObservable.remove(this._onDisposeObserver);
  29922. }
  29923. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  29924. },
  29925. enumerable: true,
  29926. configurable: true
  29927. });
  29928. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  29929. get: function () {
  29930. return true;
  29931. },
  29932. enumerable: true,
  29933. configurable: true
  29934. });
  29935. BaseTexture.prototype.getScene = function () {
  29936. return this._scene;
  29937. };
  29938. BaseTexture.prototype.getTextureMatrix = function () {
  29939. return BABYLON.Matrix.IdentityReadOnly;
  29940. };
  29941. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  29942. return BABYLON.Matrix.IdentityReadOnly;
  29943. };
  29944. BaseTexture.prototype.getInternalTexture = function () {
  29945. return this._texture;
  29946. };
  29947. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  29948. return !this.isBlocking || this.isReady();
  29949. };
  29950. BaseTexture.prototype.isReady = function () {
  29951. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  29952. this.delayLoad();
  29953. return false;
  29954. }
  29955. if (this._texture) {
  29956. return this._texture.isReady;
  29957. }
  29958. return false;
  29959. };
  29960. BaseTexture.prototype.getSize = function () {
  29961. if (this._texture) {
  29962. if (this._texture.width) {
  29963. this._cachedSize.width = this._texture.width;
  29964. this._cachedSize.height = this._texture.height;
  29965. return this._cachedSize;
  29966. }
  29967. if (this._texture._size) {
  29968. this._cachedSize.width = this._texture._size;
  29969. this._cachedSize.height = this._texture._size;
  29970. return this._cachedSize;
  29971. }
  29972. }
  29973. return this._cachedSize;
  29974. };
  29975. BaseTexture.prototype.getBaseSize = function () {
  29976. if (!this.isReady() || !this._texture)
  29977. return BABYLON.Size.Zero();
  29978. if (this._texture._size) {
  29979. return new BABYLON.Size(this._texture._size, this._texture._size);
  29980. }
  29981. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  29982. };
  29983. BaseTexture.prototype.scale = function (ratio) {
  29984. };
  29985. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  29986. get: function () {
  29987. return false;
  29988. },
  29989. enumerable: true,
  29990. configurable: true
  29991. });
  29992. /** @hidden */
  29993. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  29994. if (!this._scene) {
  29995. return null;
  29996. }
  29997. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  29998. for (var index = 0; index < texturesCache.length; index++) {
  29999. var texturesCacheEntry = texturesCache[index];
  30000. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30001. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30002. texturesCacheEntry.incrementReferences();
  30003. return texturesCacheEntry;
  30004. }
  30005. }
  30006. }
  30007. return null;
  30008. };
  30009. /** @hidden */
  30010. BaseTexture.prototype._rebuild = function () {
  30011. };
  30012. BaseTexture.prototype.delayLoad = function () {
  30013. };
  30014. BaseTexture.prototype.clone = function () {
  30015. return null;
  30016. };
  30017. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30018. get: function () {
  30019. if (!this._texture) {
  30020. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30021. }
  30022. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30023. },
  30024. enumerable: true,
  30025. configurable: true
  30026. });
  30027. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30028. get: function () {
  30029. if (!this._texture) {
  30030. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30031. }
  30032. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30033. },
  30034. enumerable: true,
  30035. configurable: true
  30036. });
  30037. /**
  30038. * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.
  30039. * This will returns an RGBA array buffer containing either in values (0-255) or
  30040. * float values (0-1) depending of the underlying buffer type.
  30041. * @param faceIndex The face of the texture to read (in case of cube texture)
  30042. * @param level The LOD level of the texture to read (in case of Mip Maps)
  30043. * @returns The Array buffer containing the pixels data.
  30044. */
  30045. BaseTexture.prototype.readPixels = function (faceIndex, level) {
  30046. if (faceIndex === void 0) { faceIndex = 0; }
  30047. if (level === void 0) { level = 0; }
  30048. if (!this._texture) {
  30049. return null;
  30050. }
  30051. var size = this.getSize();
  30052. var width = size.width;
  30053. var height = size.height;
  30054. var scene = this.getScene();
  30055. if (!scene) {
  30056. return null;
  30057. }
  30058. var engine = scene.getEngine();
  30059. if (level != 0) {
  30060. width = width / Math.pow(2, level);
  30061. height = height / Math.pow(2, level);
  30062. width = Math.round(width);
  30063. height = Math.round(height);
  30064. }
  30065. if (this._texture.isCube) {
  30066. return engine._readTexturePixels(this._texture, width, height, faceIndex, level);
  30067. }
  30068. return engine._readTexturePixels(this._texture, width, height, -1, level);
  30069. };
  30070. BaseTexture.prototype.releaseInternalTexture = function () {
  30071. if (this._texture) {
  30072. this._texture.dispose();
  30073. this._texture = null;
  30074. }
  30075. };
  30076. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30077. get: function () {
  30078. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30079. return null;
  30080. }
  30081. if (!this._texture._sphericalPolynomial) {
  30082. this._texture._sphericalPolynomial =
  30083. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30084. }
  30085. return this._texture._sphericalPolynomial;
  30086. },
  30087. set: function (value) {
  30088. if (this._texture) {
  30089. this._texture._sphericalPolynomial = value;
  30090. }
  30091. },
  30092. enumerable: true,
  30093. configurable: true
  30094. });
  30095. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30096. get: function () {
  30097. if (this._texture) {
  30098. return this._texture._lodTextureHigh;
  30099. }
  30100. return null;
  30101. },
  30102. enumerable: true,
  30103. configurable: true
  30104. });
  30105. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30106. get: function () {
  30107. if (this._texture) {
  30108. return this._texture._lodTextureMid;
  30109. }
  30110. return null;
  30111. },
  30112. enumerable: true,
  30113. configurable: true
  30114. });
  30115. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30116. get: function () {
  30117. if (this._texture) {
  30118. return this._texture._lodTextureLow;
  30119. }
  30120. return null;
  30121. },
  30122. enumerable: true,
  30123. configurable: true
  30124. });
  30125. BaseTexture.prototype.dispose = function () {
  30126. if (!this._scene) {
  30127. return;
  30128. }
  30129. // Animations
  30130. this._scene.stopAnimation(this);
  30131. // Remove from scene
  30132. this._scene._removePendingData(this);
  30133. var index = this._scene.textures.indexOf(this);
  30134. if (index >= 0) {
  30135. this._scene.textures.splice(index, 1);
  30136. }
  30137. if (this._texture === undefined) {
  30138. return;
  30139. }
  30140. // Release
  30141. this.releaseInternalTexture();
  30142. // Callback
  30143. this.onDisposeObservable.notifyObservers(this);
  30144. this.onDisposeObservable.clear();
  30145. };
  30146. BaseTexture.prototype.serialize = function () {
  30147. if (!this.name) {
  30148. return null;
  30149. }
  30150. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30151. // Animations
  30152. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30153. return serializationObject;
  30154. };
  30155. BaseTexture.WhenAllReady = function (textures, callback) {
  30156. var numRemaining = textures.length;
  30157. if (numRemaining === 0) {
  30158. callback();
  30159. return;
  30160. }
  30161. var _loop_1 = function () {
  30162. texture = textures[i];
  30163. if (texture.isReady()) {
  30164. if (--numRemaining === 0) {
  30165. callback();
  30166. }
  30167. }
  30168. else {
  30169. onLoadObservable = texture.onLoadObservable;
  30170. var onLoadCallback_1 = function () {
  30171. onLoadObservable.removeCallback(onLoadCallback_1);
  30172. if (--numRemaining === 0) {
  30173. callback();
  30174. }
  30175. };
  30176. onLoadObservable.add(onLoadCallback_1);
  30177. }
  30178. };
  30179. var texture, onLoadObservable;
  30180. for (var i = 0; i < textures.length; i++) {
  30181. _loop_1();
  30182. }
  30183. };
  30184. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30185. __decorate([
  30186. BABYLON.serialize()
  30187. ], BaseTexture.prototype, "name", void 0);
  30188. __decorate([
  30189. BABYLON.serialize("hasAlpha")
  30190. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30191. __decorate([
  30192. BABYLON.serialize()
  30193. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30194. __decorate([
  30195. BABYLON.serialize()
  30196. ], BaseTexture.prototype, "level", void 0);
  30197. __decorate([
  30198. BABYLON.serialize()
  30199. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30200. __decorate([
  30201. BABYLON.serialize("coordinatesMode")
  30202. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30203. __decorate([
  30204. BABYLON.serialize()
  30205. ], BaseTexture.prototype, "wrapU", void 0);
  30206. __decorate([
  30207. BABYLON.serialize()
  30208. ], BaseTexture.prototype, "wrapV", void 0);
  30209. __decorate([
  30210. BABYLON.serialize()
  30211. ], BaseTexture.prototype, "wrapR", void 0);
  30212. __decorate([
  30213. BABYLON.serialize()
  30214. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30215. __decorate([
  30216. BABYLON.serialize()
  30217. ], BaseTexture.prototype, "isCube", void 0);
  30218. __decorate([
  30219. BABYLON.serialize()
  30220. ], BaseTexture.prototype, "is3D", void 0);
  30221. __decorate([
  30222. BABYLON.serialize()
  30223. ], BaseTexture.prototype, "gammaSpace", void 0);
  30224. __decorate([
  30225. BABYLON.serialize()
  30226. ], BaseTexture.prototype, "invertZ", void 0);
  30227. __decorate([
  30228. BABYLON.serialize()
  30229. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30230. __decorate([
  30231. BABYLON.serialize()
  30232. ], BaseTexture.prototype, "lodGenerationOffset", null);
  30233. __decorate([
  30234. BABYLON.serialize()
  30235. ], BaseTexture.prototype, "lodGenerationScale", null);
  30236. __decorate([
  30237. BABYLON.serialize()
  30238. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30239. return BaseTexture;
  30240. }());
  30241. BABYLON.BaseTexture = BaseTexture;
  30242. })(BABYLON || (BABYLON = {}));
  30243. //# sourceMappingURL=babylon.baseTexture.js.map
  30244. var BABYLON;
  30245. (function (BABYLON) {
  30246. var Texture = /** @class */ (function (_super) {
  30247. __extends(Texture, _super);
  30248. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30249. if (noMipmap === void 0) { noMipmap = false; }
  30250. if (invertY === void 0) { invertY = true; }
  30251. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30252. if (onLoad === void 0) { onLoad = null; }
  30253. if (onError === void 0) { onError = null; }
  30254. if (buffer === void 0) { buffer = null; }
  30255. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30256. var _this = _super.call(this, scene) || this;
  30257. _this.uOffset = 0;
  30258. _this.vOffset = 0;
  30259. _this.uScale = 1.0;
  30260. _this.vScale = 1.0;
  30261. _this.uAng = 0;
  30262. _this.vAng = 0;
  30263. _this.wAng = 0;
  30264. /**
  30265. * Defines the center of rotation (U)
  30266. */
  30267. _this.uRotationCenter = 0.5;
  30268. /**
  30269. * Defines the center of rotation (V)
  30270. */
  30271. _this.vRotationCenter = 0.5;
  30272. /**
  30273. * Defines the center of rotation (W)
  30274. */
  30275. _this.wRotationCenter = 0.5;
  30276. _this._isBlocking = true;
  30277. _this.name = url || "";
  30278. _this.url = url;
  30279. _this._noMipmap = noMipmap;
  30280. _this._invertY = invertY;
  30281. _this._samplingMode = samplingMode;
  30282. _this._buffer = buffer;
  30283. _this._deleteBuffer = deleteBuffer;
  30284. if (format) {
  30285. _this._format = format;
  30286. }
  30287. scene = _this.getScene();
  30288. if (!scene) {
  30289. return _this;
  30290. }
  30291. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30292. var load = function () {
  30293. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30294. _this.onLoadObservable.notifyObservers(_this);
  30295. }
  30296. if (onLoad) {
  30297. onLoad();
  30298. }
  30299. if (!_this.isBlocking && scene) {
  30300. scene.resetCachedMaterial();
  30301. }
  30302. };
  30303. if (!_this.url) {
  30304. _this._delayedOnLoad = load;
  30305. _this._delayedOnError = onError;
  30306. return _this;
  30307. }
  30308. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30309. if (!_this._texture) {
  30310. if (!scene.useDelayedTextureLoading) {
  30311. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30312. if (deleteBuffer) {
  30313. delete _this._buffer;
  30314. }
  30315. }
  30316. else {
  30317. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30318. _this._delayedOnLoad = load;
  30319. _this._delayedOnError = onError;
  30320. }
  30321. }
  30322. else {
  30323. if (_this._texture.isReady) {
  30324. BABYLON.Tools.SetImmediate(function () { return load(); });
  30325. }
  30326. else {
  30327. _this._texture.onLoadedObservable.add(load);
  30328. }
  30329. }
  30330. return _this;
  30331. }
  30332. Object.defineProperty(Texture.prototype, "noMipmap", {
  30333. get: function () {
  30334. return this._noMipmap;
  30335. },
  30336. enumerable: true,
  30337. configurable: true
  30338. });
  30339. Object.defineProperty(Texture.prototype, "isBlocking", {
  30340. get: function () {
  30341. return this._isBlocking;
  30342. },
  30343. set: function (value) {
  30344. this._isBlocking = value;
  30345. },
  30346. enumerable: true,
  30347. configurable: true
  30348. });
  30349. Object.defineProperty(Texture.prototype, "samplingMode", {
  30350. get: function () {
  30351. return this._samplingMode;
  30352. },
  30353. enumerable: true,
  30354. configurable: true
  30355. });
  30356. /**
  30357. * Update the url (and optional buffer) of this texture if url was null during construction.
  30358. * @param url the url of the texture
  30359. * @param buffer the buffer of the texture (defaults to null)
  30360. */
  30361. Texture.prototype.updateURL = function (url, buffer) {
  30362. if (buffer === void 0) { buffer = null; }
  30363. if (this.url) {
  30364. throw new Error("URL is already set");
  30365. }
  30366. this.url = url;
  30367. this._buffer = buffer;
  30368. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30369. this.delayLoad();
  30370. };
  30371. Texture.prototype.delayLoad = function () {
  30372. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30373. return;
  30374. }
  30375. var scene = this.getScene();
  30376. if (!scene) {
  30377. return;
  30378. }
  30379. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30380. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  30381. if (!this._texture) {
  30382. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  30383. if (this._deleteBuffer) {
  30384. delete this._buffer;
  30385. }
  30386. }
  30387. else {
  30388. if (this._delayedOnLoad) {
  30389. if (this._texture.isReady) {
  30390. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  30391. }
  30392. else {
  30393. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  30394. }
  30395. }
  30396. }
  30397. this._delayedOnLoad = null;
  30398. this._delayedOnError = null;
  30399. };
  30400. /**
  30401. * Default is Trilinear mode.
  30402. *
  30403. * | Value | Type | Description |
  30404. * | ----- | ------------------ | ----------- |
  30405. * | 1 | NEAREST_SAMPLINGMODE or NEAREST_NEAREST_MIPLINEAR | Nearest is: mag = nearest, min = nearest, mip = linear |
  30406. * | 2 | BILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPNEAREST | Bilinear is: mag = linear, min = linear, mip = nearest |
  30407. * | 3 | TRILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPLINEAR | Trilinear is: mag = linear, min = linear, mip = linear |
  30408. * | 4 | NEAREST_NEAREST_MIPNEAREST | |
  30409. * | 5 | NEAREST_LINEAR_MIPNEAREST | |
  30410. * | 6 | NEAREST_LINEAR_MIPLINEAR | |
  30411. * | 7 | NEAREST_LINEAR | |
  30412. * | 8 | NEAREST_NEAREST | |
  30413. * | 9 | LINEAR_NEAREST_MIPNEAREST | |
  30414. * | 10 | LINEAR_NEAREST_MIPLINEAR | |
  30415. * | 11 | LINEAR_LINEAR | |
  30416. * | 12 | LINEAR_NEAREST | |
  30417. *
  30418. * > _mag_: magnification filter (close to the viewer)
  30419. * > _min_: minification filter (far from the viewer)
  30420. * > _mip_: filter used between mip map levels
  30421. *
  30422. */
  30423. Texture.prototype.updateSamplingMode = function (samplingMode) {
  30424. if (!this._texture) {
  30425. return;
  30426. }
  30427. var scene = this.getScene();
  30428. if (!scene) {
  30429. return;
  30430. }
  30431. this._samplingMode = samplingMode;
  30432. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  30433. };
  30434. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  30435. x *= this.uScale;
  30436. y *= this.vScale;
  30437. x -= this.uRotationCenter * this.uScale;
  30438. y -= this.vRotationCenter * this.vScale;
  30439. z -= this.wRotationCenter;
  30440. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  30441. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  30442. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  30443. t.z += this.wRotationCenter;
  30444. };
  30445. Texture.prototype.getTextureMatrix = function () {
  30446. var _this = this;
  30447. if (this.uOffset === this._cachedUOffset &&
  30448. this.vOffset === this._cachedVOffset &&
  30449. this.uScale === this._cachedUScale &&
  30450. this.vScale === this._cachedVScale &&
  30451. this.uAng === this._cachedUAng &&
  30452. this.vAng === this._cachedVAng &&
  30453. this.wAng === this._cachedWAng) {
  30454. return this._cachedTextureMatrix;
  30455. }
  30456. this._cachedUOffset = this.uOffset;
  30457. this._cachedVOffset = this.vOffset;
  30458. this._cachedUScale = this.uScale;
  30459. this._cachedVScale = this.vScale;
  30460. this._cachedUAng = this.uAng;
  30461. this._cachedVAng = this.vAng;
  30462. this._cachedWAng = this.wAng;
  30463. if (!this._cachedTextureMatrix) {
  30464. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30465. this._rowGenerationMatrix = new BABYLON.Matrix();
  30466. this._t0 = BABYLON.Vector3.Zero();
  30467. this._t1 = BABYLON.Vector3.Zero();
  30468. this._t2 = BABYLON.Vector3.Zero();
  30469. }
  30470. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  30471. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  30472. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  30473. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  30474. this._t1.subtractInPlace(this._t0);
  30475. this._t2.subtractInPlace(this._t0);
  30476. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30477. this._cachedTextureMatrix.m[0] = this._t1.x;
  30478. this._cachedTextureMatrix.m[1] = this._t1.y;
  30479. this._cachedTextureMatrix.m[2] = this._t1.z;
  30480. this._cachedTextureMatrix.m[4] = this._t2.x;
  30481. this._cachedTextureMatrix.m[5] = this._t2.y;
  30482. this._cachedTextureMatrix.m[6] = this._t2.z;
  30483. this._cachedTextureMatrix.m[8] = this._t0.x;
  30484. this._cachedTextureMatrix.m[9] = this._t0.y;
  30485. this._cachedTextureMatrix.m[10] = this._t0.z;
  30486. var scene = this.getScene();
  30487. if (!scene) {
  30488. return this._cachedTextureMatrix;
  30489. }
  30490. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30491. return mat.hasTexture(_this);
  30492. });
  30493. return this._cachedTextureMatrix;
  30494. };
  30495. Texture.prototype.getReflectionTextureMatrix = function () {
  30496. var _this = this;
  30497. var scene = this.getScene();
  30498. if (!scene) {
  30499. return this._cachedTextureMatrix;
  30500. }
  30501. if (this.uOffset === this._cachedUOffset &&
  30502. this.vOffset === this._cachedVOffset &&
  30503. this.uScale === this._cachedUScale &&
  30504. this.vScale === this._cachedVScale &&
  30505. this.coordinatesMode === this._cachedCoordinatesMode) {
  30506. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  30507. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  30508. return this._cachedTextureMatrix;
  30509. }
  30510. }
  30511. else {
  30512. return this._cachedTextureMatrix;
  30513. }
  30514. }
  30515. if (!this._cachedTextureMatrix) {
  30516. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30517. }
  30518. if (!this._projectionModeMatrix) {
  30519. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  30520. }
  30521. this._cachedUOffset = this.uOffset;
  30522. this._cachedVOffset = this.vOffset;
  30523. this._cachedUScale = this.uScale;
  30524. this._cachedVScale = this.vScale;
  30525. this._cachedCoordinatesMode = this.coordinatesMode;
  30526. switch (this.coordinatesMode) {
  30527. case Texture.PLANAR_MODE:
  30528. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30529. this._cachedTextureMatrix[0] = this.uScale;
  30530. this._cachedTextureMatrix[5] = this.vScale;
  30531. this._cachedTextureMatrix[12] = this.uOffset;
  30532. this._cachedTextureMatrix[13] = this.vOffset;
  30533. break;
  30534. case Texture.PROJECTION_MODE:
  30535. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  30536. this._projectionModeMatrix.m[0] = 0.5;
  30537. this._projectionModeMatrix.m[5] = -0.5;
  30538. this._projectionModeMatrix.m[10] = 0.0;
  30539. this._projectionModeMatrix.m[12] = 0.5;
  30540. this._projectionModeMatrix.m[13] = 0.5;
  30541. this._projectionModeMatrix.m[14] = 1.0;
  30542. this._projectionModeMatrix.m[15] = 1.0;
  30543. var projectionMatrix = scene.getProjectionMatrix();
  30544. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  30545. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  30546. break;
  30547. default:
  30548. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30549. break;
  30550. }
  30551. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30552. return (mat.getActiveTextures().indexOf(_this) !== -1);
  30553. });
  30554. return this._cachedTextureMatrix;
  30555. };
  30556. Texture.prototype.clone = function () {
  30557. var _this = this;
  30558. return BABYLON.SerializationHelper.Clone(function () {
  30559. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  30560. }, this);
  30561. };
  30562. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  30563. get: function () {
  30564. if (!this._onLoadObservable) {
  30565. this._onLoadObservable = new BABYLON.Observable();
  30566. }
  30567. return this._onLoadObservable;
  30568. },
  30569. enumerable: true,
  30570. configurable: true
  30571. });
  30572. Texture.prototype.serialize = function () {
  30573. var serializationObject = _super.prototype.serialize.call(this);
  30574. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  30575. serializationObject.base64String = this._buffer;
  30576. serializationObject.name = serializationObject.name.replace("data:", "");
  30577. }
  30578. serializationObject.invertY = this._invertY;
  30579. serializationObject.samplingMode = this.samplingMode;
  30580. return serializationObject;
  30581. };
  30582. Texture.prototype.getClassName = function () {
  30583. return "Texture";
  30584. };
  30585. Texture.prototype.dispose = function () {
  30586. _super.prototype.dispose.call(this);
  30587. if (this._onLoadObservable) {
  30588. this._onLoadObservable.clear();
  30589. this._onLoadObservable = null;
  30590. }
  30591. this._delayedOnLoad = null;
  30592. this._delayedOnError = null;
  30593. };
  30594. // Statics
  30595. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30596. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30597. if (onLoad === void 0) { onLoad = null; }
  30598. if (onError === void 0) { onError = null; }
  30599. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30600. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  30601. };
  30602. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  30603. if (parsedTexture.customType) {
  30604. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  30605. // Update Sampling Mode
  30606. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  30607. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  30608. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  30609. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  30610. }
  30611. }
  30612. return parsedCustomTexture;
  30613. }
  30614. if (parsedTexture.isCube) {
  30615. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  30616. }
  30617. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  30618. return null;
  30619. }
  30620. var texture = BABYLON.SerializationHelper.Parse(function () {
  30621. var generateMipMaps = true;
  30622. if (parsedTexture.noMipmap) {
  30623. generateMipMaps = false;
  30624. }
  30625. if (parsedTexture.mirrorPlane) {
  30626. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30627. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  30628. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  30629. return mirrorTexture;
  30630. }
  30631. else if (parsedTexture.isRenderTarget) {
  30632. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30633. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  30634. return renderTargetTexture;
  30635. }
  30636. else {
  30637. var texture;
  30638. if (parsedTexture.base64String) {
  30639. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  30640. }
  30641. else {
  30642. var url = rootUrl + parsedTexture.name;
  30643. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  30644. url = parsedTexture.url;
  30645. }
  30646. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  30647. }
  30648. return texture;
  30649. }
  30650. }, parsedTexture, scene);
  30651. // Update Sampling Mode
  30652. if (parsedTexture.samplingMode) {
  30653. var sampling = parsedTexture.samplingMode;
  30654. if (texture._samplingMode !== sampling) {
  30655. texture.updateSamplingMode(sampling);
  30656. }
  30657. }
  30658. // Animations
  30659. if (parsedTexture.animations) {
  30660. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  30661. var parsedAnimation = parsedTexture.animations[animationIndex];
  30662. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  30663. }
  30664. }
  30665. return texture;
  30666. };
  30667. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30668. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30669. if (noMipmap === void 0) { noMipmap = false; }
  30670. if (invertY === void 0) { invertY = true; }
  30671. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30672. if (onLoad === void 0) { onLoad = null; }
  30673. if (onError === void 0) { onError = null; }
  30674. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30675. if (name.substr(0, 5) !== "data:") {
  30676. name = "data:" + name;
  30677. }
  30678. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  30679. };
  30680. // Constants
  30681. Texture.NEAREST_SAMPLINGMODE = BABYLON.Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  30682. Texture.NEAREST_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR; // nearest is mag = nearest and min = nearest and mip = linear
  30683. Texture.BILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_BILINEAR_SAMPLINGMODE;
  30684. Texture.LINEAR_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST; // Bilinear is mag = linear and min = linear and mip = nearest
  30685. Texture.TRILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  30686. Texture.LINEAR_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR; // Trilinear is mag = linear and min = linear and mip = linear
  30687. Texture.NEAREST_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST;
  30688. Texture.NEAREST_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST;
  30689. Texture.NEAREST_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR;
  30690. Texture.NEAREST_LINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR;
  30691. Texture.NEAREST_NEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST;
  30692. Texture.LINEAR_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST;
  30693. Texture.LINEAR_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR;
  30694. Texture.LINEAR_LINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR;
  30695. Texture.LINEAR_NEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST;
  30696. Texture.EXPLICIT_MODE = BABYLON.Engine.TEXTURE_EXPLICIT_MODE;
  30697. Texture.SPHERICAL_MODE = BABYLON.Engine.TEXTURE_SPHERICAL_MODE;
  30698. Texture.PLANAR_MODE = BABYLON.Engine.TEXTURE_PLANAR_MODE;
  30699. Texture.CUBIC_MODE = BABYLON.Engine.TEXTURE_CUBIC_MODE;
  30700. Texture.PROJECTION_MODE = BABYLON.Engine.TEXTURE_PROJECTION_MODE;
  30701. Texture.SKYBOX_MODE = BABYLON.Engine.TEXTURE_SKYBOX_MODE;
  30702. Texture.INVCUBIC_MODE = BABYLON.Engine.TEXTURE_INVCUBIC_MODE;
  30703. Texture.EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_EQUIRECTANGULAR_MODE;
  30704. Texture.FIXED_EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE;
  30705. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE;
  30706. Texture.CLAMP_ADDRESSMODE = BABYLON.Engine.TEXTURE_CLAMP_ADDRESSMODE;
  30707. Texture.WRAP_ADDRESSMODE = BABYLON.Engine.TEXTURE_WRAP_ADDRESSMODE;
  30708. Texture.MIRROR_ADDRESSMODE = BABYLON.Engine.TEXTURE_MIRROR_ADDRESSMODE;
  30709. /**
  30710. * 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
  30711. */
  30712. Texture.UseSerializedUrlIfAny = false;
  30713. __decorate([
  30714. BABYLON.serialize()
  30715. ], Texture.prototype, "url", void 0);
  30716. __decorate([
  30717. BABYLON.serialize()
  30718. ], Texture.prototype, "uOffset", void 0);
  30719. __decorate([
  30720. BABYLON.serialize()
  30721. ], Texture.prototype, "vOffset", void 0);
  30722. __decorate([
  30723. BABYLON.serialize()
  30724. ], Texture.prototype, "uScale", void 0);
  30725. __decorate([
  30726. BABYLON.serialize()
  30727. ], Texture.prototype, "vScale", void 0);
  30728. __decorate([
  30729. BABYLON.serialize()
  30730. ], Texture.prototype, "uAng", void 0);
  30731. __decorate([
  30732. BABYLON.serialize()
  30733. ], Texture.prototype, "vAng", void 0);
  30734. __decorate([
  30735. BABYLON.serialize()
  30736. ], Texture.prototype, "wAng", void 0);
  30737. __decorate([
  30738. BABYLON.serialize()
  30739. ], Texture.prototype, "uRotationCenter", void 0);
  30740. __decorate([
  30741. BABYLON.serialize()
  30742. ], Texture.prototype, "vRotationCenter", void 0);
  30743. __decorate([
  30744. BABYLON.serialize()
  30745. ], Texture.prototype, "wRotationCenter", void 0);
  30746. __decorate([
  30747. BABYLON.serialize()
  30748. ], Texture.prototype, "isBlocking", null);
  30749. return Texture;
  30750. }(BABYLON.BaseTexture));
  30751. BABYLON.Texture = Texture;
  30752. })(BABYLON || (BABYLON = {}));
  30753. //# sourceMappingURL=babylon.texture.js.map
  30754. var BABYLON;
  30755. (function (BABYLON) {
  30756. /**
  30757. * @hidden
  30758. **/
  30759. var _InstancesBatch = /** @class */ (function () {
  30760. function _InstancesBatch() {
  30761. this.mustReturn = false;
  30762. this.visibleInstances = new Array();
  30763. this.renderSelf = new Array();
  30764. }
  30765. return _InstancesBatch;
  30766. }());
  30767. BABYLON._InstancesBatch = _InstancesBatch;
  30768. var Mesh = /** @class */ (function (_super) {
  30769. __extends(Mesh, _super);
  30770. /**
  30771. * @constructor
  30772. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  30773. * @param {Scene} scene The scene to add this mesh to.
  30774. * @param {Node} parent The parent of this mesh, if it has one
  30775. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  30776. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  30777. * When false, achieved by calling a clone(), also passing False.
  30778. * This will make creation of children, recursive.
  30779. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  30780. */
  30781. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  30782. if (scene === void 0) { scene = null; }
  30783. if (parent === void 0) { parent = null; }
  30784. if (source === void 0) { source = null; }
  30785. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  30786. var _this = _super.call(this, name, scene) || this;
  30787. // Members
  30788. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30789. _this.instances = new Array();
  30790. _this._LODLevels = new Array();
  30791. /** @hidden */
  30792. _this._visibleInstances = {};
  30793. _this._renderIdForInstances = new Array();
  30794. _this._batchCache = new _InstancesBatch();
  30795. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  30796. // Use by builder only to know what orientation were the mesh build in.
  30797. /** @hidden */
  30798. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  30799. _this.overrideMaterialSideOrientation = null;
  30800. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  30801. // Will be used to save a source mesh reference, If any
  30802. _this._source = null;
  30803. scene = _this.getScene();
  30804. if (source) {
  30805. // Geometry
  30806. if (source._geometry) {
  30807. source._geometry.applyToMesh(_this);
  30808. }
  30809. // Deep copy
  30810. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  30811. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen",
  30812. "onBeforeDrawObservable", "onBeforeRenderObservable", "onAfterRenderObservable", "onBeforeDraw"
  30813. ], ["_poseMatrix"]);
  30814. // Source mesh
  30815. _this._source = source;
  30816. // Construction Params
  30817. // Clone parameters allowing mesh to be updated in case of parametric shapes.
  30818. _this._originalBuilderSideOrientation = source._originalBuilderSideOrientation;
  30819. var myAnyThis = _this;
  30820. var myAnySource = source;
  30821. myAnyThis._closePath = myAnySource._closePath;
  30822. myAnyThis._idx = myAnySource._idx;
  30823. myAnyThis.dashSize = myAnySource.dashSize;
  30824. myAnyThis.gapSize = myAnySource.gapSize;
  30825. myAnyThis.path3D = myAnySource.path3D;
  30826. myAnyThis.pathArray = myAnySource.pathArray;
  30827. myAnyThis.arc = myAnySource.arc;
  30828. myAnyThis.radius = myAnySource.radius;
  30829. // Animation ranges
  30830. if (_this._source._ranges) {
  30831. var ranges = _this._source._ranges;
  30832. for (var name in ranges) {
  30833. if (!ranges.hasOwnProperty(name)) {
  30834. continue;
  30835. }
  30836. if (!ranges[name]) {
  30837. continue;
  30838. }
  30839. _this.createAnimationRange(name, ranges[name].from, ranges[name].to);
  30840. }
  30841. }
  30842. // Metadata
  30843. if (source.metadata && source.metadata.clone) {
  30844. _this.metadata = source.metadata.clone();
  30845. }
  30846. else {
  30847. _this.metadata = source.metadata;
  30848. }
  30849. // Tags
  30850. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  30851. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  30852. }
  30853. // Parent
  30854. _this.parent = source.parent;
  30855. // Pivot
  30856. _this.setPivotMatrix(source.getPivotMatrix());
  30857. _this.id = name + "." + source.id;
  30858. // Material
  30859. _this.material = source.material;
  30860. var index;
  30861. if (!doNotCloneChildren) {
  30862. // Children
  30863. var directDescendants = source.getDescendants(true);
  30864. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  30865. var child = directDescendants[index_1];
  30866. if (child.clone) {
  30867. child.clone(name + "." + child.name, _this);
  30868. }
  30869. }
  30870. }
  30871. // Physics clone
  30872. var physicsEngine = _this.getScene().getPhysicsEngine();
  30873. if (clonePhysicsImpostor && physicsEngine) {
  30874. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  30875. if (impostor) {
  30876. _this.physicsImpostor = impostor.clone(_this);
  30877. }
  30878. }
  30879. // Particles
  30880. for (index = 0; index < scene.particleSystems.length; index++) {
  30881. var system = scene.particleSystems[index];
  30882. if (system.emitter === source) {
  30883. system.clone(system.name, _this);
  30884. }
  30885. }
  30886. _this.refreshBoundingInfo();
  30887. _this.computeWorldMatrix(true);
  30888. }
  30889. // Parent
  30890. if (parent !== null) {
  30891. _this.parent = parent;
  30892. }
  30893. return _this;
  30894. }
  30895. Object.defineProperty(Mesh, "FRONTSIDE", {
  30896. /**
  30897. * Mesh side orientation : usually the external or front surface
  30898. */
  30899. get: function () {
  30900. return Mesh._FRONTSIDE;
  30901. },
  30902. enumerable: true,
  30903. configurable: true
  30904. });
  30905. Object.defineProperty(Mesh, "BACKSIDE", {
  30906. /**
  30907. * Mesh side orientation : usually the internal or back surface
  30908. */
  30909. get: function () {
  30910. return Mesh._BACKSIDE;
  30911. },
  30912. enumerable: true,
  30913. configurable: true
  30914. });
  30915. Object.defineProperty(Mesh, "DOUBLESIDE", {
  30916. /**
  30917. * Mesh side orientation : both internal and external or front and back surfaces
  30918. */
  30919. get: function () {
  30920. return Mesh._DOUBLESIDE;
  30921. },
  30922. enumerable: true,
  30923. configurable: true
  30924. });
  30925. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  30926. /**
  30927. * Mesh side orientation : by default, `FRONTSIDE`
  30928. */
  30929. get: function () {
  30930. return Mesh._DEFAULTSIDE;
  30931. },
  30932. enumerable: true,
  30933. configurable: true
  30934. });
  30935. Object.defineProperty(Mesh, "NO_CAP", {
  30936. /**
  30937. * Mesh cap setting : no cap
  30938. */
  30939. get: function () {
  30940. return Mesh._NO_CAP;
  30941. },
  30942. enumerable: true,
  30943. configurable: true
  30944. });
  30945. Object.defineProperty(Mesh, "CAP_START", {
  30946. /**
  30947. * Mesh cap setting : one cap at the beginning of the mesh
  30948. */
  30949. get: function () {
  30950. return Mesh._CAP_START;
  30951. },
  30952. enumerable: true,
  30953. configurable: true
  30954. });
  30955. Object.defineProperty(Mesh, "CAP_END", {
  30956. /**
  30957. * Mesh cap setting : one cap at the end of the mesh
  30958. */
  30959. get: function () {
  30960. return Mesh._CAP_END;
  30961. },
  30962. enumerable: true,
  30963. configurable: true
  30964. });
  30965. Object.defineProperty(Mesh, "CAP_ALL", {
  30966. /**
  30967. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  30968. */
  30969. get: function () {
  30970. return Mesh._CAP_ALL;
  30971. },
  30972. enumerable: true,
  30973. configurable: true
  30974. });
  30975. Object.defineProperty(Mesh.prototype, "onBeforeRenderObservable", {
  30976. /**
  30977. * An event triggered before rendering the mesh
  30978. */
  30979. get: function () {
  30980. if (!this._onBeforeRenderObservable) {
  30981. this._onBeforeRenderObservable = new BABYLON.Observable();
  30982. }
  30983. return this._onBeforeRenderObservable;
  30984. },
  30985. enumerable: true,
  30986. configurable: true
  30987. });
  30988. Object.defineProperty(Mesh.prototype, "onAfterRenderObservable", {
  30989. /**
  30990. * An event triggered after rendering the mesh
  30991. */
  30992. get: function () {
  30993. if (!this._onAfterRenderObservable) {
  30994. this._onAfterRenderObservable = new BABYLON.Observable();
  30995. }
  30996. return this._onAfterRenderObservable;
  30997. },
  30998. enumerable: true,
  30999. configurable: true
  31000. });
  31001. Object.defineProperty(Mesh.prototype, "onBeforeDrawObservable", {
  31002. /**
  31003. * An event triggered before drawing the mesh
  31004. */
  31005. get: function () {
  31006. if (!this._onBeforeDrawObservable) {
  31007. this._onBeforeDrawObservable = new BABYLON.Observable();
  31008. }
  31009. return this._onBeforeDrawObservable;
  31010. },
  31011. enumerable: true,
  31012. configurable: true
  31013. });
  31014. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  31015. set: function (callback) {
  31016. if (this._onBeforeDrawObserver) {
  31017. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31018. }
  31019. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31020. },
  31021. enumerable: true,
  31022. configurable: true
  31023. });
  31024. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31025. get: function () {
  31026. return this._morphTargetManager;
  31027. },
  31028. set: function (value) {
  31029. if (this._morphTargetManager === value) {
  31030. return;
  31031. }
  31032. this._morphTargetManager = value;
  31033. this._syncGeometryWithMorphTargetManager();
  31034. },
  31035. enumerable: true,
  31036. configurable: true
  31037. });
  31038. Object.defineProperty(Mesh.prototype, "source", {
  31039. get: function () {
  31040. return this._source;
  31041. },
  31042. enumerable: true,
  31043. configurable: true
  31044. });
  31045. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31046. get: function () {
  31047. return this._unIndexed;
  31048. },
  31049. set: function (value) {
  31050. if (this._unIndexed !== value) {
  31051. this._unIndexed = value;
  31052. this._markSubMeshesAsAttributesDirty();
  31053. }
  31054. },
  31055. enumerable: true,
  31056. configurable: true
  31057. });
  31058. // Methods
  31059. /**
  31060. * Returns the string "Mesh".
  31061. */
  31062. Mesh.prototype.getClassName = function () {
  31063. return "Mesh";
  31064. };
  31065. /**
  31066. * Returns a string.
  31067. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31068. */
  31069. Mesh.prototype.toString = function (fullDetails) {
  31070. var ret = _super.prototype.toString.call(this, fullDetails);
  31071. ret += ", n vertices: " + this.getTotalVertices();
  31072. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31073. if (this.animations) {
  31074. for (var i = 0; i < this.animations.length; i++) {
  31075. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31076. }
  31077. }
  31078. if (fullDetails) {
  31079. if (this._geometry) {
  31080. var ib = this.getIndices();
  31081. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31082. if (vb && ib) {
  31083. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31084. }
  31085. }
  31086. else {
  31087. ret += ", flat shading: UNKNOWN";
  31088. }
  31089. }
  31090. return ret;
  31091. };
  31092. /** @hidden */
  31093. Mesh.prototype._unBindEffect = function () {
  31094. _super.prototype._unBindEffect.call(this);
  31095. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31096. var instance = _a[_i];
  31097. instance._unBindEffect();
  31098. }
  31099. };
  31100. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31101. /**
  31102. * True if the mesh has some Levels Of Details (LOD).
  31103. * Returns a boolean.
  31104. */
  31105. get: function () {
  31106. return this._LODLevels.length > 0;
  31107. },
  31108. enumerable: true,
  31109. configurable: true
  31110. });
  31111. /**
  31112. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  31113. * @returns an array of {BABYLON.MeshLODLevel}
  31114. */
  31115. Mesh.prototype.getLODLevels = function () {
  31116. return this._LODLevels;
  31117. };
  31118. Mesh.prototype._sortLODLevels = function () {
  31119. this._LODLevels.sort(function (a, b) {
  31120. if (a.distance < b.distance) {
  31121. return 1;
  31122. }
  31123. if (a.distance > b.distance) {
  31124. return -1;
  31125. }
  31126. return 0;
  31127. });
  31128. };
  31129. /**
  31130. * Add a mesh as LOD level triggered at the given distance.
  31131. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31132. * @param distance The distance from the center of the object to show this level
  31133. * @param mesh The mesh to be added as LOD level (can be null)
  31134. * @return This mesh (for chaining)
  31135. */
  31136. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31137. if (mesh && mesh._masterMesh) {
  31138. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31139. return this;
  31140. }
  31141. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31142. this._LODLevels.push(level);
  31143. if (mesh) {
  31144. mesh._masterMesh = this;
  31145. }
  31146. this._sortLODLevels();
  31147. return this;
  31148. };
  31149. /**
  31150. * Returns the LOD level mesh at the passed distance or null if not found.
  31151. * It is related to the method `addLODLevel(distance, mesh)`.
  31152. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31153. * Returns an object Mesh or `null`.
  31154. */
  31155. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31156. for (var index = 0; index < this._LODLevels.length; index++) {
  31157. var level = this._LODLevels[index];
  31158. if (level.distance === distance) {
  31159. return level.mesh;
  31160. }
  31161. }
  31162. return null;
  31163. };
  31164. /**
  31165. * Remove a mesh from the LOD array
  31166. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31167. * @param {Mesh} mesh The mesh to be removed.
  31168. * @return {Mesh} This mesh (for chaining)
  31169. */
  31170. Mesh.prototype.removeLODLevel = function (mesh) {
  31171. for (var index = 0; index < this._LODLevels.length; index++) {
  31172. if (this._LODLevels[index].mesh === mesh) {
  31173. this._LODLevels.splice(index, 1);
  31174. if (mesh) {
  31175. mesh._masterMesh = null;
  31176. }
  31177. }
  31178. }
  31179. this._sortLODLevels();
  31180. return this;
  31181. };
  31182. /**
  31183. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31184. * tuto : http://doc.babylonjs.com/how_to/how_to_use_lod
  31185. */
  31186. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31187. if (!this._LODLevels || this._LODLevels.length === 0) {
  31188. return this;
  31189. }
  31190. var bSphere;
  31191. if (boundingSphere) {
  31192. bSphere = boundingSphere;
  31193. }
  31194. else {
  31195. var boundingInfo = this.getBoundingInfo();
  31196. bSphere = boundingInfo.boundingSphere;
  31197. }
  31198. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31199. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31200. if (this.onLODLevelSelection) {
  31201. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31202. }
  31203. return this;
  31204. }
  31205. for (var index = 0; index < this._LODLevels.length; index++) {
  31206. var level = this._LODLevels[index];
  31207. if (level.distance < distanceToCamera) {
  31208. if (level.mesh) {
  31209. level.mesh._preActivate();
  31210. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31211. }
  31212. if (this.onLODLevelSelection) {
  31213. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31214. }
  31215. return level.mesh;
  31216. }
  31217. }
  31218. if (this.onLODLevelSelection) {
  31219. this.onLODLevelSelection(distanceToCamera, this, this);
  31220. }
  31221. return this;
  31222. };
  31223. Object.defineProperty(Mesh.prototype, "geometry", {
  31224. /**
  31225. * Returns the mesh internal Geometry object.
  31226. */
  31227. get: function () {
  31228. return this._geometry;
  31229. },
  31230. enumerable: true,
  31231. configurable: true
  31232. });
  31233. /**
  31234. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31235. */
  31236. Mesh.prototype.getTotalVertices = function () {
  31237. if (this._geometry === null || this._geometry === undefined) {
  31238. return 0;
  31239. }
  31240. return this._geometry.getTotalVertices();
  31241. };
  31242. /**
  31243. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  31244. * 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.
  31245. * You can force the copy with forceCopy === true
  31246. * Returns null if the mesh has no geometry or no vertex buffer.
  31247. * Possible `kind` values :
  31248. * - BABYLON.VertexBuffer.PositionKind
  31249. * - BABYLON.VertexBuffer.UVKind
  31250. * - BABYLON.VertexBuffer.UV2Kind
  31251. * - BABYLON.VertexBuffer.UV3Kind
  31252. * - BABYLON.VertexBuffer.UV4Kind
  31253. * - BABYLON.VertexBuffer.UV5Kind
  31254. * - BABYLON.VertexBuffer.UV6Kind
  31255. * - BABYLON.VertexBuffer.ColorKind
  31256. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31257. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31258. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31259. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31260. */
  31261. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31262. if (!this._geometry) {
  31263. return null;
  31264. }
  31265. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31266. };
  31267. /**
  31268. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  31269. * Returns `null` if the mesh has no geometry.
  31270. * Possible `kind` values :
  31271. * - BABYLON.VertexBuffer.PositionKind
  31272. * - BABYLON.VertexBuffer.UVKind
  31273. * - BABYLON.VertexBuffer.UV2Kind
  31274. * - BABYLON.VertexBuffer.UV3Kind
  31275. * - BABYLON.VertexBuffer.UV4Kind
  31276. * - BABYLON.VertexBuffer.UV5Kind
  31277. * - BABYLON.VertexBuffer.UV6Kind
  31278. * - BABYLON.VertexBuffer.ColorKind
  31279. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31280. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31281. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31282. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31283. */
  31284. Mesh.prototype.getVertexBuffer = function (kind) {
  31285. if (!this._geometry) {
  31286. return null;
  31287. }
  31288. return this._geometry.getVertexBuffer(kind);
  31289. };
  31290. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31291. if (!this._geometry) {
  31292. if (this._delayInfo) {
  31293. return this._delayInfo.indexOf(kind) !== -1;
  31294. }
  31295. return false;
  31296. }
  31297. return this._geometry.isVerticesDataPresent(kind);
  31298. };
  31299. /**
  31300. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31301. * Possible `kind` values :
  31302. * - BABYLON.VertexBuffer.PositionKind
  31303. * - BABYLON.VertexBuffer.UVKind
  31304. * - BABYLON.VertexBuffer.UV2Kind
  31305. * - BABYLON.VertexBuffer.UV3Kind
  31306. * - BABYLON.VertexBuffer.UV4Kind
  31307. * - BABYLON.VertexBuffer.UV5Kind
  31308. * - BABYLON.VertexBuffer.UV6Kind
  31309. * - BABYLON.VertexBuffer.ColorKind
  31310. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31311. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31312. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31313. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31314. */
  31315. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31316. if (!this._geometry) {
  31317. if (this._delayInfo) {
  31318. return this._delayInfo.indexOf(kind) !== -1;
  31319. }
  31320. return false;
  31321. }
  31322. return this._geometry.isVertexBufferUpdatable(kind);
  31323. };
  31324. /**
  31325. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  31326. * Possible `kind` values :
  31327. * - BABYLON.VertexBuffer.PositionKind
  31328. * - BABYLON.VertexBuffer.UVKind
  31329. * - BABYLON.VertexBuffer.UV2Kind
  31330. * - BABYLON.VertexBuffer.UV3Kind
  31331. * - BABYLON.VertexBuffer.UV4Kind
  31332. * - BABYLON.VertexBuffer.UV5Kind
  31333. * - BABYLON.VertexBuffer.UV6Kind
  31334. * - BABYLON.VertexBuffer.ColorKind
  31335. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31336. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31337. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31338. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31339. */
  31340. Mesh.prototype.getVerticesDataKinds = function () {
  31341. if (!this._geometry) {
  31342. var result = new Array();
  31343. if (this._delayInfo) {
  31344. this._delayInfo.forEach(function (kind, index, array) {
  31345. result.push(kind);
  31346. });
  31347. }
  31348. return result;
  31349. }
  31350. return this._geometry.getVerticesDataKinds();
  31351. };
  31352. /**
  31353. * Returns a positive integer : the total number of indices in this mesh geometry.
  31354. * Returns zero if the mesh has no geometry.
  31355. */
  31356. Mesh.prototype.getTotalIndices = function () {
  31357. if (!this._geometry) {
  31358. return 0;
  31359. }
  31360. return this._geometry.getTotalIndices();
  31361. };
  31362. /**
  31363. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31364. * @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.
  31365. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  31366. * @returns the indices array or an empty array if the mesh has no geometry
  31367. */
  31368. Mesh.prototype.getIndices = function (copyWhenShared, forceCopy) {
  31369. if (!this._geometry) {
  31370. return [];
  31371. }
  31372. return this._geometry.getIndices(copyWhenShared, forceCopy);
  31373. };
  31374. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31375. get: function () {
  31376. return this._masterMesh !== null && this._masterMesh !== undefined;
  31377. },
  31378. enumerable: true,
  31379. configurable: true
  31380. });
  31381. /**
  31382. * Determine if the current mesh is ready to be rendered
  31383. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31384. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31385. * @returns true if all associated assets are ready (material, textures, shaders)
  31386. */
  31387. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31388. if (completeCheck === void 0) { completeCheck = false; }
  31389. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31390. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31391. return false;
  31392. }
  31393. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31394. return false;
  31395. }
  31396. if (!this.subMeshes || this.subMeshes.length === 0) {
  31397. return true;
  31398. }
  31399. if (!completeCheck) {
  31400. return true;
  31401. }
  31402. var engine = this.getEngine();
  31403. var scene = this.getScene();
  31404. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31405. this.computeWorldMatrix();
  31406. var mat = this.material || scene.defaultMaterial;
  31407. if (mat) {
  31408. if (mat.storeEffectOnSubMeshes) {
  31409. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31410. var subMesh = _a[_i];
  31411. var effectiveMaterial = subMesh.getMaterial();
  31412. if (effectiveMaterial) {
  31413. if (effectiveMaterial.storeEffectOnSubMeshes) {
  31414. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31415. return false;
  31416. }
  31417. }
  31418. else {
  31419. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31420. return false;
  31421. }
  31422. }
  31423. }
  31424. }
  31425. }
  31426. else {
  31427. if (!mat.isReady(this, hardwareInstancedRendering)) {
  31428. return false;
  31429. }
  31430. }
  31431. }
  31432. // Shadows
  31433. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  31434. var light = _c[_b];
  31435. var generator = light.getShadowGenerator();
  31436. if (generator) {
  31437. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  31438. var subMesh = _e[_d];
  31439. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  31440. return false;
  31441. }
  31442. }
  31443. }
  31444. }
  31445. // LOD
  31446. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  31447. var lod = _g[_f];
  31448. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  31449. return false;
  31450. }
  31451. }
  31452. return true;
  31453. };
  31454. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  31455. /**
  31456. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  31457. * This property is pertinent only for updatable parametric shapes.
  31458. */
  31459. get: function () {
  31460. return this._areNormalsFrozen;
  31461. },
  31462. enumerable: true,
  31463. configurable: true
  31464. });
  31465. /**
  31466. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31467. * It has no effect at all on other shapes.
  31468. * It prevents the mesh normals from being recomputed on next `positions` array update.
  31469. * Returns the Mesh.
  31470. */
  31471. Mesh.prototype.freezeNormals = function () {
  31472. this._areNormalsFrozen = true;
  31473. return this;
  31474. };
  31475. /**
  31476. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31477. * It has no effect at all on other shapes.
  31478. * It reactivates the mesh normals computation if it was previously frozen.
  31479. * Returns the Mesh.
  31480. */
  31481. Mesh.prototype.unfreezeNormals = function () {
  31482. this._areNormalsFrozen = false;
  31483. return this;
  31484. };
  31485. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  31486. /**
  31487. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  31488. */
  31489. set: function (count) {
  31490. this._overridenInstanceCount = count;
  31491. },
  31492. enumerable: true,
  31493. configurable: true
  31494. });
  31495. // Methods
  31496. /** @hidden */
  31497. Mesh.prototype._preActivate = function () {
  31498. var sceneRenderId = this.getScene().getRenderId();
  31499. if (this._preActivateId === sceneRenderId) {
  31500. return this;
  31501. }
  31502. this._preActivateId = sceneRenderId;
  31503. this._visibleInstances = null;
  31504. return this;
  31505. };
  31506. /** @hidden */
  31507. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  31508. if (this._visibleInstances) {
  31509. this._visibleInstances.intermediateDefaultRenderId = renderId;
  31510. }
  31511. return this;
  31512. };
  31513. /** @hidden */
  31514. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  31515. if (!this._visibleInstances) {
  31516. this._visibleInstances = {};
  31517. this._visibleInstances.defaultRenderId = renderId;
  31518. this._visibleInstances.selfDefaultRenderId = this._renderId;
  31519. }
  31520. if (!this._visibleInstances[renderId]) {
  31521. this._visibleInstances[renderId] = new Array();
  31522. }
  31523. this._visibleInstances[renderId].push(instance);
  31524. return this;
  31525. };
  31526. /**
  31527. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  31528. * This means the mesh underlying bounding box and sphere are recomputed.
  31529. * Returns the Mesh.
  31530. */
  31531. Mesh.prototype.refreshBoundingInfo = function () {
  31532. return this._refreshBoundingInfo(false);
  31533. };
  31534. /** @hidden */
  31535. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  31536. if (this._boundingInfo && this._boundingInfo.isLocked) {
  31537. return this;
  31538. }
  31539. var data = this._getPositionData(applySkeleton);
  31540. if (data) {
  31541. var bias = this.geometry ? this.geometry.boundingBias : null;
  31542. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices(), bias);
  31543. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  31544. }
  31545. if (this.subMeshes) {
  31546. for (var index = 0; index < this.subMeshes.length; index++) {
  31547. this.subMeshes[index].refreshBoundingInfo();
  31548. }
  31549. }
  31550. this._updateBoundingInfo();
  31551. return this;
  31552. };
  31553. Mesh.prototype._getPositionData = function (applySkeleton) {
  31554. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31555. if (data && applySkeleton && this.skeleton) {
  31556. data = BABYLON.Tools.Slice(data);
  31557. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31558. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31559. if (matricesWeightsData && matricesIndicesData) {
  31560. var needExtras = this.numBoneInfluencers > 4;
  31561. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  31562. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  31563. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  31564. var tempVector = BABYLON.Tmp.Vector3[0];
  31565. var finalMatrix = BABYLON.Tmp.Matrix[0];
  31566. var tempMatrix = BABYLON.Tmp.Matrix[1];
  31567. var matWeightIdx = 0;
  31568. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  31569. finalMatrix.reset();
  31570. var inf;
  31571. var weight;
  31572. for (inf = 0; inf < 4; inf++) {
  31573. weight = matricesWeightsData[matWeightIdx + inf];
  31574. if (weight > 0) {
  31575. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31576. finalMatrix.addToSelf(tempMatrix);
  31577. }
  31578. }
  31579. if (needExtras) {
  31580. for (inf = 0; inf < 4; inf++) {
  31581. weight = matricesWeightsExtraData[matWeightIdx + inf];
  31582. if (weight > 0) {
  31583. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31584. finalMatrix.addToSelf(tempMatrix);
  31585. }
  31586. }
  31587. }
  31588. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  31589. tempVector.toArray(data, index);
  31590. }
  31591. }
  31592. }
  31593. return data;
  31594. };
  31595. /** @hidden */
  31596. Mesh.prototype._createGlobalSubMesh = function (force) {
  31597. var totalVertices = this.getTotalVertices();
  31598. if (!totalVertices || !this.getIndices()) {
  31599. return null;
  31600. }
  31601. // Check if we need to recreate the submeshes
  31602. if (this.subMeshes && this.subMeshes.length > 0) {
  31603. var ib = this.getIndices();
  31604. if (!ib) {
  31605. return null;
  31606. }
  31607. var totalIndices = ib.length;
  31608. var needToRecreate = false;
  31609. if (force) {
  31610. needToRecreate = true;
  31611. }
  31612. else {
  31613. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31614. var submesh = _a[_i];
  31615. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  31616. needToRecreate = true;
  31617. break;
  31618. }
  31619. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  31620. needToRecreate = true;
  31621. break;
  31622. }
  31623. }
  31624. }
  31625. if (!needToRecreate) {
  31626. return this.subMeshes[0];
  31627. }
  31628. }
  31629. this.releaseSubMeshes();
  31630. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  31631. };
  31632. Mesh.prototype.subdivide = function (count) {
  31633. if (count < 1) {
  31634. return;
  31635. }
  31636. var totalIndices = this.getTotalIndices();
  31637. var subdivisionSize = (totalIndices / count) | 0;
  31638. var offset = 0;
  31639. // Ensure that subdivisionSize is a multiple of 3
  31640. while (subdivisionSize % 3 !== 0) {
  31641. subdivisionSize++;
  31642. }
  31643. this.releaseSubMeshes();
  31644. for (var index = 0; index < count; index++) {
  31645. if (offset >= totalIndices) {
  31646. break;
  31647. }
  31648. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  31649. offset += subdivisionSize;
  31650. }
  31651. this.synchronizeInstances();
  31652. };
  31653. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  31654. if (updatable === void 0) { updatable = false; }
  31655. if (!this._geometry) {
  31656. var vertexData = new BABYLON.VertexData();
  31657. vertexData.set(data, kind);
  31658. var scene = this.getScene();
  31659. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31660. }
  31661. else {
  31662. this._geometry.setVerticesData(kind, data, updatable, stride);
  31663. }
  31664. return this;
  31665. };
  31666. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  31667. if (updatable === void 0) { updatable = true; }
  31668. var vb = this.getVertexBuffer(kind);
  31669. if (!vb || vb.isUpdatable() === updatable) {
  31670. return;
  31671. }
  31672. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  31673. };
  31674. /**
  31675. * Sets the mesh VertexBuffer.
  31676. * Returns the Mesh.
  31677. */
  31678. Mesh.prototype.setVerticesBuffer = function (buffer) {
  31679. if (!this._geometry) {
  31680. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  31681. }
  31682. this._geometry.setVerticesBuffer(buffer);
  31683. return this;
  31684. };
  31685. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  31686. if (!this._geometry) {
  31687. return this;
  31688. }
  31689. if (!makeItUnique) {
  31690. this._geometry.updateVerticesData(kind, data, updateExtends);
  31691. }
  31692. else {
  31693. this.makeGeometryUnique();
  31694. this.updateVerticesData(kind, data, updateExtends, false);
  31695. }
  31696. return this;
  31697. };
  31698. /**
  31699. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  31700. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  31701. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  31702. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  31703. * Returns the Mesh.
  31704. */
  31705. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  31706. if (computeNormals === void 0) { computeNormals = true; }
  31707. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31708. if (!positions) {
  31709. return this;
  31710. }
  31711. positionFunction(positions);
  31712. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  31713. if (computeNormals) {
  31714. var indices = this.getIndices();
  31715. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31716. if (!normals) {
  31717. return this;
  31718. }
  31719. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  31720. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  31721. }
  31722. return this;
  31723. };
  31724. /**
  31725. * Creates a un-shared specific occurence of the geometry for the mesh.
  31726. * Returns the Mesh.
  31727. */
  31728. Mesh.prototype.makeGeometryUnique = function () {
  31729. if (!this._geometry) {
  31730. return this;
  31731. }
  31732. var oldGeometry = this._geometry;
  31733. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  31734. oldGeometry.releaseForMesh(this, true);
  31735. geometry.applyToMesh(this);
  31736. return this;
  31737. };
  31738. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  31739. if (totalVertices === void 0) { totalVertices = null; }
  31740. if (updatable === void 0) { updatable = false; }
  31741. if (!this._geometry) {
  31742. var vertexData = new BABYLON.VertexData();
  31743. vertexData.indices = indices;
  31744. var scene = this.getScene();
  31745. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31746. }
  31747. else {
  31748. this._geometry.setIndices(indices, totalVertices, updatable);
  31749. }
  31750. return this;
  31751. };
  31752. /**
  31753. * Update the current index buffer
  31754. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  31755. * Returns the Mesh.
  31756. */
  31757. Mesh.prototype.updateIndices = function (indices, offset) {
  31758. if (!this._geometry) {
  31759. return this;
  31760. }
  31761. this._geometry.updateIndices(indices, offset);
  31762. return this;
  31763. };
  31764. /**
  31765. * Invert the geometry to move from a right handed system to a left handed one.
  31766. * Returns the Mesh.
  31767. */
  31768. Mesh.prototype.toLeftHanded = function () {
  31769. if (!this._geometry) {
  31770. return this;
  31771. }
  31772. this._geometry.toLeftHanded();
  31773. return this;
  31774. };
  31775. /** @hidden */
  31776. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  31777. if (!this._geometry) {
  31778. return this;
  31779. }
  31780. var engine = this.getScene().getEngine();
  31781. // Wireframe
  31782. var indexToBind;
  31783. if (this._unIndexed) {
  31784. indexToBind = null;
  31785. }
  31786. else {
  31787. switch (fillMode) {
  31788. case BABYLON.Material.PointFillMode:
  31789. indexToBind = null;
  31790. break;
  31791. case BABYLON.Material.WireFrameFillMode:
  31792. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  31793. break;
  31794. default:
  31795. case BABYLON.Material.TriangleFillMode:
  31796. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  31797. break;
  31798. }
  31799. }
  31800. // VBOs
  31801. this._geometry._bind(effect, indexToBind);
  31802. return this;
  31803. };
  31804. /** @hidden */
  31805. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  31806. if (alternate === void 0) { alternate = false; }
  31807. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  31808. return this;
  31809. }
  31810. if (this._onBeforeDrawObservable) {
  31811. this._onBeforeDrawObservable.notifyObservers(this);
  31812. }
  31813. var scene = this.getScene();
  31814. var engine = scene.getEngine();
  31815. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  31816. // or triangles as points
  31817. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  31818. }
  31819. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  31820. // Triangles as wireframe
  31821. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  31822. }
  31823. else {
  31824. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  31825. }
  31826. if (scene._isAlternateRenderingEnabled && !alternate) {
  31827. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  31828. if (!effect || !scene.activeCamera) {
  31829. return this;
  31830. }
  31831. scene._switchToAlternateCameraConfiguration(true);
  31832. this._effectiveMaterial.bindView(effect);
  31833. this._effectiveMaterial.bindViewProjection(effect);
  31834. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  31835. this._draw(subMesh, fillMode, instancesCount, true);
  31836. engine.setViewport(scene.activeCamera.viewport);
  31837. scene._switchToAlternateCameraConfiguration(false);
  31838. this._effectiveMaterial.bindView(effect);
  31839. this._effectiveMaterial.bindViewProjection(effect);
  31840. }
  31841. return this;
  31842. };
  31843. /**
  31844. * Registers for this mesh a javascript function called just before the rendering process.
  31845. * This function is passed the current mesh.
  31846. * Return the Mesh.
  31847. */
  31848. Mesh.prototype.registerBeforeRender = function (func) {
  31849. this.onBeforeRenderObservable.add(func);
  31850. return this;
  31851. };
  31852. /**
  31853. * Disposes a previously registered javascript function called before the rendering.
  31854. * This function is passed the current mesh.
  31855. * Returns the Mesh.
  31856. */
  31857. Mesh.prototype.unregisterBeforeRender = function (func) {
  31858. this.onBeforeRenderObservable.removeCallback(func);
  31859. return this;
  31860. };
  31861. /**
  31862. * Registers for this mesh a javascript function called just after the rendering is complete.
  31863. * This function is passed the current mesh.
  31864. * Returns the Mesh.
  31865. */
  31866. Mesh.prototype.registerAfterRender = function (func) {
  31867. this.onAfterRenderObservable.add(func);
  31868. return this;
  31869. };
  31870. /**
  31871. * Disposes a previously registered javascript function called after the rendering.
  31872. * This function is passed the current mesh.
  31873. * Return the Mesh.
  31874. */
  31875. Mesh.prototype.unregisterAfterRender = function (func) {
  31876. this.onAfterRenderObservable.removeCallback(func);
  31877. return this;
  31878. };
  31879. /** @hidden */
  31880. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  31881. var scene = this.getScene();
  31882. this._batchCache.mustReturn = false;
  31883. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  31884. this._batchCache.visibleInstances[subMeshId] = null;
  31885. if (this._visibleInstances) {
  31886. var currentRenderId = scene.getRenderId();
  31887. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  31888. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  31889. var selfRenderId = this._renderId;
  31890. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  31891. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  31892. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  31893. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  31894. }
  31895. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  31896. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  31897. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  31898. this._batchCache.mustReturn = true;
  31899. return this._batchCache;
  31900. }
  31901. if (currentRenderId !== selfRenderId) {
  31902. this._batchCache.renderSelf[subMeshId] = false;
  31903. }
  31904. }
  31905. this._renderIdForInstances[subMeshId] = currentRenderId;
  31906. }
  31907. return this._batchCache;
  31908. };
  31909. /** @hidden */
  31910. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  31911. var visibleInstances = batch.visibleInstances[subMesh._id];
  31912. if (!visibleInstances) {
  31913. return this;
  31914. }
  31915. var matricesCount = visibleInstances.length + 1;
  31916. var bufferSize = matricesCount * 16 * 4;
  31917. var currentInstancesBufferSize = this._instancesBufferSize;
  31918. var instancesBuffer = this._instancesBuffer;
  31919. while (this._instancesBufferSize < bufferSize) {
  31920. this._instancesBufferSize *= 2;
  31921. }
  31922. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  31923. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  31924. }
  31925. var offset = 0;
  31926. var instancesCount = 0;
  31927. var world = this.getWorldMatrix();
  31928. if (batch.renderSelf[subMesh._id]) {
  31929. world.copyToArray(this._instancesData, offset);
  31930. offset += 16;
  31931. instancesCount++;
  31932. }
  31933. if (visibleInstances) {
  31934. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  31935. var instance = visibleInstances[instanceIndex];
  31936. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  31937. offset += 16;
  31938. instancesCount++;
  31939. }
  31940. }
  31941. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  31942. if (instancesBuffer) {
  31943. instancesBuffer.dispose();
  31944. }
  31945. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  31946. this._instancesBuffer = instancesBuffer;
  31947. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  31948. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  31949. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  31950. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  31951. }
  31952. else {
  31953. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  31954. }
  31955. this._bind(subMesh, effect, fillMode);
  31956. this._draw(subMesh, fillMode, instancesCount);
  31957. engine.unbindInstanceAttributes();
  31958. return this;
  31959. };
  31960. /** @hidden */
  31961. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  31962. var scene = this.getScene();
  31963. var engine = scene.getEngine();
  31964. if (hardwareInstancedRendering) {
  31965. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  31966. }
  31967. else {
  31968. if (batch.renderSelf[subMesh._id]) {
  31969. // Draw
  31970. if (onBeforeDraw) {
  31971. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  31972. }
  31973. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  31974. }
  31975. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  31976. if (visibleInstancesForSubMesh) {
  31977. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  31978. var instance = visibleInstancesForSubMesh[instanceIndex];
  31979. // World
  31980. var world = instance.getWorldMatrix();
  31981. if (onBeforeDraw) {
  31982. onBeforeDraw(true, world, effectiveMaterial);
  31983. }
  31984. // Draw
  31985. this._draw(subMesh, fillMode);
  31986. }
  31987. }
  31988. }
  31989. return this;
  31990. };
  31991. /**
  31992. * 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
  31993. * @param subMesh defines the subMesh to render
  31994. * @param enableAlphaMode defines if alpha mode can be changed
  31995. * @returns the current mesh
  31996. */
  31997. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  31998. this._checkOcclusionQuery();
  31999. if (this._isOccluded) {
  32000. return this;
  32001. }
  32002. var scene = this.getScene();
  32003. // Managing instances
  32004. var batch = this._getInstancesRenderList(subMesh._id);
  32005. if (batch.mustReturn) {
  32006. return this;
  32007. }
  32008. // Checking geometry state
  32009. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32010. return this;
  32011. }
  32012. if (this._onBeforeRenderObservable) {
  32013. this._onBeforeRenderObservable.notifyObservers(this);
  32014. }
  32015. var engine = scene.getEngine();
  32016. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32017. // Material
  32018. var material = subMesh.getMaterial();
  32019. if (!material) {
  32020. return this;
  32021. }
  32022. this._effectiveMaterial = material;
  32023. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32024. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32025. return this;
  32026. }
  32027. }
  32028. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32029. return this;
  32030. }
  32031. // Alpha mode
  32032. if (enableAlphaMode) {
  32033. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32034. }
  32035. for (var _i = 0, _a = scene._beforeRenderingMeshStage; _i < _a.length; _i++) {
  32036. var step = _a[_i];
  32037. step.action(this, subMesh, batch);
  32038. }
  32039. var effect;
  32040. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32041. effect = subMesh.effect;
  32042. }
  32043. else {
  32044. effect = this._effectiveMaterial.getEffect();
  32045. }
  32046. if (!effect) {
  32047. return this;
  32048. }
  32049. var sideOrientation = this.overrideMaterialSideOrientation;
  32050. if (sideOrientation == null) {
  32051. sideOrientation = this._effectiveMaterial.sideOrientation;
  32052. if (this._getWorldMatrixDeterminant() < 0) {
  32053. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32054. }
  32055. }
  32056. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32057. if (this._effectiveMaterial.forceDepthWrite) {
  32058. engine.setDepthWrite(true);
  32059. }
  32060. // Bind
  32061. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32062. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32063. this._bind(subMesh, effect, fillMode);
  32064. }
  32065. var world = this.getWorldMatrix();
  32066. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32067. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32068. }
  32069. else {
  32070. this._effectiveMaterial.bind(world, this);
  32071. }
  32072. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32073. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32074. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32075. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32076. }
  32077. // Draw
  32078. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32079. // Unbind
  32080. this._effectiveMaterial.unbind();
  32081. for (var _b = 0, _c = scene._afterRenderingMeshStage; _b < _c.length; _b++) {
  32082. var step = _c[_b];
  32083. step.action(this, subMesh, batch);
  32084. }
  32085. if (this._onAfterRenderObservable) {
  32086. this._onAfterRenderObservable.notifyObservers(this);
  32087. }
  32088. return this;
  32089. };
  32090. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32091. if (isInstance && effectiveMaterial) {
  32092. effectiveMaterial.bindOnlyWorldMatrix(world);
  32093. }
  32094. };
  32095. /**
  32096. * Returns an array populated with IParticleSystem objects whose the mesh is the emitter.
  32097. */
  32098. Mesh.prototype.getEmittedParticleSystems = function () {
  32099. var results = new Array();
  32100. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32101. var particleSystem = this.getScene().particleSystems[index];
  32102. if (particleSystem.emitter === this) {
  32103. results.push(particleSystem);
  32104. }
  32105. }
  32106. return results;
  32107. };
  32108. /**
  32109. * Returns an array populated with IParticleSystem objects whose the mesh or its children are the emitter.
  32110. */
  32111. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  32112. var results = new Array();
  32113. var descendants = this.getDescendants();
  32114. descendants.push(this);
  32115. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32116. var particleSystem = this.getScene().particleSystems[index];
  32117. var emitter = particleSystem.emitter;
  32118. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  32119. results.push(particleSystem);
  32120. }
  32121. }
  32122. return results;
  32123. };
  32124. /**
  32125. * Normalize matrix weights so that all vertices have a total weight set to 1
  32126. */
  32127. Mesh.prototype.cleanMatrixWeights = function () {
  32128. var epsilon = 1e-3;
  32129. var noInfluenceBoneIndex = 0.0;
  32130. if (this.skeleton) {
  32131. noInfluenceBoneIndex = this.skeleton.bones.length;
  32132. }
  32133. else {
  32134. return;
  32135. }
  32136. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32137. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32138. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32139. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  32140. var influencers = this.numBoneInfluencers;
  32141. var size = matricesWeights.length;
  32142. for (var i = 0; i < size; i += 4) {
  32143. var weight = 0.0;
  32144. var firstZeroWeight = -1;
  32145. for (var j = 0; j < 4; j++) {
  32146. var w = matricesWeights[i + j];
  32147. weight += w;
  32148. if (w < epsilon && firstZeroWeight < 0) {
  32149. firstZeroWeight = j;
  32150. }
  32151. }
  32152. if (matricesWeightsExtra) {
  32153. for (var j = 0; j < 4; j++) {
  32154. var w = matricesWeightsExtra[i + j];
  32155. weight += w;
  32156. if (w < epsilon && firstZeroWeight < 0) {
  32157. firstZeroWeight = j + 4;
  32158. }
  32159. }
  32160. }
  32161. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32162. firstZeroWeight = influencers - 1;
  32163. }
  32164. if (weight > epsilon) {
  32165. var mweight = 1.0 / weight;
  32166. for (var j = 0; j < 4; j++) {
  32167. matricesWeights[i + j] *= mweight;
  32168. }
  32169. if (matricesWeightsExtra) {
  32170. for (var j = 0; j < 4; j++) {
  32171. matricesWeightsExtra[i + j] *= mweight;
  32172. }
  32173. }
  32174. }
  32175. else {
  32176. if (firstZeroWeight >= 4) {
  32177. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32178. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32179. }
  32180. else {
  32181. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32182. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32183. }
  32184. }
  32185. }
  32186. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32187. if (matricesIndicesExtra) {
  32188. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32189. }
  32190. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  32191. if (matricesWeightsExtra) {
  32192. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);
  32193. }
  32194. };
  32195. /** @hidden */
  32196. Mesh.prototype._checkDelayState = function () {
  32197. var scene = this.getScene();
  32198. if (this._geometry) {
  32199. this._geometry.load(scene);
  32200. }
  32201. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32202. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32203. this._queueLoad(scene);
  32204. }
  32205. return this;
  32206. };
  32207. Mesh.prototype._queueLoad = function (scene) {
  32208. var _this = this;
  32209. scene._addPendingData(this);
  32210. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32211. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32212. if (data instanceof ArrayBuffer) {
  32213. _this._delayLoadingFunction(data, _this);
  32214. }
  32215. else {
  32216. _this._delayLoadingFunction(JSON.parse(data), _this);
  32217. }
  32218. _this.instances.forEach(function (instance) {
  32219. instance._syncSubMeshes();
  32220. });
  32221. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32222. scene._removePendingData(_this);
  32223. }, function () { }, scene.database, getBinaryData);
  32224. return this;
  32225. };
  32226. /**
  32227. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  32228. * A mesh is in the frustum if its bounding box intersects the frustum
  32229. * @param frustumPlanes defines the frustum to test
  32230. * @returns true if the mesh is in the frustum planes
  32231. */
  32232. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32233. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32234. return false;
  32235. }
  32236. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32237. return false;
  32238. }
  32239. this._checkDelayState();
  32240. return true;
  32241. };
  32242. /**
  32243. * Sets the mesh material by the material or multiMaterial `id` property.
  32244. * The material `id` is a string identifying the material or the multiMaterial.
  32245. * This method returns the Mesh.
  32246. */
  32247. Mesh.prototype.setMaterialByID = function (id) {
  32248. var materials = this.getScene().materials;
  32249. var index;
  32250. for (index = materials.length - 1; index > -1; index--) {
  32251. if (materials[index].id === id) {
  32252. this.material = materials[index];
  32253. return this;
  32254. }
  32255. }
  32256. // Multi
  32257. var multiMaterials = this.getScene().multiMaterials;
  32258. for (index = multiMaterials.length - 1; index > -1; index--) {
  32259. if (multiMaterials[index].id === id) {
  32260. this.material = multiMaterials[index];
  32261. return this;
  32262. }
  32263. }
  32264. return this;
  32265. };
  32266. /**
  32267. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32268. */
  32269. Mesh.prototype.getAnimatables = function () {
  32270. var results = new Array();
  32271. if (this.material) {
  32272. results.push(this.material);
  32273. }
  32274. if (this.skeleton) {
  32275. results.push(this.skeleton);
  32276. }
  32277. return results;
  32278. };
  32279. /**
  32280. * Modifies the mesh geometry according to the passed transformation matrix.
  32281. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32282. * The mesh normals are modified using the same transformation.
  32283. * tuto : http://doc.babylonjs.com/resources/baking_transformations
  32284. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32285. * Returns the Mesh.
  32286. */
  32287. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32288. // Position
  32289. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32290. return this;
  32291. }
  32292. var submeshes = this.subMeshes.splice(0);
  32293. this._resetPointsArrayCache();
  32294. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32295. var temp = new Array();
  32296. var index;
  32297. for (index = 0; index < data.length; index += 3) {
  32298. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32299. }
  32300. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32301. // Normals
  32302. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32303. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32304. temp = [];
  32305. for (index = 0; index < data.length; index += 3) {
  32306. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32307. }
  32308. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32309. }
  32310. // flip faces?
  32311. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32312. this.flipFaces();
  32313. }
  32314. // Restore submeshes
  32315. this.releaseSubMeshes();
  32316. this.subMeshes = submeshes;
  32317. return this;
  32318. };
  32319. /**
  32320. * Modifies the mesh geometry according to its own current World Matrix.
  32321. * The mesh World Matrix is then reset.
  32322. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32323. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  32324. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32325. * Returns the Mesh.
  32326. */
  32327. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32328. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32329. this.scaling.copyFromFloats(1, 1, 1);
  32330. this.position.copyFromFloats(0, 0, 0);
  32331. this.rotation.copyFromFloats(0, 0, 0);
  32332. //only if quaternion is already set
  32333. if (this.rotationQuaternion) {
  32334. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32335. }
  32336. this._worldMatrix = BABYLON.Matrix.Identity();
  32337. return this;
  32338. };
  32339. Object.defineProperty(Mesh.prototype, "_positions", {
  32340. // Cache
  32341. get: function () {
  32342. if (this._geometry) {
  32343. return this._geometry._positions;
  32344. }
  32345. return null;
  32346. },
  32347. enumerable: true,
  32348. configurable: true
  32349. });
  32350. /** @hidden */
  32351. Mesh.prototype._resetPointsArrayCache = function () {
  32352. if (this._geometry) {
  32353. this._geometry._resetPointsArrayCache();
  32354. }
  32355. return this;
  32356. };
  32357. /** @hidden */
  32358. Mesh.prototype._generatePointsArray = function () {
  32359. if (this._geometry) {
  32360. return this._geometry._generatePointsArray();
  32361. }
  32362. return false;
  32363. };
  32364. /**
  32365. * Returns a new Mesh object generated from the current mesh properties.
  32366. * This method must not get confused with createInstance().
  32367. * The parameter `name` is a string, the name given to the new mesh.
  32368. * The optional parameter `newParent` can be any Node object (default `null`).
  32369. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  32370. * 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.
  32371. */
  32372. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32373. if (name === void 0) { name = ""; }
  32374. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32375. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32376. };
  32377. /**
  32378. * Releases resources associated with this mesh.
  32379. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32380. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32381. */
  32382. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32383. var _this = this;
  32384. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32385. this.morphTargetManager = null;
  32386. if (this._geometry) {
  32387. this._geometry.releaseForMesh(this, true);
  32388. }
  32389. if (this._onBeforeDrawObservable) {
  32390. this._onBeforeDrawObservable.clear();
  32391. }
  32392. if (this._onBeforeRenderObservable) {
  32393. this._onBeforeRenderObservable.clear();
  32394. }
  32395. if (this._onAfterRenderObservable) {
  32396. this._onAfterRenderObservable.clear();
  32397. }
  32398. // Sources
  32399. var meshes = this.getScene().meshes;
  32400. meshes.forEach(function (abstractMesh) {
  32401. var mesh = abstractMesh;
  32402. if (mesh._source && mesh._source === _this) {
  32403. mesh._source = null;
  32404. }
  32405. });
  32406. this._source = null;
  32407. // Instances
  32408. if (this._instancesBuffer) {
  32409. this._instancesBuffer.dispose();
  32410. this._instancesBuffer = null;
  32411. }
  32412. while (this.instances.length) {
  32413. this.instances[0].dispose();
  32414. }
  32415. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32416. };
  32417. /**
  32418. * Modifies the mesh geometry according to a displacement map.
  32419. * 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.
  32420. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32421. * This method returns nothing.
  32422. * @param url is a string, the URL from the image file is to be downloaded.
  32423. * @param minHeight is the lower limit of the displacement.
  32424. * @param maxHeight is the upper limit of the displacement.
  32425. * @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.
  32426. * @param uvOffset is an optional vector2 used to offset UV.
  32427. * @param uvScale is an optional vector2 used to scale UV.
  32428. * @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.
  32429. * @returns the Mesh.
  32430. */
  32431. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale, forceUpdate) {
  32432. var _this = this;
  32433. if (forceUpdate === void 0) { forceUpdate = false; }
  32434. var scene = this.getScene();
  32435. var onload = function (img) {
  32436. // Getting height map data
  32437. var canvas = document.createElement("canvas");
  32438. var context = canvas.getContext("2d");
  32439. var heightMapWidth = img.width;
  32440. var heightMapHeight = img.height;
  32441. canvas.width = heightMapWidth;
  32442. canvas.height = heightMapHeight;
  32443. context.drawImage(img, 0, 0);
  32444. // Create VertexData from map data
  32445. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  32446. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  32447. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate);
  32448. //execute success callback, if set
  32449. if (onSuccess) {
  32450. onSuccess(_this);
  32451. }
  32452. };
  32453. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  32454. return this;
  32455. };
  32456. /**
  32457. * Modifies the mesh geometry according to a displacementMap buffer.
  32458. * 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.
  32459. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32460. * @param buffer is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel.
  32461. * @param heightMapWidth is the width of the buffer image.
  32462. * @param heightMapHeight is the height of the buffer image.
  32463. * @param minHeight is the lower limit of the displacement.
  32464. * @param maxHeight is the upper limit of the displacement.
  32465. * @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.
  32466. * @param uvOffset is an optional vector2 used to offset UV.
  32467. * @param uvScale is an optional vector2 used to scale UV.
  32468. * @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.
  32469. * @returns the Mesh.
  32470. */
  32471. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate) {
  32472. if (forceUpdate === void 0) { forceUpdate = false; }
  32473. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  32474. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  32475. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32476. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  32477. return this;
  32478. }
  32479. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, true, true);
  32480. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32481. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32482. var position = BABYLON.Vector3.Zero();
  32483. var normal = BABYLON.Vector3.Zero();
  32484. var uv = BABYLON.Vector2.Zero();
  32485. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  32486. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  32487. for (var index = 0; index < positions.length; index += 3) {
  32488. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  32489. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  32490. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  32491. // Compute height
  32492. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  32493. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  32494. var pos = (u + v * heightMapWidth) * 4;
  32495. var r = buffer[pos] / 255.0;
  32496. var g = buffer[pos + 1] / 255.0;
  32497. var b = buffer[pos + 2] / 255.0;
  32498. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  32499. normal.normalize();
  32500. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  32501. position = position.add(normal);
  32502. position.toArray(positions, index);
  32503. }
  32504. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  32505. if (forceUpdate) {
  32506. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32507. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32508. }
  32509. else {
  32510. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32511. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32512. }
  32513. return this;
  32514. };
  32515. /**
  32516. * Modify the mesh to get a flat shading rendering.
  32517. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  32518. * This method returns the Mesh.
  32519. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  32520. */
  32521. Mesh.prototype.convertToFlatShadedMesh = function () {
  32522. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  32523. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32524. var kinds = this.getVerticesDataKinds();
  32525. var vbs = {};
  32526. var data = {};
  32527. var newdata = {};
  32528. var updatableNormals = false;
  32529. var kindIndex;
  32530. var kind;
  32531. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32532. kind = kinds[kindIndex];
  32533. var vertexBuffer = this.getVertexBuffer(kind);
  32534. if (kind === BABYLON.VertexBuffer.NormalKind) {
  32535. updatableNormals = vertexBuffer.isUpdatable();
  32536. kinds.splice(kindIndex, 1);
  32537. kindIndex--;
  32538. continue;
  32539. }
  32540. vbs[kind] = vertexBuffer;
  32541. data[kind] = vbs[kind].getData();
  32542. newdata[kind] = [];
  32543. }
  32544. // Save previous submeshes
  32545. var previousSubmeshes = this.subMeshes.slice(0);
  32546. var indices = this.getIndices();
  32547. var totalIndices = this.getTotalIndices();
  32548. // Generating unique vertices per face
  32549. var index;
  32550. for (index = 0; index < totalIndices; index++) {
  32551. var vertexIndex = indices[index];
  32552. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32553. kind = kinds[kindIndex];
  32554. var stride = vbs[kind].getStrideSize();
  32555. for (var offset = 0; offset < stride; offset++) {
  32556. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32557. }
  32558. }
  32559. }
  32560. // Updating faces & normal
  32561. var normals = [];
  32562. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  32563. for (index = 0; index < totalIndices; index += 3) {
  32564. indices[index] = index;
  32565. indices[index + 1] = index + 1;
  32566. indices[index + 2] = index + 2;
  32567. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  32568. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  32569. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  32570. var p1p2 = p1.subtract(p2);
  32571. var p3p2 = p3.subtract(p2);
  32572. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  32573. // Store same normals for every vertex
  32574. for (var localIndex = 0; localIndex < 3; localIndex++) {
  32575. normals.push(normal.x);
  32576. normals.push(normal.y);
  32577. normals.push(normal.z);
  32578. }
  32579. }
  32580. this.setIndices(indices);
  32581. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  32582. // Updating vertex buffers
  32583. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32584. kind = kinds[kindIndex];
  32585. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32586. }
  32587. // Updating submeshes
  32588. this.releaseSubMeshes();
  32589. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32590. var previousOne = previousSubmeshes[submeshIndex];
  32591. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32592. }
  32593. this.synchronizeInstances();
  32594. return this;
  32595. };
  32596. /**
  32597. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  32598. * In other words, more vertices, no more indices and a single bigger VBO.
  32599. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  32600. * Returns the Mesh.
  32601. */
  32602. Mesh.prototype.convertToUnIndexedMesh = function () {
  32603. /// <summary>Remove indices by unfolding faces into buffers</summary>
  32604. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32605. var kinds = this.getVerticesDataKinds();
  32606. var vbs = {};
  32607. var data = {};
  32608. var newdata = {};
  32609. var kindIndex;
  32610. var kind;
  32611. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32612. kind = kinds[kindIndex];
  32613. var vertexBuffer = this.getVertexBuffer(kind);
  32614. vbs[kind] = vertexBuffer;
  32615. data[kind] = vbs[kind].getData();
  32616. newdata[kind] = [];
  32617. }
  32618. // Save previous submeshes
  32619. var previousSubmeshes = this.subMeshes.slice(0);
  32620. var indices = this.getIndices();
  32621. var totalIndices = this.getTotalIndices();
  32622. // Generating unique vertices per face
  32623. var index;
  32624. for (index = 0; index < totalIndices; index++) {
  32625. var vertexIndex = indices[index];
  32626. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32627. kind = kinds[kindIndex];
  32628. var stride = vbs[kind].getStrideSize();
  32629. for (var offset = 0; offset < stride; offset++) {
  32630. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32631. }
  32632. }
  32633. }
  32634. // Updating indices
  32635. for (index = 0; index < totalIndices; index += 3) {
  32636. indices[index] = index;
  32637. indices[index + 1] = index + 1;
  32638. indices[index + 2] = index + 2;
  32639. }
  32640. this.setIndices(indices);
  32641. // Updating vertex buffers
  32642. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32643. kind = kinds[kindIndex];
  32644. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32645. }
  32646. // Updating submeshes
  32647. this.releaseSubMeshes();
  32648. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32649. var previousOne = previousSubmeshes[submeshIndex];
  32650. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32651. }
  32652. this._unIndexed = true;
  32653. this.synchronizeInstances();
  32654. return this;
  32655. };
  32656. /**
  32657. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  32658. * This method returns the Mesh.
  32659. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  32660. */
  32661. Mesh.prototype.flipFaces = function (flipNormals) {
  32662. if (flipNormals === void 0) { flipNormals = false; }
  32663. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  32664. var i;
  32665. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  32666. for (i = 0; i < vertex_data.normals.length; i++) {
  32667. vertex_data.normals[i] *= -1;
  32668. }
  32669. }
  32670. if (vertex_data.indices) {
  32671. var temp;
  32672. for (i = 0; i < vertex_data.indices.length; i += 3) {
  32673. // reassign indices
  32674. temp = vertex_data.indices[i + 1];
  32675. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  32676. vertex_data.indices[i + 2] = temp;
  32677. }
  32678. }
  32679. vertex_data.applyToMesh(this);
  32680. return this;
  32681. };
  32682. // Instances
  32683. /**
  32684. * Creates a new InstancedMesh object from the mesh model.
  32685. * An instance shares the same properties and the same material than its model.
  32686. * Please make sure to call mesh.makeGeometryUnique() if you are calling createInstance on a previously cloned mesh.
  32687. * Only these properties of each instance can then be set individually :
  32688. * - position
  32689. * - rotation
  32690. * - rotationQuaternion
  32691. * - setPivotMatrix
  32692. * - scaling
  32693. *
  32694. * @see http://doc.babylonjs.com/how_to/how_to_use_instances
  32695. * Warning : this method is not supported for Line mesh and LineSystem
  32696. */
  32697. Mesh.prototype.createInstance = function (name) {
  32698. return new BABYLON.InstancedMesh(name, this);
  32699. };
  32700. /**
  32701. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  32702. * After this call, all the mesh instances have the same submeshes than the current mesh.
  32703. * This method returns the Mesh.
  32704. */
  32705. Mesh.prototype.synchronizeInstances = function () {
  32706. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  32707. var instance = this.instances[instanceIndex];
  32708. instance._syncSubMeshes();
  32709. }
  32710. return this;
  32711. };
  32712. /**
  32713. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  32714. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  32715. * This should be used together with the simplification to avoid disappearing triangles.
  32716. * Returns the Mesh.
  32717. * @param successCallback an optional success callback to be called after the optimization finished.
  32718. */
  32719. Mesh.prototype.optimizeIndices = function (successCallback) {
  32720. var _this = this;
  32721. var indices = this.getIndices();
  32722. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32723. if (!positions || !indices) {
  32724. return this;
  32725. }
  32726. var vectorPositions = new Array();
  32727. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  32728. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  32729. }
  32730. var dupes = new Array();
  32731. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  32732. var realPos = vectorPositions.length - 1 - iteration;
  32733. var testedPosition = vectorPositions[realPos];
  32734. for (var j = 0; j < realPos; ++j) {
  32735. var againstPosition = vectorPositions[j];
  32736. if (testedPosition.equals(againstPosition)) {
  32737. dupes[realPos] = j;
  32738. break;
  32739. }
  32740. }
  32741. }, function () {
  32742. for (var i = 0; i < indices.length; ++i) {
  32743. indices[i] = dupes[indices[i]] || indices[i];
  32744. }
  32745. //indices are now reordered
  32746. var originalSubMeshes = _this.subMeshes.slice(0);
  32747. _this.setIndices(indices);
  32748. _this.subMeshes = originalSubMeshes;
  32749. if (successCallback) {
  32750. successCallback(_this);
  32751. }
  32752. });
  32753. return this;
  32754. };
  32755. Mesh.prototype.serialize = function (serializationObject) {
  32756. serializationObject.name = this.name;
  32757. serializationObject.id = this.id;
  32758. serializationObject.type = this.getClassName();
  32759. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  32760. serializationObject.tags = BABYLON.Tags.GetTags(this);
  32761. }
  32762. serializationObject.position = this.position.asArray();
  32763. if (this.rotationQuaternion) {
  32764. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  32765. }
  32766. else if (this.rotation) {
  32767. serializationObject.rotation = this.rotation.asArray();
  32768. }
  32769. serializationObject.scaling = this.scaling.asArray();
  32770. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  32771. serializationObject.isEnabled = this.isEnabled(false);
  32772. serializationObject.isVisible = this.isVisible;
  32773. serializationObject.infiniteDistance = this.infiniteDistance;
  32774. serializationObject.pickable = this.isPickable;
  32775. serializationObject.receiveShadows = this.receiveShadows;
  32776. serializationObject.billboardMode = this.billboardMode;
  32777. serializationObject.visibility = this.visibility;
  32778. serializationObject.checkCollisions = this.checkCollisions;
  32779. serializationObject.isBlocker = this.isBlocker;
  32780. // Parent
  32781. if (this.parent) {
  32782. serializationObject.parentId = this.parent.id;
  32783. }
  32784. // Geometry
  32785. serializationObject.isUnIndexed = this.isUnIndexed;
  32786. var geometry = this._geometry;
  32787. if (geometry) {
  32788. var geometryId = geometry.id;
  32789. serializationObject.geometryId = geometryId;
  32790. // SubMeshes
  32791. serializationObject.subMeshes = [];
  32792. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  32793. var subMesh = this.subMeshes[subIndex];
  32794. serializationObject.subMeshes.push({
  32795. materialIndex: subMesh.materialIndex,
  32796. verticesStart: subMesh.verticesStart,
  32797. verticesCount: subMesh.verticesCount,
  32798. indexStart: subMesh.indexStart,
  32799. indexCount: subMesh.indexCount
  32800. });
  32801. }
  32802. }
  32803. // Material
  32804. if (this.material) {
  32805. serializationObject.materialId = this.material.id;
  32806. }
  32807. else {
  32808. this.material = null;
  32809. }
  32810. // Morph targets
  32811. if (this.morphTargetManager) {
  32812. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  32813. }
  32814. // Skeleton
  32815. if (this.skeleton) {
  32816. serializationObject.skeletonId = this.skeleton.id;
  32817. }
  32818. // Physics
  32819. //TODO implement correct serialization for physics impostors.
  32820. var impostor = this.getPhysicsImpostor();
  32821. if (impostor) {
  32822. serializationObject.physicsMass = impostor.getParam("mass");
  32823. serializationObject.physicsFriction = impostor.getParam("friction");
  32824. serializationObject.physicsRestitution = impostor.getParam("mass");
  32825. serializationObject.physicsImpostor = impostor.type;
  32826. }
  32827. // Metadata
  32828. if (this.metadata) {
  32829. serializationObject.metadata = this.metadata;
  32830. }
  32831. // Instances
  32832. serializationObject.instances = [];
  32833. for (var index = 0; index < this.instances.length; index++) {
  32834. var instance = this.instances[index];
  32835. if (instance.doNotSerialize) {
  32836. continue;
  32837. }
  32838. var serializationInstance = {
  32839. name: instance.name,
  32840. id: instance.id,
  32841. position: instance.position.asArray(),
  32842. scaling: instance.scaling.asArray()
  32843. };
  32844. if (instance.parent) {
  32845. serializationInstance.parentId = instance.parent.id;
  32846. }
  32847. if (instance.rotationQuaternion) {
  32848. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  32849. }
  32850. else if (instance.rotation) {
  32851. serializationInstance.rotation = instance.rotation.asArray();
  32852. }
  32853. serializationObject.instances.push(serializationInstance);
  32854. // Animations
  32855. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  32856. serializationInstance.ranges = instance.serializeAnimationRanges();
  32857. }
  32858. //
  32859. // Animations
  32860. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  32861. serializationObject.ranges = this.serializeAnimationRanges();
  32862. // Layer mask
  32863. serializationObject.layerMask = this.layerMask;
  32864. // Alpha
  32865. serializationObject.alphaIndex = this.alphaIndex;
  32866. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  32867. // Overlay
  32868. serializationObject.overlayAlpha = this.overlayAlpha;
  32869. serializationObject.overlayColor = this.overlayColor.asArray();
  32870. serializationObject.renderOverlay = this.renderOverlay;
  32871. // Fog
  32872. serializationObject.applyFog = this.applyFog;
  32873. // Action Manager
  32874. if (this.actionManager) {
  32875. serializationObject.actions = this.actionManager.serialize(this.name);
  32876. }
  32877. };
  32878. /** @hidden */
  32879. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  32880. if (!this.geometry) {
  32881. return;
  32882. }
  32883. this._markSubMeshesAsAttributesDirty();
  32884. var morphTargetManager = this._morphTargetManager;
  32885. if (morphTargetManager && morphTargetManager.vertexCount) {
  32886. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  32887. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  32888. this.morphTargetManager = null;
  32889. return;
  32890. }
  32891. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  32892. var morphTarget = morphTargetManager.getActiveTarget(index);
  32893. var positions = morphTarget.getPositions();
  32894. if (!positions) {
  32895. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  32896. return;
  32897. }
  32898. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  32899. var normals = morphTarget.getNormals();
  32900. if (normals) {
  32901. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  32902. }
  32903. var tangents = morphTarget.getTangents();
  32904. if (tangents) {
  32905. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  32906. }
  32907. }
  32908. }
  32909. else {
  32910. var index = 0;
  32911. // Positions
  32912. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  32913. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  32914. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  32915. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  32916. }
  32917. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  32918. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  32919. }
  32920. index++;
  32921. }
  32922. }
  32923. };
  32924. // Statics
  32925. /**
  32926. * Returns a new Mesh object parsed from the source provided.
  32927. * The parameter `parsedMesh` is the source.
  32928. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  32929. */
  32930. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  32931. var mesh;
  32932. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  32933. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  32934. }
  32935. else {
  32936. mesh = new Mesh(parsedMesh.name, scene);
  32937. }
  32938. mesh.id = parsedMesh.id;
  32939. if (BABYLON.Tags) {
  32940. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  32941. }
  32942. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  32943. if (parsedMesh.metadata !== undefined) {
  32944. mesh.metadata = parsedMesh.metadata;
  32945. }
  32946. if (parsedMesh.rotationQuaternion) {
  32947. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  32948. }
  32949. else if (parsedMesh.rotation) {
  32950. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  32951. }
  32952. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  32953. if (parsedMesh.localMatrix) {
  32954. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  32955. }
  32956. else if (parsedMesh.pivotMatrix) {
  32957. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  32958. }
  32959. mesh.setEnabled(parsedMesh.isEnabled);
  32960. mesh.isVisible = parsedMesh.isVisible;
  32961. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  32962. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  32963. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  32964. if (parsedMesh.applyFog !== undefined) {
  32965. mesh.applyFog = parsedMesh.applyFog;
  32966. }
  32967. if (parsedMesh.pickable !== undefined) {
  32968. mesh.isPickable = parsedMesh.pickable;
  32969. }
  32970. if (parsedMesh.alphaIndex !== undefined) {
  32971. mesh.alphaIndex = parsedMesh.alphaIndex;
  32972. }
  32973. mesh.receiveShadows = parsedMesh.receiveShadows;
  32974. mesh.billboardMode = parsedMesh.billboardMode;
  32975. if (parsedMesh.visibility !== undefined) {
  32976. mesh.visibility = parsedMesh.visibility;
  32977. }
  32978. mesh.checkCollisions = parsedMesh.checkCollisions;
  32979. if (parsedMesh.isBlocker !== undefined) {
  32980. mesh.isBlocker = parsedMesh.isBlocker;
  32981. }
  32982. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  32983. // freezeWorldMatrix
  32984. if (parsedMesh.freezeWorldMatrix) {
  32985. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  32986. }
  32987. // Parent
  32988. if (parsedMesh.parentId) {
  32989. mesh._waitingParentId = parsedMesh.parentId;
  32990. }
  32991. // Actions
  32992. if (parsedMesh.actions !== undefined) {
  32993. mesh._waitingActions = parsedMesh.actions;
  32994. }
  32995. // Overlay
  32996. if (parsedMesh.overlayAlpha !== undefined) {
  32997. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  32998. }
  32999. if (parsedMesh.overlayColor !== undefined) {
  33000. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  33001. }
  33002. if (parsedMesh.renderOverlay !== undefined) {
  33003. mesh.renderOverlay = parsedMesh.renderOverlay;
  33004. }
  33005. // Geometry
  33006. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  33007. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  33008. if (parsedMesh.delayLoadingFile) {
  33009. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33010. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  33011. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  33012. if (parsedMesh._binaryInfo) {
  33013. mesh._binaryInfo = parsedMesh._binaryInfo;
  33014. }
  33015. mesh._delayInfo = [];
  33016. if (parsedMesh.hasUVs) {
  33017. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33018. }
  33019. if (parsedMesh.hasUVs2) {
  33020. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33021. }
  33022. if (parsedMesh.hasUVs3) {
  33023. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33024. }
  33025. if (parsedMesh.hasUVs4) {
  33026. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33027. }
  33028. if (parsedMesh.hasUVs5) {
  33029. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33030. }
  33031. if (parsedMesh.hasUVs6) {
  33032. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33033. }
  33034. if (parsedMesh.hasColors) {
  33035. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33036. }
  33037. if (parsedMesh.hasMatricesIndices) {
  33038. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33039. }
  33040. if (parsedMesh.hasMatricesWeights) {
  33041. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33042. }
  33043. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  33044. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  33045. mesh._checkDelayState();
  33046. }
  33047. }
  33048. else {
  33049. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  33050. }
  33051. // Material
  33052. if (parsedMesh.materialId) {
  33053. mesh.setMaterialByID(parsedMesh.materialId);
  33054. }
  33055. else {
  33056. mesh.material = null;
  33057. }
  33058. // Morph targets
  33059. if (parsedMesh.morphTargetManagerId > -1) {
  33060. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  33061. }
  33062. // Skeleton
  33063. if (parsedMesh.skeletonId > -1) {
  33064. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  33065. if (parsedMesh.numBoneInfluencers) {
  33066. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  33067. }
  33068. }
  33069. // Animations
  33070. if (parsedMesh.animations) {
  33071. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33072. var parsedAnimation = parsedMesh.animations[animationIndex];
  33073. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33074. }
  33075. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  33076. }
  33077. if (parsedMesh.autoAnimate) {
  33078. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33079. }
  33080. // Layer Mask
  33081. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  33082. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  33083. }
  33084. else {
  33085. mesh.layerMask = 0x0FFFFFFF;
  33086. }
  33087. // Physics
  33088. if (parsedMesh.physicsImpostor) {
  33089. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  33090. mass: parsedMesh.physicsMass,
  33091. friction: parsedMesh.physicsFriction,
  33092. restitution: parsedMesh.physicsRestitution
  33093. }, scene);
  33094. }
  33095. // Instances
  33096. if (parsedMesh.instances) {
  33097. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33098. var parsedInstance = parsedMesh.instances[index];
  33099. var instance = mesh.createInstance(parsedInstance.name);
  33100. if (parsedInstance.id) {
  33101. instance.id = parsedInstance.id;
  33102. }
  33103. if (BABYLON.Tags) {
  33104. if (parsedInstance.tags) {
  33105. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33106. }
  33107. else {
  33108. BABYLON.Tags.AddTagsTo(instance, parsedMesh.tags);
  33109. }
  33110. }
  33111. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33112. if (parsedInstance.parentId) {
  33113. instance._waitingParentId = parsedInstance.parentId;
  33114. }
  33115. if (parsedInstance.rotationQuaternion) {
  33116. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33117. }
  33118. else if (parsedInstance.rotation) {
  33119. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33120. }
  33121. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33122. instance.checkCollisions = mesh.checkCollisions;
  33123. if (parsedMesh.animations) {
  33124. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33125. parsedAnimation = parsedMesh.animations[animationIndex];
  33126. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33127. }
  33128. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  33129. if (parsedMesh.autoAnimate) {
  33130. scene.beginAnimation(instance, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33131. }
  33132. }
  33133. }
  33134. }
  33135. return mesh;
  33136. };
  33137. /**
  33138. * Creates a ribbon mesh.
  33139. * Please consider using the same method from the MeshBuilder class instead.
  33140. * 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.
  33141. *
  33142. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  33143. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33144. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  33145. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  33146. * 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.
  33147. * 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.
  33148. * 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
  33149. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33150. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33151. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33152. */
  33153. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33154. if (closeArray === void 0) { closeArray = false; }
  33155. if (updatable === void 0) { updatable = false; }
  33156. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33157. pathArray: pathArray,
  33158. closeArray: closeArray,
  33159. closePath: closePath,
  33160. offset: offset,
  33161. updatable: updatable,
  33162. sideOrientation: sideOrientation,
  33163. instance: instance
  33164. }, scene);
  33165. };
  33166. /**
  33167. * Creates a plane polygonal mesh. By default, this is a disc.
  33168. * Please consider using the same method from the MeshBuilder class instead.
  33169. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  33170. * 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.
  33171. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33172. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33173. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33174. */
  33175. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33176. if (scene === void 0) { scene = null; }
  33177. var options = {
  33178. radius: radius,
  33179. tessellation: tessellation,
  33180. sideOrientation: sideOrientation,
  33181. updatable: updatable
  33182. };
  33183. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33184. };
  33185. /**
  33186. * Creates a box mesh.
  33187. * Please consider using the same method from the MeshBuilder class instead.
  33188. * The parameter `size` sets the size (float) of each box side (default 1).
  33189. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33190. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33191. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33192. */
  33193. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33194. if (scene === void 0) { scene = null; }
  33195. var options = {
  33196. size: size,
  33197. sideOrientation: sideOrientation,
  33198. updatable: updatable
  33199. };
  33200. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33201. };
  33202. /**
  33203. * Creates a sphere mesh.
  33204. * Please consider using the same method from the MeshBuilder class instead.
  33205. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  33206. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  33207. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33208. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33209. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33210. */
  33211. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33212. var options = {
  33213. segments: segments,
  33214. diameterX: diameter,
  33215. diameterY: diameter,
  33216. diameterZ: diameter,
  33217. sideOrientation: sideOrientation,
  33218. updatable: updatable
  33219. };
  33220. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33221. };
  33222. /**
  33223. * Creates a cylinder or a cone mesh.
  33224. * Please consider using the same method from the MeshBuilder class instead.
  33225. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  33226. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  33227. * 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.
  33228. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  33229. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  33230. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33231. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33232. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33233. */
  33234. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33235. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33236. if (scene !== undefined) {
  33237. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33238. updatable = scene;
  33239. }
  33240. scene = subdivisions;
  33241. subdivisions = 1;
  33242. }
  33243. var options = {
  33244. height: height,
  33245. diameterTop: diameterTop,
  33246. diameterBottom: diameterBottom,
  33247. tessellation: tessellation,
  33248. subdivisions: subdivisions,
  33249. sideOrientation: sideOrientation,
  33250. updatable: updatable
  33251. };
  33252. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33253. };
  33254. // Torus (Code from SharpDX.org)
  33255. /**
  33256. * Creates a torus mesh.
  33257. * Please consider using the same method from the MeshBuilder class instead.
  33258. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  33259. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  33260. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  33261. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33262. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33263. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33264. */
  33265. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33266. var options = {
  33267. diameter: diameter,
  33268. thickness: thickness,
  33269. tessellation: tessellation,
  33270. sideOrientation: sideOrientation,
  33271. updatable: updatable
  33272. };
  33273. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33274. };
  33275. /**
  33276. * Creates a torus knot mesh.
  33277. * Please consider using the same method from the MeshBuilder class instead.
  33278. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  33279. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  33280. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  33281. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  33282. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33283. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33284. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33285. */
  33286. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33287. var options = {
  33288. radius: radius,
  33289. tube: tube,
  33290. radialSegments: radialSegments,
  33291. tubularSegments: tubularSegments,
  33292. p: p,
  33293. q: q,
  33294. sideOrientation: sideOrientation,
  33295. updatable: updatable
  33296. };
  33297. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33298. };
  33299. /**
  33300. * Creates a line mesh.
  33301. * Please consider using the same method from the MeshBuilder class instead.
  33302. * 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.
  33303. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33304. * The parameter `points` is an array successive Vector3.
  33305. * 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
  33306. * When updating an instance, remember that only point positions can change, not the number of points.
  33307. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33308. */
  33309. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33310. if (scene === void 0) { scene = null; }
  33311. if (updatable === void 0) { updatable = false; }
  33312. if (instance === void 0) { instance = null; }
  33313. var options = {
  33314. points: points,
  33315. updatable: updatable,
  33316. instance: instance
  33317. };
  33318. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33319. };
  33320. /**
  33321. * Creates a dashed line mesh.
  33322. * Please consider using the same method from the MeshBuilder class instead.
  33323. * 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.
  33324. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33325. * The parameter `points` is an array successive Vector3.
  33326. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  33327. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  33328. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  33329. * 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
  33330. * When updating an instance, remember that only point positions can change, not the number of points.
  33331. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33332. */
  33333. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33334. if (scene === void 0) { scene = null; }
  33335. var options = {
  33336. points: points,
  33337. dashSize: dashSize,
  33338. gapSize: gapSize,
  33339. dashNb: dashNb,
  33340. updatable: updatable,
  33341. instance: instance
  33342. };
  33343. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33344. };
  33345. /**
  33346. * Creates a polygon mesh.
  33347. * Please consider using the same method from the MeshBuilder class instead.
  33348. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33349. * 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.
  33350. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33351. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33352. * Remember you can only change the shape positions, not their number when updating a polygon.
  33353. */
  33354. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33355. var options = {
  33356. shape: shape,
  33357. holes: holes,
  33358. updatable: updatable,
  33359. sideOrientation: sideOrientation
  33360. };
  33361. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33362. };
  33363. /**
  33364. * Creates an extruded polygon mesh, with depth in the Y direction.
  33365. * Please consider using the same method from the MeshBuilder class instead.
  33366. */
  33367. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33368. var options = {
  33369. shape: shape,
  33370. holes: holes,
  33371. depth: depth,
  33372. updatable: updatable,
  33373. sideOrientation: sideOrientation
  33374. };
  33375. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33376. };
  33377. /**
  33378. * Creates an extruded shape mesh.
  33379. * 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.
  33380. * Please consider using the same method from the MeshBuilder class instead.
  33381. *
  33382. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33383. * 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
  33384. * extruded along the Z axis.
  33385. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33386. * 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.
  33387. * The parameter `scale` (float, default 1) is the value to scale the shape.
  33388. * 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
  33389. * 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
  33390. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33391. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33392. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33393. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33394. */
  33395. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33396. if (scene === void 0) { scene = null; }
  33397. var options = {
  33398. shape: shape,
  33399. path: path,
  33400. scale: scale,
  33401. rotation: rotation,
  33402. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33403. sideOrientation: sideOrientation,
  33404. instance: instance,
  33405. updatable: updatable
  33406. };
  33407. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33408. };
  33409. /**
  33410. * Creates an custom extruded shape mesh.
  33411. * 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.
  33412. * Please consider using the same method from the MeshBuilder class instead.
  33413. *
  33414. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33415. * 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
  33416. * extruded along the Z axis.
  33417. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33418. * 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
  33419. * and the distance of this point from the begining of the path :
  33420. * ```javascript
  33421. * var rotationFunction = function(i, distance) {
  33422. * // do things
  33423. * return rotationValue; }
  33424. * ```
  33425. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  33426. * 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
  33427. * and the distance of this point from the begining of the path :
  33428. * ```javascript
  33429. * var scaleFunction = function(i, distance) {
  33430. * // do things
  33431. * return scaleValue;}
  33432. * ```
  33433. * It must returns a float value that will be the scale value applied to the shape on each path point.
  33434. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  33435. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  33436. * 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
  33437. * 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
  33438. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33439. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33440. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33441. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33442. */
  33443. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  33444. var options = {
  33445. shape: shape,
  33446. path: path,
  33447. scaleFunction: scaleFunction,
  33448. rotationFunction: rotationFunction,
  33449. ribbonCloseArray: ribbonCloseArray,
  33450. ribbonClosePath: ribbonClosePath,
  33451. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33452. sideOrientation: sideOrientation,
  33453. instance: instance,
  33454. updatable: updatable
  33455. };
  33456. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  33457. };
  33458. /**
  33459. * Creates lathe mesh.
  33460. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  33461. * Please consider using the same method from the MeshBuilder class instead.
  33462. * 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
  33463. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  33464. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  33465. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  33466. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33467. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33468. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33469. */
  33470. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  33471. var options = {
  33472. shape: shape,
  33473. radius: radius,
  33474. tessellation: tessellation,
  33475. sideOrientation: sideOrientation,
  33476. updatable: updatable
  33477. };
  33478. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  33479. };
  33480. /**
  33481. * Creates a plane mesh.
  33482. * Please consider using the same method from the MeshBuilder class instead.
  33483. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  33484. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33485. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33486. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33487. */
  33488. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  33489. var options = {
  33490. size: size,
  33491. width: size,
  33492. height: size,
  33493. sideOrientation: sideOrientation,
  33494. updatable: updatable
  33495. };
  33496. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  33497. };
  33498. /**
  33499. * Creates a ground mesh.
  33500. * Please consider using the same method from the MeshBuilder class instead.
  33501. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  33502. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  33503. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33504. */
  33505. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  33506. var options = {
  33507. width: width,
  33508. height: height,
  33509. subdivisions: subdivisions,
  33510. updatable: updatable
  33511. };
  33512. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  33513. };
  33514. /**
  33515. * Creates a tiled ground mesh.
  33516. * Please consider using the same method from the MeshBuilder class instead.
  33517. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  33518. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  33519. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  33520. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  33521. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  33522. * numbers of subdivisions on the ground width and height of each tile.
  33523. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33524. */
  33525. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  33526. var options = {
  33527. xmin: xmin,
  33528. zmin: zmin,
  33529. xmax: xmax,
  33530. zmax: zmax,
  33531. subdivisions: subdivisions,
  33532. precision: precision,
  33533. updatable: updatable
  33534. };
  33535. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  33536. };
  33537. /**
  33538. * Creates a ground mesh from a height map.
  33539. * tuto : http://doc.babylonjs.com/babylon101/height_map
  33540. * Please consider using the same method from the MeshBuilder class instead.
  33541. * The parameter `url` sets the URL of the height map image resource.
  33542. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  33543. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  33544. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  33545. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  33546. * 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).
  33547. * This function is passed the newly built mesh :
  33548. * ```javascript
  33549. * function(mesh) { // do things
  33550. * return; }
  33551. * ```
  33552. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33553. */
  33554. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  33555. var options = {
  33556. width: width,
  33557. height: height,
  33558. subdivisions: subdivisions,
  33559. minHeight: minHeight,
  33560. maxHeight: maxHeight,
  33561. updatable: updatable,
  33562. onReady: onReady
  33563. };
  33564. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  33565. };
  33566. /**
  33567. * Creates a tube mesh.
  33568. * 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.
  33569. * Please consider using the same method from the MeshBuilder class instead.
  33570. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  33571. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  33572. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  33573. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  33574. * 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.
  33575. * It must return a radius value (positive float) :
  33576. * ```javascript
  33577. * var radiusFunction = function(i, distance) {
  33578. * // do things
  33579. * return radius; }
  33580. * ```
  33581. * 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
  33582. * 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
  33583. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33584. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33585. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33586. */
  33587. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  33588. var options = {
  33589. path: path,
  33590. radius: radius,
  33591. tessellation: tessellation,
  33592. radiusFunction: radiusFunction,
  33593. arc: 1,
  33594. cap: cap,
  33595. updatable: updatable,
  33596. sideOrientation: sideOrientation,
  33597. instance: instance
  33598. };
  33599. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  33600. };
  33601. /**
  33602. * Creates a polyhedron mesh.
  33603. * Please consider using the same method from the MeshBuilder class instead.
  33604. * 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
  33605. * to choose the wanted type.
  33606. * The parameter `size` (positive float, default 1) sets the polygon size.
  33607. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  33608. * 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`.
  33609. * 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
  33610. * 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)`).
  33611. * 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
  33612. * 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.
  33613. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33614. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33615. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33616. */
  33617. Mesh.CreatePolyhedron = function (name, options, scene) {
  33618. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  33619. };
  33620. /**
  33621. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  33622. * Please consider using the same method from the MeshBuilder class instead.
  33623. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  33624. * 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`).
  33625. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  33626. * 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.
  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.CreateIcoSphere = function (name, options, scene) {
  33632. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  33633. };
  33634. /**
  33635. * Creates a decal mesh.
  33636. * Please consider using the same method from the MeshBuilder class instead.
  33637. * 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.
  33638. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  33639. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  33640. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  33641. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  33642. */
  33643. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  33644. var options = {
  33645. position: position,
  33646. normal: normal,
  33647. size: size,
  33648. angle: angle
  33649. };
  33650. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  33651. };
  33652. // Skeletons
  33653. /**
  33654. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33655. */
  33656. Mesh.prototype.setPositionsForCPUSkinning = function () {
  33657. if (!this._sourcePositions) {
  33658. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33659. if (!source) {
  33660. return this._sourcePositions;
  33661. }
  33662. this._sourcePositions = new Float32Array(source);
  33663. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  33664. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  33665. }
  33666. }
  33667. return this._sourcePositions;
  33668. };
  33669. /**
  33670. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33671. */
  33672. Mesh.prototype.setNormalsForCPUSkinning = function () {
  33673. if (!this._sourceNormals) {
  33674. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33675. if (!source) {
  33676. return this._sourceNormals;
  33677. }
  33678. this._sourceNormals = new Float32Array(source);
  33679. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  33680. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  33681. }
  33682. }
  33683. return this._sourceNormals;
  33684. };
  33685. /**
  33686. * Updates the vertex buffer by applying transformation from the bones.
  33687. * Returns the Mesh.
  33688. *
  33689. * @param {skeleton} skeleton to apply
  33690. */
  33691. Mesh.prototype.applySkeleton = function (skeleton) {
  33692. if (!this.geometry) {
  33693. return this;
  33694. }
  33695. if (this.geometry._softwareSkinningFrameId == this.getScene().getFrameId()) {
  33696. return this;
  33697. }
  33698. this.geometry._softwareSkinningFrameId = this.getScene().getFrameId();
  33699. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33700. return this;
  33701. }
  33702. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33703. return this;
  33704. }
  33705. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33706. return this;
  33707. }
  33708. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33709. return this;
  33710. }
  33711. if (!this._sourcePositions) {
  33712. var submeshes = this.subMeshes.slice();
  33713. this.setPositionsForCPUSkinning();
  33714. this.subMeshes = submeshes;
  33715. }
  33716. if (!this._sourceNormals) {
  33717. this.setNormalsForCPUSkinning();
  33718. }
  33719. // positionsData checks for not being Float32Array will only pass at most once
  33720. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33721. if (!positionsData) {
  33722. return this;
  33723. }
  33724. if (!(positionsData instanceof Float32Array)) {
  33725. positionsData = new Float32Array(positionsData);
  33726. }
  33727. // normalsData checks for not being Float32Array will only pass at most once
  33728. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33729. if (!normalsData) {
  33730. return this;
  33731. }
  33732. if (!(normalsData instanceof Float32Array)) {
  33733. normalsData = new Float32Array(normalsData);
  33734. }
  33735. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33736. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33737. if (!matricesWeightsData || !matricesIndicesData) {
  33738. return this;
  33739. }
  33740. var needExtras = this.numBoneInfluencers > 4;
  33741. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  33742. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  33743. var skeletonMatrices = skeleton.getTransformMatrices(this);
  33744. var tempVector3 = BABYLON.Vector3.Zero();
  33745. var finalMatrix = new BABYLON.Matrix();
  33746. var tempMatrix = new BABYLON.Matrix();
  33747. var matWeightIdx = 0;
  33748. var inf;
  33749. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  33750. var weight;
  33751. for (inf = 0; inf < 4; inf++) {
  33752. weight = matricesWeightsData[matWeightIdx + inf];
  33753. if (weight > 0) {
  33754. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33755. finalMatrix.addToSelf(tempMatrix);
  33756. }
  33757. }
  33758. if (needExtras) {
  33759. for (inf = 0; inf < 4; inf++) {
  33760. weight = matricesWeightsExtraData[matWeightIdx + inf];
  33761. if (weight > 0) {
  33762. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33763. finalMatrix.addToSelf(tempMatrix);
  33764. }
  33765. }
  33766. }
  33767. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  33768. tempVector3.toArray(positionsData, index);
  33769. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  33770. tempVector3.toArray(normalsData, index);
  33771. finalMatrix.reset();
  33772. }
  33773. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  33774. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  33775. return this;
  33776. };
  33777. // Tools
  33778. /**
  33779. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  33780. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  33781. */
  33782. Mesh.MinMax = function (meshes) {
  33783. var minVector = null;
  33784. var maxVector = null;
  33785. meshes.forEach(function (mesh, index, array) {
  33786. var boundingInfo = mesh.getBoundingInfo();
  33787. var boundingBox = boundingInfo.boundingBox;
  33788. if (!minVector || !maxVector) {
  33789. minVector = boundingBox.minimumWorld;
  33790. maxVector = boundingBox.maximumWorld;
  33791. }
  33792. else {
  33793. minVector.minimizeInPlace(boundingBox.minimumWorld);
  33794. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  33795. }
  33796. });
  33797. if (!minVector || !maxVector) {
  33798. return {
  33799. min: BABYLON.Vector3.Zero(),
  33800. max: BABYLON.Vector3.Zero()
  33801. };
  33802. }
  33803. return {
  33804. min: minVector,
  33805. max: maxVector
  33806. };
  33807. };
  33808. /**
  33809. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  33810. */
  33811. Mesh.Center = function (meshesOrMinMaxVector) {
  33812. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  33813. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  33814. };
  33815. /**
  33816. * Merge the array of meshes into a single mesh for performance reasons.
  33817. * @param meshes - The vertices source. They should all be of the same material. Entries can empty
  33818. * @param disposeSource - When true (default), dispose of the vertices from the source meshes
  33819. * @param allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  33820. * @param meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  33821. * @param subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  33822. */
  33823. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  33824. if (disposeSource === void 0) { disposeSource = true; }
  33825. var index;
  33826. if (!allow32BitsIndices) {
  33827. var totalVertices = 0;
  33828. // Counting vertices
  33829. for (index = 0; index < meshes.length; index++) {
  33830. if (meshes[index]) {
  33831. totalVertices += meshes[index].getTotalVertices();
  33832. if (totalVertices > 65536) {
  33833. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  33834. return null;
  33835. }
  33836. }
  33837. }
  33838. }
  33839. // Merge
  33840. var vertexData = null;
  33841. var otherVertexData;
  33842. var indiceArray = new Array();
  33843. var source = null;
  33844. for (index = 0; index < meshes.length; index++) {
  33845. if (meshes[index]) {
  33846. var wm = meshes[index].computeWorldMatrix(true);
  33847. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);
  33848. otherVertexData.transform(wm);
  33849. if (vertexData) {
  33850. vertexData.merge(otherVertexData, allow32BitsIndices);
  33851. }
  33852. else {
  33853. vertexData = otherVertexData;
  33854. source = meshes[index];
  33855. }
  33856. if (subdivideWithSubMeshes) {
  33857. indiceArray.push(meshes[index].getTotalIndices());
  33858. }
  33859. }
  33860. }
  33861. source = source;
  33862. if (!meshSubclass) {
  33863. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  33864. }
  33865. vertexData.applyToMesh(meshSubclass);
  33866. // Setting properties
  33867. meshSubclass.material = source.material;
  33868. meshSubclass.checkCollisions = source.checkCollisions;
  33869. // Cleaning
  33870. if (disposeSource) {
  33871. for (index = 0; index < meshes.length; index++) {
  33872. if (meshes[index]) {
  33873. meshes[index].dispose();
  33874. }
  33875. }
  33876. }
  33877. // Subdivide
  33878. if (subdivideWithSubMeshes) {
  33879. //-- removal of global submesh
  33880. meshSubclass.releaseSubMeshes();
  33881. index = 0;
  33882. var offset = 0;
  33883. //-- apply subdivision according to index table
  33884. while (index < indiceArray.length) {
  33885. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  33886. offset += indiceArray[index];
  33887. index++;
  33888. }
  33889. }
  33890. return meshSubclass;
  33891. };
  33892. // Consts
  33893. Mesh._FRONTSIDE = 0;
  33894. Mesh._BACKSIDE = 1;
  33895. Mesh._DOUBLESIDE = 2;
  33896. Mesh._DEFAULTSIDE = 0;
  33897. Mesh._NO_CAP = 0;
  33898. Mesh._CAP_START = 1;
  33899. Mesh._CAP_END = 2;
  33900. Mesh._CAP_ALL = 3;
  33901. return Mesh;
  33902. }(BABYLON.AbstractMesh));
  33903. BABYLON.Mesh = Mesh;
  33904. })(BABYLON || (BABYLON = {}));
  33905. //# sourceMappingURL=babylon.mesh.js.map
  33906. var BABYLON;
  33907. (function (BABYLON) {
  33908. var BaseSubMesh = /** @class */ (function () {
  33909. function BaseSubMesh() {
  33910. }
  33911. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  33912. get: function () {
  33913. return this._materialEffect;
  33914. },
  33915. enumerable: true,
  33916. configurable: true
  33917. });
  33918. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  33919. if (defines === void 0) { defines = null; }
  33920. if (this._materialEffect === effect) {
  33921. if (!effect) {
  33922. this._materialDefines = null;
  33923. }
  33924. return;
  33925. }
  33926. this._materialDefines = defines;
  33927. this._materialEffect = effect;
  33928. };
  33929. return BaseSubMesh;
  33930. }());
  33931. BABYLON.BaseSubMesh = BaseSubMesh;
  33932. var SubMesh = /** @class */ (function (_super) {
  33933. __extends(SubMesh, _super);
  33934. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  33935. if (createBoundingBox === void 0) { createBoundingBox = true; }
  33936. var _this = _super.call(this) || this;
  33937. _this.materialIndex = materialIndex;
  33938. _this.verticesStart = verticesStart;
  33939. _this.verticesCount = verticesCount;
  33940. _this.indexStart = indexStart;
  33941. _this.indexCount = indexCount;
  33942. /** @hidden */
  33943. _this._renderId = 0;
  33944. _this._mesh = mesh;
  33945. _this._renderingMesh = renderingMesh || mesh;
  33946. mesh.subMeshes.push(_this);
  33947. _this._trianglePlanes = [];
  33948. _this._id = mesh.subMeshes.length - 1;
  33949. if (createBoundingBox) {
  33950. _this.refreshBoundingInfo();
  33951. mesh.computeWorldMatrix(true);
  33952. }
  33953. return _this;
  33954. }
  33955. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  33956. if (createBoundingBox === void 0) { createBoundingBox = true; }
  33957. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  33958. };
  33959. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  33960. get: function () {
  33961. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  33962. },
  33963. enumerable: true,
  33964. configurable: true
  33965. });
  33966. /**
  33967. * Returns the submesh BoudingInfo object.
  33968. */
  33969. SubMesh.prototype.getBoundingInfo = function () {
  33970. if (this.IsGlobal) {
  33971. return this._mesh.getBoundingInfo();
  33972. }
  33973. return this._boundingInfo;
  33974. };
  33975. /**
  33976. * Sets the submesh BoundingInfo.
  33977. * Return the SubMesh.
  33978. */
  33979. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  33980. this._boundingInfo = boundingInfo;
  33981. return this;
  33982. };
  33983. /**
  33984. * Returns the mesh of the current submesh.
  33985. */
  33986. SubMesh.prototype.getMesh = function () {
  33987. return this._mesh;
  33988. };
  33989. /**
  33990. * Returns the rendering mesh of the submesh.
  33991. */
  33992. SubMesh.prototype.getRenderingMesh = function () {
  33993. return this._renderingMesh;
  33994. };
  33995. /**
  33996. * Returns the submesh material.
  33997. */
  33998. SubMesh.prototype.getMaterial = function () {
  33999. var rootMaterial = this._renderingMesh.material;
  34000. if (rootMaterial === null || rootMaterial === undefined) {
  34001. return this._mesh.getScene().defaultMaterial;
  34002. }
  34003. else if (rootMaterial.getSubMaterial) {
  34004. var multiMaterial = rootMaterial;
  34005. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  34006. if (this._currentMaterial !== effectiveMaterial) {
  34007. this._currentMaterial = effectiveMaterial;
  34008. this._materialDefines = null;
  34009. }
  34010. return effectiveMaterial;
  34011. }
  34012. return rootMaterial;
  34013. };
  34014. // Methods
  34015. /**
  34016. * Sets a new updated BoundingInfo object to the submesh.
  34017. * Returns the SubMesh.
  34018. */
  34019. SubMesh.prototype.refreshBoundingInfo = function () {
  34020. this._lastColliderWorldVertices = null;
  34021. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  34022. return this;
  34023. }
  34024. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34025. if (!data) {
  34026. this._boundingInfo = this._mesh.getBoundingInfo();
  34027. return this;
  34028. }
  34029. var indices = this._renderingMesh.getIndices();
  34030. var extend;
  34031. //is this the only submesh?
  34032. if (this.indexStart === 0 && this.indexCount === indices.length) {
  34033. var boundingInfo = this._renderingMesh.getBoundingInfo();
  34034. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  34035. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  34036. }
  34037. else {
  34038. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  34039. }
  34040. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  34041. return this;
  34042. };
  34043. /** @hidden */
  34044. SubMesh.prototype._checkCollision = function (collider) {
  34045. var boundingInfo = this.getBoundingInfo();
  34046. return boundingInfo._checkCollision(collider);
  34047. };
  34048. /**
  34049. * Updates the submesh BoundingInfo.
  34050. * Returns the Submesh.
  34051. */
  34052. SubMesh.prototype.updateBoundingInfo = function (world) {
  34053. var boundingInfo = this.getBoundingInfo();
  34054. if (!boundingInfo) {
  34055. this.refreshBoundingInfo();
  34056. boundingInfo = this.getBoundingInfo();
  34057. }
  34058. boundingInfo.update(world);
  34059. return this;
  34060. };
  34061. /**
  34062. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  34063. * Boolean returned.
  34064. */
  34065. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  34066. var boundingInfo = this.getBoundingInfo();
  34067. if (!boundingInfo) {
  34068. return false;
  34069. }
  34070. return boundingInfo.isInFrustum(frustumPlanes);
  34071. };
  34072. /**
  34073. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  34074. * Boolean returned.
  34075. */
  34076. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  34077. var boundingInfo = this.getBoundingInfo();
  34078. if (!boundingInfo) {
  34079. return false;
  34080. }
  34081. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  34082. };
  34083. /**
  34084. * Renders the submesh.
  34085. * Returns it.
  34086. */
  34087. SubMesh.prototype.render = function (enableAlphaMode) {
  34088. this._renderingMesh.render(this, enableAlphaMode);
  34089. return this;
  34090. };
  34091. /**
  34092. * Returns a new Index Buffer.
  34093. * Type returned : WebGLBuffer.
  34094. */
  34095. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  34096. if (!this._linesIndexBuffer) {
  34097. var linesIndices = [];
  34098. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34099. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  34100. }
  34101. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  34102. this.linesIndexCount = linesIndices.length;
  34103. }
  34104. return this._linesIndexBuffer;
  34105. };
  34106. /**
  34107. * True is the passed Ray intersects the submesh bounding box.
  34108. * Boolean returned.
  34109. */
  34110. SubMesh.prototype.canIntersects = function (ray) {
  34111. var boundingInfo = this.getBoundingInfo();
  34112. if (!boundingInfo) {
  34113. return false;
  34114. }
  34115. return ray.intersectsBox(boundingInfo.boundingBox);
  34116. };
  34117. /**
  34118. * Returns an object IntersectionInfo.
  34119. */
  34120. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34121. var intersectInfo = null;
  34122. var material = this.getMaterial();
  34123. if (!material) {
  34124. return null;
  34125. }
  34126. switch (material.fillMode) {
  34127. case BABYLON.Material.PointListDrawMode:
  34128. case BABYLON.Material.LineListDrawMode:
  34129. case BABYLON.Material.LineLoopDrawMode:
  34130. case BABYLON.Material.LineStripDrawMode:
  34131. case BABYLON.Material.TriangleFanDrawMode:
  34132. case BABYLON.Material.TriangleStripDrawMode:
  34133. return null;
  34134. }
  34135. // LineMesh first as it's also a Mesh...
  34136. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34137. var lineMesh = this._mesh;
  34138. // Line test
  34139. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  34140. var p0 = positions[indices[index]];
  34141. var p1 = positions[indices[index + 1]];
  34142. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  34143. if (length < 0) {
  34144. continue;
  34145. }
  34146. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  34147. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  34148. if (fastCheck) {
  34149. break;
  34150. }
  34151. }
  34152. }
  34153. }
  34154. else {
  34155. // Triangles test
  34156. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34157. var p0 = positions[indices[index]];
  34158. var p1 = positions[indices[index + 1]];
  34159. var p2 = positions[indices[index + 2]];
  34160. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  34161. if (currentIntersectInfo) {
  34162. if (currentIntersectInfo.distance < 0) {
  34163. continue;
  34164. }
  34165. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  34166. intersectInfo = currentIntersectInfo;
  34167. intersectInfo.faceId = index / 3;
  34168. if (fastCheck) {
  34169. break;
  34170. }
  34171. }
  34172. }
  34173. }
  34174. }
  34175. return intersectInfo;
  34176. };
  34177. /** @hidden */
  34178. SubMesh.prototype._rebuild = function () {
  34179. if (this._linesIndexBuffer) {
  34180. this._linesIndexBuffer = null;
  34181. }
  34182. };
  34183. // Clone
  34184. /**
  34185. * Creates a new Submesh from the passed Mesh.
  34186. */
  34187. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  34188. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  34189. if (!this.IsGlobal) {
  34190. var boundingInfo = this.getBoundingInfo();
  34191. if (!boundingInfo) {
  34192. return result;
  34193. }
  34194. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  34195. }
  34196. return result;
  34197. };
  34198. // Dispose
  34199. /**
  34200. * Disposes the Submesh.
  34201. * Returns nothing.
  34202. */
  34203. SubMesh.prototype.dispose = function () {
  34204. if (this._linesIndexBuffer) {
  34205. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  34206. this._linesIndexBuffer = null;
  34207. }
  34208. // Remove from mesh
  34209. var index = this._mesh.subMeshes.indexOf(this);
  34210. this._mesh.subMeshes.splice(index, 1);
  34211. };
  34212. // Statics
  34213. /**
  34214. * Creates a new Submesh from the passed parameters :
  34215. * - materialIndex (integer) : the index of the main mesh material.
  34216. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  34217. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  34218. * - mesh (Mesh) : the main mesh to create the submesh from.
  34219. * - renderingMesh (optional Mesh) : rendering mesh.
  34220. */
  34221. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  34222. var minVertexIndex = Number.MAX_VALUE;
  34223. var maxVertexIndex = -Number.MAX_VALUE;
  34224. renderingMesh = (renderingMesh || mesh);
  34225. var indices = renderingMesh.getIndices();
  34226. for (var index = startIndex; index < startIndex + indexCount; index++) {
  34227. var vertexIndex = indices[index];
  34228. if (vertexIndex < minVertexIndex)
  34229. minVertexIndex = vertexIndex;
  34230. if (vertexIndex > maxVertexIndex)
  34231. maxVertexIndex = vertexIndex;
  34232. }
  34233. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  34234. };
  34235. return SubMesh;
  34236. }(BaseSubMesh));
  34237. BABYLON.SubMesh = SubMesh;
  34238. })(BABYLON || (BABYLON = {}));
  34239. //# sourceMappingURL=babylon.subMesh.js.map
  34240. var __assign = (this && this.__assign) || function () {
  34241. __assign = Object.assign || function(t) {
  34242. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34243. s = arguments[i];
  34244. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34245. t[p] = s[p];
  34246. }
  34247. return t;
  34248. };
  34249. return __assign.apply(this, arguments);
  34250. };
  34251. var BABYLON;
  34252. (function (BABYLON) {
  34253. /**
  34254. * Manages the defines for the Material
  34255. */
  34256. var MaterialDefines = /** @class */ (function () {
  34257. function MaterialDefines() {
  34258. this._isDirty = true;
  34259. /** @hidden */
  34260. this._areLightsDirty = true;
  34261. /** @hidden */
  34262. this._areAttributesDirty = true;
  34263. /** @hidden */
  34264. this._areTexturesDirty = true;
  34265. /** @hidden */
  34266. this._areFresnelDirty = true;
  34267. /** @hidden */
  34268. this._areMiscDirty = true;
  34269. /** @hidden */
  34270. this._areImageProcessingDirty = true;
  34271. /** @hidden */
  34272. this._normals = false;
  34273. /** @hidden */
  34274. this._uvs = false;
  34275. /** @hidden */
  34276. this._needNormals = false;
  34277. /** @hidden */
  34278. this._needUVs = false;
  34279. }
  34280. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34281. /**
  34282. * Specifies if the material needs to be re-calculated
  34283. */
  34284. get: function () {
  34285. return this._isDirty;
  34286. },
  34287. enumerable: true,
  34288. configurable: true
  34289. });
  34290. /**
  34291. * Marks the material to indicate that it has been re-calculated
  34292. */
  34293. MaterialDefines.prototype.markAsProcessed = function () {
  34294. this._isDirty = false;
  34295. this._areAttributesDirty = false;
  34296. this._areTexturesDirty = false;
  34297. this._areFresnelDirty = false;
  34298. this._areLightsDirty = false;
  34299. this._areMiscDirty = false;
  34300. this._areImageProcessingDirty = false;
  34301. };
  34302. /**
  34303. * Marks the material to indicate that it needs to be re-calculated
  34304. */
  34305. MaterialDefines.prototype.markAsUnprocessed = function () {
  34306. this._isDirty = true;
  34307. };
  34308. /**
  34309. * Marks the material to indicate all of its defines need to be re-calculated
  34310. */
  34311. MaterialDefines.prototype.markAllAsDirty = function () {
  34312. this._areTexturesDirty = true;
  34313. this._areAttributesDirty = true;
  34314. this._areLightsDirty = true;
  34315. this._areFresnelDirty = true;
  34316. this._areMiscDirty = true;
  34317. this._areImageProcessingDirty = true;
  34318. this._isDirty = true;
  34319. };
  34320. /**
  34321. * Marks the material to indicate that image processing needs to be re-calculated
  34322. */
  34323. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34324. this._areImageProcessingDirty = true;
  34325. this._isDirty = true;
  34326. };
  34327. /**
  34328. * Marks the material to indicate the lights need to be re-calculated
  34329. */
  34330. MaterialDefines.prototype.markAsLightDirty = function () {
  34331. this._areLightsDirty = true;
  34332. this._isDirty = true;
  34333. };
  34334. /**
  34335. * Marks the attribute state as changed
  34336. */
  34337. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34338. this._areAttributesDirty = true;
  34339. this._isDirty = true;
  34340. };
  34341. /**
  34342. * Marks the texture state as changed
  34343. */
  34344. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34345. this._areTexturesDirty = true;
  34346. this._isDirty = true;
  34347. };
  34348. /**
  34349. * Marks the fresnel state as changed
  34350. */
  34351. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34352. this._areFresnelDirty = true;
  34353. this._isDirty = true;
  34354. };
  34355. /**
  34356. * Marks the misc state as changed
  34357. */
  34358. MaterialDefines.prototype.markAsMiscDirty = function () {
  34359. this._areMiscDirty = true;
  34360. this._isDirty = true;
  34361. };
  34362. /**
  34363. * Rebuilds the material defines
  34364. */
  34365. MaterialDefines.prototype.rebuild = function () {
  34366. if (this._keys) {
  34367. delete this._keys;
  34368. }
  34369. this._keys = [];
  34370. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34371. var key = _a[_i];
  34372. if (key[0] === "_") {
  34373. continue;
  34374. }
  34375. this._keys.push(key);
  34376. }
  34377. };
  34378. /**
  34379. * Specifies if two material defines are equal
  34380. * @param other - A material define instance to compare to
  34381. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34382. */
  34383. MaterialDefines.prototype.isEqual = function (other) {
  34384. if (this._keys.length !== other._keys.length) {
  34385. return false;
  34386. }
  34387. for (var index = 0; index < this._keys.length; index++) {
  34388. var prop = this._keys[index];
  34389. if (this[prop] !== other[prop]) {
  34390. return false;
  34391. }
  34392. }
  34393. return true;
  34394. };
  34395. /**
  34396. * Clones this instance's defines to another instance
  34397. * @param other - material defines to clone values to
  34398. */
  34399. MaterialDefines.prototype.cloneTo = function (other) {
  34400. if (this._keys.length !== other._keys.length) {
  34401. other._keys = this._keys.slice(0);
  34402. }
  34403. for (var index = 0; index < this._keys.length; index++) {
  34404. var prop = this._keys[index];
  34405. other[prop] = this[prop];
  34406. }
  34407. };
  34408. /**
  34409. * Resets the material define values
  34410. */
  34411. MaterialDefines.prototype.reset = function () {
  34412. for (var index = 0; index < this._keys.length; index++) {
  34413. var prop = this._keys[index];
  34414. var type = typeof this[prop];
  34415. switch (type) {
  34416. case "number":
  34417. this[prop] = 0;
  34418. break;
  34419. case "string":
  34420. this[prop] = "";
  34421. break;
  34422. default:
  34423. this[prop] = false;
  34424. break;
  34425. }
  34426. }
  34427. };
  34428. /**
  34429. * Converts the material define values to a string
  34430. * @returns - String of material define information
  34431. */
  34432. MaterialDefines.prototype.toString = function () {
  34433. var result = "";
  34434. for (var index = 0; index < this._keys.length; index++) {
  34435. var prop = this._keys[index];
  34436. var value = this[prop];
  34437. var type = typeof value;
  34438. switch (type) {
  34439. case "number":
  34440. case "string":
  34441. result += "#define " + prop + " " + value + "\n";
  34442. break;
  34443. default:
  34444. if (value) {
  34445. result += "#define " + prop + "\n";
  34446. }
  34447. break;
  34448. }
  34449. }
  34450. return result;
  34451. };
  34452. return MaterialDefines;
  34453. }());
  34454. BABYLON.MaterialDefines = MaterialDefines;
  34455. /**
  34456. * Base class for the main features of a material in Babylon.js
  34457. */
  34458. var Material = /** @class */ (function () {
  34459. /**
  34460. * Creates a material instance
  34461. * @param name defines the name of the material
  34462. * @param scene defines the scene to reference
  34463. * @param doNotAdd specifies if the material should be added to the scene
  34464. */
  34465. function Material(name, scene, doNotAdd) {
  34466. /**
  34467. * Specifies if the ready state should be checked on each call
  34468. */
  34469. this.checkReadyOnEveryCall = false;
  34470. /**
  34471. * Specifies if the ready state should be checked once
  34472. */
  34473. this.checkReadyOnlyOnce = false;
  34474. /**
  34475. * The state of the material
  34476. */
  34477. this.state = "";
  34478. /**
  34479. * The alpha value of the material
  34480. */
  34481. this._alpha = 1.0;
  34482. /**
  34483. * Specifies if back face culling is enabled
  34484. */
  34485. this._backFaceCulling = true;
  34486. /**
  34487. * Gets a boolean indicating that current material needs to register RTT
  34488. */
  34489. this.hasRenderTargetTextures = false;
  34490. /**
  34491. * Specifies if the material should be serialized
  34492. */
  34493. this.doNotSerialize = false;
  34494. /**
  34495. * Specifies if the effect should be stored on sub meshes
  34496. */
  34497. this.storeEffectOnSubMeshes = false;
  34498. /**
  34499. * An event triggered when the material is disposed
  34500. */
  34501. this.onDisposeObservable = new BABYLON.Observable();
  34502. /**
  34503. * Stores the value of the alpha mode
  34504. */
  34505. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  34506. /**
  34507. * Stores the state of the need depth pre-pass value
  34508. */
  34509. this._needDepthPrePass = false;
  34510. /**
  34511. * Specifies if depth writing should be disabled
  34512. */
  34513. this.disableDepthWrite = false;
  34514. /**
  34515. * Specifies if depth writing should be forced
  34516. */
  34517. this.forceDepthWrite = false;
  34518. /**
  34519. * Specifies if there should be a separate pass for culling
  34520. */
  34521. this.separateCullingPass = false;
  34522. /**
  34523. * Stores the state specifing if fog should be enabled
  34524. */
  34525. this._fogEnabled = true;
  34526. /**
  34527. * Stores the size of points
  34528. */
  34529. this.pointSize = 1.0;
  34530. /**
  34531. * Stores the z offset value
  34532. */
  34533. this.zOffset = 0;
  34534. /**
  34535. * @hidden
  34536. * Specifies if the material was previously ready
  34537. */
  34538. this._wasPreviouslyReady = false;
  34539. /**
  34540. * Stores the fill mode state
  34541. */
  34542. this._fillMode = Material.TriangleFillMode;
  34543. this.name = name;
  34544. this.id = name || BABYLON.Tools.RandomId();
  34545. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  34546. this.uniqueId = this._scene.getUniqueId();
  34547. if (this._scene.useRightHandedSystem) {
  34548. this.sideOrientation = Material.ClockWiseSideOrientation;
  34549. }
  34550. else {
  34551. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  34552. }
  34553. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  34554. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  34555. if (!doNotAdd) {
  34556. this._scene.materials.push(this);
  34557. }
  34558. }
  34559. Object.defineProperty(Material, "TriangleFillMode", {
  34560. /**
  34561. * Returns the triangle fill mode
  34562. */
  34563. get: function () {
  34564. return Material._TriangleFillMode;
  34565. },
  34566. enumerable: true,
  34567. configurable: true
  34568. });
  34569. Object.defineProperty(Material, "WireFrameFillMode", {
  34570. /**
  34571. * Returns the wireframe mode
  34572. */
  34573. get: function () {
  34574. return Material._WireFrameFillMode;
  34575. },
  34576. enumerable: true,
  34577. configurable: true
  34578. });
  34579. Object.defineProperty(Material, "PointFillMode", {
  34580. /**
  34581. * Returns the point fill mode
  34582. */
  34583. get: function () {
  34584. return Material._PointFillMode;
  34585. },
  34586. enumerable: true,
  34587. configurable: true
  34588. });
  34589. Object.defineProperty(Material, "PointListDrawMode", {
  34590. /**
  34591. * Returns the point list draw mode
  34592. */
  34593. get: function () {
  34594. return Material._PointListDrawMode;
  34595. },
  34596. enumerable: true,
  34597. configurable: true
  34598. });
  34599. Object.defineProperty(Material, "LineListDrawMode", {
  34600. /**
  34601. * Returns the line list draw mode
  34602. */
  34603. get: function () {
  34604. return Material._LineListDrawMode;
  34605. },
  34606. enumerable: true,
  34607. configurable: true
  34608. });
  34609. Object.defineProperty(Material, "LineLoopDrawMode", {
  34610. /**
  34611. * Returns the line loop draw mode
  34612. */
  34613. get: function () {
  34614. return Material._LineLoopDrawMode;
  34615. },
  34616. enumerable: true,
  34617. configurable: true
  34618. });
  34619. Object.defineProperty(Material, "LineStripDrawMode", {
  34620. /**
  34621. * Returns the line strip draw mode
  34622. */
  34623. get: function () {
  34624. return Material._LineStripDrawMode;
  34625. },
  34626. enumerable: true,
  34627. configurable: true
  34628. });
  34629. Object.defineProperty(Material, "TriangleStripDrawMode", {
  34630. /**
  34631. * Returns the triangle strip draw mode
  34632. */
  34633. get: function () {
  34634. return Material._TriangleStripDrawMode;
  34635. },
  34636. enumerable: true,
  34637. configurable: true
  34638. });
  34639. Object.defineProperty(Material, "TriangleFanDrawMode", {
  34640. /**
  34641. * Returns the triangle fan draw mode
  34642. */
  34643. get: function () {
  34644. return Material._TriangleFanDrawMode;
  34645. },
  34646. enumerable: true,
  34647. configurable: true
  34648. });
  34649. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  34650. /**
  34651. * Returns the clock-wise side orientation
  34652. */
  34653. get: function () {
  34654. return Material._ClockWiseSideOrientation;
  34655. },
  34656. enumerable: true,
  34657. configurable: true
  34658. });
  34659. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  34660. /**
  34661. * Returns the counter clock-wise side orientation
  34662. */
  34663. get: function () {
  34664. return Material._CounterClockWiseSideOrientation;
  34665. },
  34666. enumerable: true,
  34667. configurable: true
  34668. });
  34669. Object.defineProperty(Material, "TextureDirtyFlag", {
  34670. /**
  34671. * Returns the dirty texture flag value
  34672. */
  34673. get: function () {
  34674. return Material._TextureDirtyFlag;
  34675. },
  34676. enumerable: true,
  34677. configurable: true
  34678. });
  34679. Object.defineProperty(Material, "LightDirtyFlag", {
  34680. /**
  34681. * Returns the dirty light flag value
  34682. */
  34683. get: function () {
  34684. return Material._LightDirtyFlag;
  34685. },
  34686. enumerable: true,
  34687. configurable: true
  34688. });
  34689. Object.defineProperty(Material, "FresnelDirtyFlag", {
  34690. /**
  34691. * Returns the dirty fresnel flag value
  34692. */
  34693. get: function () {
  34694. return Material._FresnelDirtyFlag;
  34695. },
  34696. enumerable: true,
  34697. configurable: true
  34698. });
  34699. Object.defineProperty(Material, "AttributesDirtyFlag", {
  34700. /**
  34701. * Returns the dirty attributes flag value
  34702. */
  34703. get: function () {
  34704. return Material._AttributesDirtyFlag;
  34705. },
  34706. enumerable: true,
  34707. configurable: true
  34708. });
  34709. Object.defineProperty(Material, "MiscDirtyFlag", {
  34710. /**
  34711. * Returns the dirty misc flag value
  34712. */
  34713. get: function () {
  34714. return Material._MiscDirtyFlag;
  34715. },
  34716. enumerable: true,
  34717. configurable: true
  34718. });
  34719. Object.defineProperty(Material.prototype, "alpha", {
  34720. /**
  34721. * Gets the alpha value of the material
  34722. */
  34723. get: function () {
  34724. return this._alpha;
  34725. },
  34726. /**
  34727. * Sets the alpha value of the material
  34728. */
  34729. set: function (value) {
  34730. if (this._alpha === value) {
  34731. return;
  34732. }
  34733. this._alpha = value;
  34734. this.markAsDirty(Material.MiscDirtyFlag);
  34735. },
  34736. enumerable: true,
  34737. configurable: true
  34738. });
  34739. Object.defineProperty(Material.prototype, "backFaceCulling", {
  34740. /**
  34741. * Gets the back-face culling state
  34742. */
  34743. get: function () {
  34744. return this._backFaceCulling;
  34745. },
  34746. /**
  34747. * Sets the back-face culling state
  34748. */
  34749. set: function (value) {
  34750. if (this._backFaceCulling === value) {
  34751. return;
  34752. }
  34753. this._backFaceCulling = value;
  34754. this.markAsDirty(Material.TextureDirtyFlag);
  34755. },
  34756. enumerable: true,
  34757. configurable: true
  34758. });
  34759. Object.defineProperty(Material.prototype, "onDispose", {
  34760. /**
  34761. * Called during a dispose event
  34762. */
  34763. set: function (callback) {
  34764. if (this._onDisposeObserver) {
  34765. this.onDisposeObservable.remove(this._onDisposeObserver);
  34766. }
  34767. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  34768. },
  34769. enumerable: true,
  34770. configurable: true
  34771. });
  34772. Object.defineProperty(Material.prototype, "onBindObservable", {
  34773. /**
  34774. * An event triggered when the material is bound
  34775. */
  34776. get: function () {
  34777. if (!this._onBindObservable) {
  34778. this._onBindObservable = new BABYLON.Observable();
  34779. }
  34780. return this._onBindObservable;
  34781. },
  34782. enumerable: true,
  34783. configurable: true
  34784. });
  34785. Object.defineProperty(Material.prototype, "onBind", {
  34786. /**
  34787. * Called during a bind event
  34788. */
  34789. set: function (callback) {
  34790. if (this._onBindObserver) {
  34791. this.onBindObservable.remove(this._onBindObserver);
  34792. }
  34793. this._onBindObserver = this.onBindObservable.add(callback);
  34794. },
  34795. enumerable: true,
  34796. configurable: true
  34797. });
  34798. Object.defineProperty(Material.prototype, "onUnBindObservable", {
  34799. /**
  34800. * An event triggered when the material is unbound
  34801. */
  34802. get: function () {
  34803. if (!this._onUnBindObservable) {
  34804. this._onUnBindObservable = new BABYLON.Observable();
  34805. }
  34806. return this._onUnBindObservable;
  34807. },
  34808. enumerable: true,
  34809. configurable: true
  34810. });
  34811. Object.defineProperty(Material.prototype, "alphaMode", {
  34812. /**
  34813. * Gets the value of the alpha mode
  34814. */
  34815. get: function () {
  34816. return this._alphaMode;
  34817. },
  34818. /**
  34819. * Sets the value of the alpha mode.
  34820. *
  34821. * | Value | Type | Description |
  34822. * | --- | --- | --- |
  34823. * | 0 | ALPHA_DISABLE | |
  34824. * | 1 | ALPHA_ADD | |
  34825. * | 2 | ALPHA_COMBINE | |
  34826. * | 3 | ALPHA_SUBTRACT | |
  34827. * | 4 | ALPHA_MULTIPLY | |
  34828. * | 5 | ALPHA_MAXIMIZED | |
  34829. * | 6 | ALPHA_ONEONE | |
  34830. * | 7 | ALPHA_PREMULTIPLIED | |
  34831. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  34832. * | 9 | ALPHA_INTERPOLATE | |
  34833. * | 10 | ALPHA_SCREENMODE | |
  34834. *
  34835. */
  34836. set: function (value) {
  34837. if (this._alphaMode === value) {
  34838. return;
  34839. }
  34840. this._alphaMode = value;
  34841. this.markAsDirty(Material.TextureDirtyFlag);
  34842. },
  34843. enumerable: true,
  34844. configurable: true
  34845. });
  34846. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  34847. /**
  34848. * Gets the depth pre-pass value
  34849. */
  34850. get: function () {
  34851. return this._needDepthPrePass;
  34852. },
  34853. /**
  34854. * Sets the need depth pre-pass value
  34855. */
  34856. set: function (value) {
  34857. if (this._needDepthPrePass === value) {
  34858. return;
  34859. }
  34860. this._needDepthPrePass = value;
  34861. if (this._needDepthPrePass) {
  34862. this.checkReadyOnEveryCall = true;
  34863. }
  34864. },
  34865. enumerable: true,
  34866. configurable: true
  34867. });
  34868. Object.defineProperty(Material.prototype, "fogEnabled", {
  34869. /**
  34870. * Gets the value of the fog enabled state
  34871. */
  34872. get: function () {
  34873. return this._fogEnabled;
  34874. },
  34875. /**
  34876. * Sets the state for enabling fog
  34877. */
  34878. set: function (value) {
  34879. if (this._fogEnabled === value) {
  34880. return;
  34881. }
  34882. this._fogEnabled = value;
  34883. this.markAsDirty(Material.MiscDirtyFlag);
  34884. },
  34885. enumerable: true,
  34886. configurable: true
  34887. });
  34888. Object.defineProperty(Material.prototype, "wireframe", {
  34889. /**
  34890. * Gets a value specifying if wireframe mode is enabled
  34891. */
  34892. get: function () {
  34893. switch (this._fillMode) {
  34894. case Material.WireFrameFillMode:
  34895. case Material.LineListDrawMode:
  34896. case Material.LineLoopDrawMode:
  34897. case Material.LineStripDrawMode:
  34898. return true;
  34899. }
  34900. return this._scene.forceWireframe;
  34901. },
  34902. /**
  34903. * Sets the state of wireframe mode
  34904. */
  34905. set: function (value) {
  34906. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  34907. },
  34908. enumerable: true,
  34909. configurable: true
  34910. });
  34911. Object.defineProperty(Material.prototype, "pointsCloud", {
  34912. /**
  34913. * Gets the value specifying if point clouds are enabled
  34914. */
  34915. get: function () {
  34916. switch (this._fillMode) {
  34917. case Material.PointFillMode:
  34918. case Material.PointListDrawMode:
  34919. return true;
  34920. }
  34921. return this._scene.forcePointsCloud;
  34922. },
  34923. /**
  34924. * Sets the state of point cloud mode
  34925. */
  34926. set: function (value) {
  34927. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  34928. },
  34929. enumerable: true,
  34930. configurable: true
  34931. });
  34932. Object.defineProperty(Material.prototype, "fillMode", {
  34933. /**
  34934. * Gets the material fill mode
  34935. */
  34936. get: function () {
  34937. return this._fillMode;
  34938. },
  34939. /**
  34940. * Sets the material fill mode
  34941. */
  34942. set: function (value) {
  34943. if (this._fillMode === value) {
  34944. return;
  34945. }
  34946. this._fillMode = value;
  34947. this.markAsDirty(Material.MiscDirtyFlag);
  34948. },
  34949. enumerable: true,
  34950. configurable: true
  34951. });
  34952. /**
  34953. * Returns a string representation of the current material
  34954. * @param fullDetails defines a boolean indicating which levels of logging is desired
  34955. * @returns a string with material information
  34956. */
  34957. Material.prototype.toString = function (fullDetails) {
  34958. var ret = "Name: " + this.name;
  34959. if (fullDetails) {
  34960. }
  34961. return ret;
  34962. };
  34963. /**
  34964. * Gets the class name of the material
  34965. * @returns a string with the class name of the material
  34966. */
  34967. Material.prototype.getClassName = function () {
  34968. return "Material";
  34969. };
  34970. Object.defineProperty(Material.prototype, "isFrozen", {
  34971. /**
  34972. * Specifies if updates for the material been locked
  34973. */
  34974. get: function () {
  34975. return this.checkReadyOnlyOnce;
  34976. },
  34977. enumerable: true,
  34978. configurable: true
  34979. });
  34980. /**
  34981. * Locks updates for the material
  34982. */
  34983. Material.prototype.freeze = function () {
  34984. this.checkReadyOnlyOnce = true;
  34985. };
  34986. /**
  34987. * Unlocks updates for the material
  34988. */
  34989. Material.prototype.unfreeze = function () {
  34990. this.checkReadyOnlyOnce = false;
  34991. };
  34992. /**
  34993. * Specifies if the material is ready to be used
  34994. * @param mesh defines the mesh to check
  34995. * @param useInstances specifies if instances should be used
  34996. * @returns a boolean indicating if the material is ready to be used
  34997. */
  34998. Material.prototype.isReady = function (mesh, useInstances) {
  34999. return true;
  35000. };
  35001. /**
  35002. * Specifies that the submesh is ready to be used
  35003. * @param mesh defines the mesh to check
  35004. * @param subMesh defines which submesh to check
  35005. * @param useInstances specifies that instances should be used
  35006. * @returns a boolean indicating that the submesh is ready or not
  35007. */
  35008. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35009. return false;
  35010. };
  35011. /**
  35012. * Returns the material effect
  35013. * @returns the effect associated with the material
  35014. */
  35015. Material.prototype.getEffect = function () {
  35016. return this._effect;
  35017. };
  35018. /**
  35019. * Returns the current scene
  35020. * @returns a Scene
  35021. */
  35022. Material.prototype.getScene = function () {
  35023. return this._scene;
  35024. };
  35025. /**
  35026. * Specifies if the material will require alpha blending
  35027. * @returns a boolean specifying if alpha blending is needed
  35028. */
  35029. Material.prototype.needAlphaBlending = function () {
  35030. return (this.alpha < 1.0);
  35031. };
  35032. /**
  35033. * Specifies if the mesh will require alpha blending
  35034. * @param mesh defines the mesh to check
  35035. * @returns a boolean specifying if alpha blending is needed for the mesh
  35036. */
  35037. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  35038. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  35039. };
  35040. /**
  35041. * Specifies if this material should be rendered in alpha test mode
  35042. * @returns a boolean specifying if an alpha test is needed.
  35043. */
  35044. Material.prototype.needAlphaTesting = function () {
  35045. return false;
  35046. };
  35047. /**
  35048. * Gets the texture used for the alpha test
  35049. * @returns the texture to use for alpha testing
  35050. */
  35051. Material.prototype.getAlphaTestTexture = function () {
  35052. return null;
  35053. };
  35054. /**
  35055. * Marks the material to indicate that it needs to be re-calculated
  35056. */
  35057. Material.prototype.markDirty = function () {
  35058. this._wasPreviouslyReady = false;
  35059. };
  35060. /** @hidden */
  35061. Material.prototype._preBind = function (effect, overrideOrientation) {
  35062. if (overrideOrientation === void 0) { overrideOrientation = null; }
  35063. var engine = this._scene.getEngine();
  35064. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  35065. var reverse = orientation === Material.ClockWiseSideOrientation;
  35066. engine.enableEffect(effect ? effect : this._effect);
  35067. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  35068. return reverse;
  35069. };
  35070. /**
  35071. * Binds the material to the mesh
  35072. * @param world defines the world transformation matrix
  35073. * @param mesh defines the mesh to bind the material to
  35074. */
  35075. Material.prototype.bind = function (world, mesh) {
  35076. };
  35077. /**
  35078. * Binds the submesh to the material
  35079. * @param world defines the world transformation matrix
  35080. * @param mesh defines the mesh containing the submesh
  35081. * @param subMesh defines the submesh to bind the material to
  35082. */
  35083. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35084. };
  35085. /**
  35086. * Binds the world matrix to the material
  35087. * @param world defines the world transformation matrix
  35088. */
  35089. Material.prototype.bindOnlyWorldMatrix = function (world) {
  35090. };
  35091. /**
  35092. * Binds the scene's uniform buffer to the effect.
  35093. * @param effect defines the effect to bind to the scene uniform buffer
  35094. * @param sceneUbo defines the uniform buffer storing scene data
  35095. */
  35096. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  35097. sceneUbo.bindToEffect(effect, "Scene");
  35098. };
  35099. /**
  35100. * Binds the view matrix to the effect
  35101. * @param effect defines the effect to bind the view matrix to
  35102. */
  35103. Material.prototype.bindView = function (effect) {
  35104. if (!this._useUBO) {
  35105. effect.setMatrix("view", this.getScene().getViewMatrix());
  35106. }
  35107. else {
  35108. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35109. }
  35110. };
  35111. /**
  35112. * Binds the view projection matrix to the effect
  35113. * @param effect defines the effect to bind the view projection matrix to
  35114. */
  35115. Material.prototype.bindViewProjection = function (effect) {
  35116. if (!this._useUBO) {
  35117. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  35118. }
  35119. else {
  35120. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35121. }
  35122. };
  35123. /**
  35124. * Specifies if material alpha testing should be turned on for the mesh
  35125. * @param mesh defines the mesh to check
  35126. */
  35127. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  35128. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  35129. };
  35130. /**
  35131. * Processes to execute after binding the material to a mesh
  35132. * @param mesh defines the rendered mesh
  35133. */
  35134. Material.prototype._afterBind = function (mesh) {
  35135. this._scene._cachedMaterial = this;
  35136. if (mesh) {
  35137. this._scene._cachedVisibility = mesh.visibility;
  35138. }
  35139. else {
  35140. this._scene._cachedVisibility = 1;
  35141. }
  35142. if (this._onBindObservable && mesh) {
  35143. this._onBindObservable.notifyObservers(mesh);
  35144. }
  35145. if (this.disableDepthWrite) {
  35146. var engine = this._scene.getEngine();
  35147. this._cachedDepthWriteState = engine.getDepthWrite();
  35148. engine.setDepthWrite(false);
  35149. }
  35150. };
  35151. /**
  35152. * Unbinds the material from the mesh
  35153. */
  35154. Material.prototype.unbind = function () {
  35155. if (this._onUnBindObservable) {
  35156. this._onUnBindObservable.notifyObservers(this);
  35157. }
  35158. if (this.disableDepthWrite) {
  35159. var engine = this._scene.getEngine();
  35160. engine.setDepthWrite(this._cachedDepthWriteState);
  35161. }
  35162. };
  35163. /**
  35164. * Gets the active textures from the material
  35165. * @returns an array of textures
  35166. */
  35167. Material.prototype.getActiveTextures = function () {
  35168. return [];
  35169. };
  35170. /**
  35171. * Specifies if the material uses a texture
  35172. * @param texture defines the texture to check against the material
  35173. * @returns a boolean specifying if the material uses the texture
  35174. */
  35175. Material.prototype.hasTexture = function (texture) {
  35176. return false;
  35177. };
  35178. /**
  35179. * Makes a duplicate of the material, and gives it a new name
  35180. * @param name defines the new name for the duplicated material
  35181. * @returns the cloned material
  35182. */
  35183. Material.prototype.clone = function (name) {
  35184. return null;
  35185. };
  35186. /**
  35187. * Gets the meshes bound to the material
  35188. * @returns an array of meshes bound to the material
  35189. */
  35190. Material.prototype.getBindedMeshes = function () {
  35191. var result = new Array();
  35192. for (var index = 0; index < this._scene.meshes.length; index++) {
  35193. var mesh = this._scene.meshes[index];
  35194. if (mesh.material === this) {
  35195. result.push(mesh);
  35196. }
  35197. }
  35198. return result;
  35199. };
  35200. /**
  35201. * Force shader compilation
  35202. * @param mesh defines the mesh associated with this material
  35203. * @param onCompiled defines a function to execute once the material is compiled
  35204. * @param options defines the options to configure the compilation
  35205. */
  35206. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  35207. var _this = this;
  35208. var localOptions = __assign({ clipPlane: false }, options);
  35209. var subMesh = new BABYLON.BaseSubMesh();
  35210. var scene = this.getScene();
  35211. var checkReady = function () {
  35212. if (!_this._scene || !_this._scene.getEngine()) {
  35213. return;
  35214. }
  35215. if (subMesh._materialDefines) {
  35216. subMesh._materialDefines._renderId = -1;
  35217. }
  35218. var clipPlaneState = scene.clipPlane;
  35219. if (localOptions.clipPlane) {
  35220. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  35221. }
  35222. if (_this.storeEffectOnSubMeshes) {
  35223. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  35224. if (onCompiled) {
  35225. onCompiled(_this);
  35226. }
  35227. }
  35228. else {
  35229. setTimeout(checkReady, 16);
  35230. }
  35231. }
  35232. else {
  35233. if (_this.isReady(mesh)) {
  35234. if (onCompiled) {
  35235. onCompiled(_this);
  35236. }
  35237. }
  35238. else {
  35239. setTimeout(checkReady, 16);
  35240. }
  35241. }
  35242. if (localOptions.clipPlane) {
  35243. scene.clipPlane = clipPlaneState;
  35244. }
  35245. };
  35246. checkReady();
  35247. };
  35248. /**
  35249. * Force shader compilation
  35250. * @param mesh defines the mesh that will use this material
  35251. * @param options defines additional options for compiling the shaders
  35252. * @returns a promise that resolves when the compilation completes
  35253. */
  35254. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35255. var _this = this;
  35256. return new Promise(function (resolve) {
  35257. _this.forceCompilation(mesh, function () {
  35258. resolve();
  35259. }, options);
  35260. });
  35261. };
  35262. /**
  35263. * Marks a define in the material to indicate that it needs to be re-computed
  35264. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35265. */
  35266. Material.prototype.markAsDirty = function (flag) {
  35267. if (flag & Material.TextureDirtyFlag) {
  35268. this._markAllSubMeshesAsTexturesDirty();
  35269. }
  35270. if (flag & Material.LightDirtyFlag) {
  35271. this._markAllSubMeshesAsLightsDirty();
  35272. }
  35273. if (flag & Material.FresnelDirtyFlag) {
  35274. this._markAllSubMeshesAsFresnelDirty();
  35275. }
  35276. if (flag & Material.AttributesDirtyFlag) {
  35277. this._markAllSubMeshesAsAttributesDirty();
  35278. }
  35279. if (flag & Material.MiscDirtyFlag) {
  35280. this._markAllSubMeshesAsMiscDirty();
  35281. }
  35282. this.getScene().resetCachedMaterial();
  35283. };
  35284. /**
  35285. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35286. * @param func defines a function which checks material defines against the submeshes
  35287. */
  35288. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35289. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35290. var mesh = _a[_i];
  35291. if (!mesh.subMeshes) {
  35292. continue;
  35293. }
  35294. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35295. var subMesh = _c[_b];
  35296. if (subMesh.getMaterial() !== this) {
  35297. continue;
  35298. }
  35299. if (!subMesh._materialDefines) {
  35300. continue;
  35301. }
  35302. func(subMesh._materialDefines);
  35303. }
  35304. }
  35305. };
  35306. /**
  35307. * Indicates that image processing needs to be re-calculated for all submeshes
  35308. */
  35309. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35310. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35311. };
  35312. /**
  35313. * Indicates that textures need to be re-calculated for all submeshes
  35314. */
  35315. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35316. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35317. };
  35318. /**
  35319. * Indicates that fresnel needs to be re-calculated for all submeshes
  35320. */
  35321. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35322. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35323. };
  35324. /**
  35325. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35326. */
  35327. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35328. this._markAllSubMeshesAsDirty(function (defines) {
  35329. defines.markAsFresnelDirty();
  35330. defines.markAsMiscDirty();
  35331. });
  35332. };
  35333. /**
  35334. * Indicates that lights need to be re-calculated for all submeshes
  35335. */
  35336. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35337. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35338. };
  35339. /**
  35340. * Indicates that attributes need to be re-calculated for all submeshes
  35341. */
  35342. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35343. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35344. };
  35345. /**
  35346. * Indicates that misc needs to be re-calculated for all submeshes
  35347. */
  35348. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35349. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35350. };
  35351. /**
  35352. * Indicates that textures and misc need to be re-calculated for all submeshes
  35353. */
  35354. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35355. this._markAllSubMeshesAsDirty(function (defines) {
  35356. defines.markAsTexturesDirty();
  35357. defines.markAsMiscDirty();
  35358. });
  35359. };
  35360. /**
  35361. * Disposes the material
  35362. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35363. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35364. */
  35365. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35366. // Animations
  35367. this.getScene().stopAnimation(this);
  35368. this.getScene().freeProcessedMaterials();
  35369. // Remove from scene
  35370. var index = this._scene.materials.indexOf(this);
  35371. if (index >= 0) {
  35372. this._scene.materials.splice(index, 1);
  35373. }
  35374. // Remove from meshes
  35375. for (index = 0; index < this._scene.meshes.length; index++) {
  35376. var mesh = this._scene.meshes[index];
  35377. if (mesh.material === this) {
  35378. mesh.material = null;
  35379. if (mesh.geometry) {
  35380. var geometry = (mesh.geometry);
  35381. if (this.storeEffectOnSubMeshes) {
  35382. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35383. var subMesh = _a[_i];
  35384. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35385. if (forceDisposeEffect && subMesh._materialEffect) {
  35386. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35387. }
  35388. }
  35389. }
  35390. else {
  35391. geometry._releaseVertexArrayObject(this._effect);
  35392. }
  35393. }
  35394. }
  35395. }
  35396. this._uniformBuffer.dispose();
  35397. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35398. if (forceDisposeEffect && this._effect) {
  35399. if (!this.storeEffectOnSubMeshes) {
  35400. this._scene.getEngine()._releaseEffect(this._effect);
  35401. }
  35402. this._effect = null;
  35403. }
  35404. // Callback
  35405. this.onDisposeObservable.notifyObservers(this);
  35406. this.onDisposeObservable.clear();
  35407. if (this._onBindObservable) {
  35408. this._onBindObservable.clear();
  35409. }
  35410. if (this._onUnBindObservable) {
  35411. this._onUnBindObservable.clear();
  35412. }
  35413. };
  35414. /**
  35415. * Serializes this material
  35416. * @returns the serialized material object
  35417. */
  35418. Material.prototype.serialize = function () {
  35419. return BABYLON.SerializationHelper.Serialize(this);
  35420. };
  35421. /**
  35422. * Creates a MultiMaterial from parsed MultiMaterial data.
  35423. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35424. * @param scene defines the hosting scene
  35425. * @returns a new MultiMaterial
  35426. */
  35427. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35428. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35429. multiMaterial.id = parsedMultiMaterial.id;
  35430. if (BABYLON.Tags) {
  35431. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35432. }
  35433. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35434. var subMatId = parsedMultiMaterial.materials[matIndex];
  35435. if (subMatId) {
  35436. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35437. }
  35438. else {
  35439. multiMaterial.subMaterials.push(null);
  35440. }
  35441. }
  35442. return multiMaterial;
  35443. };
  35444. /**
  35445. * Creates a material from parsed material data
  35446. * @param parsedMaterial defines parsed material data
  35447. * @param scene defines the hosting scene
  35448. * @param rootUrl defines the root URL to use to load textures
  35449. * @returns a new material
  35450. */
  35451. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35452. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  35453. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  35454. }
  35455. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  35456. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  35457. if (!BABYLON.LegacyPBRMaterial) {
  35458. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  35459. return;
  35460. }
  35461. }
  35462. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  35463. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35464. };
  35465. // Triangle views
  35466. Material._TriangleFillMode = 0;
  35467. Material._WireFrameFillMode = 1;
  35468. Material._PointFillMode = 2;
  35469. // Draw modes
  35470. Material._PointListDrawMode = 3;
  35471. Material._LineListDrawMode = 4;
  35472. Material._LineLoopDrawMode = 5;
  35473. Material._LineStripDrawMode = 6;
  35474. Material._TriangleStripDrawMode = 7;
  35475. Material._TriangleFanDrawMode = 8;
  35476. /**
  35477. * Stores the clock-wise side orientation
  35478. */
  35479. Material._ClockWiseSideOrientation = 0;
  35480. /**
  35481. * Stores the counter clock-wise side orientation
  35482. */
  35483. Material._CounterClockWiseSideOrientation = 1;
  35484. /**
  35485. * The dirty texture flag value
  35486. */
  35487. Material._TextureDirtyFlag = 1;
  35488. /**
  35489. * The dirty light flag value
  35490. */
  35491. Material._LightDirtyFlag = 2;
  35492. /**
  35493. * The dirty fresnel flag value
  35494. */
  35495. Material._FresnelDirtyFlag = 4;
  35496. /**
  35497. * The dirty attribute flag value
  35498. */
  35499. Material._AttributesDirtyFlag = 8;
  35500. /**
  35501. * The dirty misc flag value
  35502. */
  35503. Material._MiscDirtyFlag = 16;
  35504. __decorate([
  35505. BABYLON.serialize()
  35506. ], Material.prototype, "id", void 0);
  35507. __decorate([
  35508. BABYLON.serialize()
  35509. ], Material.prototype, "uniqueId", void 0);
  35510. __decorate([
  35511. BABYLON.serialize()
  35512. ], Material.prototype, "name", void 0);
  35513. __decorate([
  35514. BABYLON.serialize()
  35515. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  35516. __decorate([
  35517. BABYLON.serialize()
  35518. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  35519. __decorate([
  35520. BABYLON.serialize()
  35521. ], Material.prototype, "state", void 0);
  35522. __decorate([
  35523. BABYLON.serialize("alpha")
  35524. ], Material.prototype, "_alpha", void 0);
  35525. __decorate([
  35526. BABYLON.serialize("backFaceCulling")
  35527. ], Material.prototype, "_backFaceCulling", void 0);
  35528. __decorate([
  35529. BABYLON.serialize()
  35530. ], Material.prototype, "sideOrientation", void 0);
  35531. __decorate([
  35532. BABYLON.serialize("alphaMode")
  35533. ], Material.prototype, "_alphaMode", void 0);
  35534. __decorate([
  35535. BABYLON.serialize()
  35536. ], Material.prototype, "_needDepthPrePass", void 0);
  35537. __decorate([
  35538. BABYLON.serialize()
  35539. ], Material.prototype, "disableDepthWrite", void 0);
  35540. __decorate([
  35541. BABYLON.serialize()
  35542. ], Material.prototype, "forceDepthWrite", void 0);
  35543. __decorate([
  35544. BABYLON.serialize()
  35545. ], Material.prototype, "separateCullingPass", void 0);
  35546. __decorate([
  35547. BABYLON.serialize("fogEnabled")
  35548. ], Material.prototype, "_fogEnabled", void 0);
  35549. __decorate([
  35550. BABYLON.serialize()
  35551. ], Material.prototype, "pointSize", void 0);
  35552. __decorate([
  35553. BABYLON.serialize()
  35554. ], Material.prototype, "zOffset", void 0);
  35555. __decorate([
  35556. BABYLON.serialize()
  35557. ], Material.prototype, "wireframe", null);
  35558. __decorate([
  35559. BABYLON.serialize()
  35560. ], Material.prototype, "pointsCloud", null);
  35561. __decorate([
  35562. BABYLON.serialize()
  35563. ], Material.prototype, "fillMode", null);
  35564. return Material;
  35565. }());
  35566. BABYLON.Material = Material;
  35567. })(BABYLON || (BABYLON = {}));
  35568. //# sourceMappingURL=babylon.material.js.map
  35569. var BABYLON;
  35570. (function (BABYLON) {
  35571. var UniformBuffer = /** @class */ (function () {
  35572. /**
  35573. * Uniform buffer objects.
  35574. *
  35575. * Handles blocks of uniform on the GPU.
  35576. *
  35577. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  35578. *
  35579. * For more information, please refer to :
  35580. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  35581. */
  35582. function UniformBuffer(engine, data, dynamic) {
  35583. this._engine = engine;
  35584. this._noUBO = !engine.supportsUniformBuffers;
  35585. this._dynamic = dynamic;
  35586. this._data = data || [];
  35587. this._uniformLocations = {};
  35588. this._uniformSizes = {};
  35589. this._uniformLocationPointer = 0;
  35590. this._needSync = false;
  35591. if (this._noUBO) {
  35592. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  35593. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  35594. this.updateFloat = this._updateFloatForEffect;
  35595. this.updateFloat2 = this._updateFloat2ForEffect;
  35596. this.updateFloat3 = this._updateFloat3ForEffect;
  35597. this.updateFloat4 = this._updateFloat4ForEffect;
  35598. this.updateMatrix = this._updateMatrixForEffect;
  35599. this.updateVector3 = this._updateVector3ForEffect;
  35600. this.updateVector4 = this._updateVector4ForEffect;
  35601. this.updateColor3 = this._updateColor3ForEffect;
  35602. this.updateColor4 = this._updateColor4ForEffect;
  35603. }
  35604. else {
  35605. this._engine._uniformBuffers.push(this);
  35606. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  35607. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  35608. this.updateFloat = this._updateFloatForUniform;
  35609. this.updateFloat2 = this._updateFloat2ForUniform;
  35610. this.updateFloat3 = this._updateFloat3ForUniform;
  35611. this.updateFloat4 = this._updateFloat4ForUniform;
  35612. this.updateMatrix = this._updateMatrixForUniform;
  35613. this.updateVector3 = this._updateVector3ForUniform;
  35614. this.updateVector4 = this._updateVector4ForUniform;
  35615. this.updateColor3 = this._updateColor3ForUniform;
  35616. this.updateColor4 = this._updateColor4ForUniform;
  35617. }
  35618. }
  35619. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  35620. // Properties
  35621. /**
  35622. * Indicates if the buffer is using the WebGL2 UBO implementation,
  35623. * or just falling back on setUniformXXX calls.
  35624. */
  35625. get: function () {
  35626. return !this._noUBO;
  35627. },
  35628. enumerable: true,
  35629. configurable: true
  35630. });
  35631. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  35632. /**
  35633. * Indicates if the WebGL underlying uniform buffer is in sync
  35634. * with the javascript cache data.
  35635. */
  35636. get: function () {
  35637. return !this._needSync;
  35638. },
  35639. enumerable: true,
  35640. configurable: true
  35641. });
  35642. /**
  35643. * Indicates if the WebGL underlying uniform buffer is dynamic.
  35644. * Also, a dynamic UniformBuffer will disable cache verification and always
  35645. * update the underlying WebGL uniform buffer to the GPU.
  35646. */
  35647. UniformBuffer.prototype.isDynamic = function () {
  35648. return this._dynamic !== undefined;
  35649. };
  35650. /**
  35651. * The data cache on JS side.
  35652. */
  35653. UniformBuffer.prototype.getData = function () {
  35654. return this._bufferData;
  35655. };
  35656. /**
  35657. * The underlying WebGL Uniform buffer.
  35658. */
  35659. UniformBuffer.prototype.getBuffer = function () {
  35660. return this._buffer;
  35661. };
  35662. /**
  35663. * std140 layout specifies how to align data within an UBO structure.
  35664. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  35665. * for specs.
  35666. */
  35667. UniformBuffer.prototype._fillAlignment = function (size) {
  35668. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  35669. // and 4x4 matrices
  35670. // TODO : change if other types are used
  35671. var alignment;
  35672. if (size <= 2) {
  35673. alignment = size;
  35674. }
  35675. else {
  35676. alignment = 4;
  35677. }
  35678. if ((this._uniformLocationPointer % alignment) !== 0) {
  35679. var oldPointer = this._uniformLocationPointer;
  35680. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  35681. var diff = this._uniformLocationPointer - oldPointer;
  35682. for (var i = 0; i < diff; i++) {
  35683. this._data.push(0);
  35684. }
  35685. }
  35686. };
  35687. /**
  35688. * Adds an uniform in the buffer.
  35689. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  35690. * for the layout to be correct !
  35691. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35692. * @param {number|number[]} size Data size, or data directly.
  35693. */
  35694. UniformBuffer.prototype.addUniform = function (name, size) {
  35695. if (this._noUBO) {
  35696. return;
  35697. }
  35698. if (this._uniformLocations[name] !== undefined) {
  35699. // Already existing uniform
  35700. return;
  35701. }
  35702. // This function must be called in the order of the shader layout !
  35703. // size can be the size of the uniform, or data directly
  35704. var data;
  35705. if (size instanceof Array) {
  35706. data = size;
  35707. size = data.length;
  35708. }
  35709. else {
  35710. size = size;
  35711. data = [];
  35712. // Fill with zeros
  35713. for (var i = 0; i < size; i++) {
  35714. data.push(0);
  35715. }
  35716. }
  35717. this._fillAlignment(size);
  35718. this._uniformSizes[name] = size;
  35719. this._uniformLocations[name] = this._uniformLocationPointer;
  35720. this._uniformLocationPointer += size;
  35721. for (var i = 0; i < size; i++) {
  35722. this._data.push(data[i]);
  35723. }
  35724. this._needSync = true;
  35725. };
  35726. /**
  35727. * Wrapper for addUniform.
  35728. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35729. * @param {Matrix} mat A 4x4 matrix.
  35730. */
  35731. UniformBuffer.prototype.addMatrix = function (name, mat) {
  35732. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  35733. };
  35734. /**
  35735. * Wrapper for addUniform.
  35736. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35737. * @param {number} x
  35738. * @param {number} y
  35739. */
  35740. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  35741. var temp = [x, y];
  35742. this.addUniform(name, temp);
  35743. };
  35744. /**
  35745. * Wrapper for addUniform.
  35746. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35747. * @param {number} x
  35748. * @param {number} y
  35749. * @param {number} z
  35750. */
  35751. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  35752. var temp = [x, y, z];
  35753. this.addUniform(name, temp);
  35754. };
  35755. /**
  35756. * Wrapper for addUniform.
  35757. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35758. * @param {Color3} color
  35759. */
  35760. UniformBuffer.prototype.addColor3 = function (name, color) {
  35761. var temp = new Array();
  35762. color.toArray(temp);
  35763. this.addUniform(name, temp);
  35764. };
  35765. /**
  35766. * Wrapper for addUniform.
  35767. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35768. * @param {Color3} color
  35769. * @param {number} alpha
  35770. */
  35771. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  35772. var temp = new Array();
  35773. color.toArray(temp);
  35774. temp.push(alpha);
  35775. this.addUniform(name, temp);
  35776. };
  35777. /**
  35778. * Wrapper for addUniform.
  35779. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35780. * @param {Vector3} vector
  35781. */
  35782. UniformBuffer.prototype.addVector3 = function (name, vector) {
  35783. var temp = new Array();
  35784. vector.toArray(temp);
  35785. this.addUniform(name, temp);
  35786. };
  35787. /**
  35788. * Wrapper for addUniform.
  35789. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35790. */
  35791. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  35792. this.addUniform(name, 12);
  35793. };
  35794. /**
  35795. * Wrapper for addUniform.
  35796. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35797. */
  35798. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  35799. this.addUniform(name, 8);
  35800. };
  35801. /**
  35802. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  35803. */
  35804. UniformBuffer.prototype.create = function () {
  35805. if (this._noUBO) {
  35806. return;
  35807. }
  35808. if (this._buffer) {
  35809. return; // nothing to do
  35810. }
  35811. // See spec, alignment must be filled as a vec4
  35812. this._fillAlignment(4);
  35813. this._bufferData = new Float32Array(this._data);
  35814. this._rebuild();
  35815. this._needSync = true;
  35816. };
  35817. /** @hidden */
  35818. UniformBuffer.prototype._rebuild = function () {
  35819. if (this._noUBO) {
  35820. return;
  35821. }
  35822. if (this._dynamic) {
  35823. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  35824. }
  35825. else {
  35826. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  35827. }
  35828. };
  35829. /**
  35830. * Updates the WebGL Uniform Buffer on the GPU.
  35831. * If the `dynamic` flag is set to true, no cache comparison is done.
  35832. * Otherwise, the buffer will be updated only if the cache differs.
  35833. */
  35834. UniformBuffer.prototype.update = function () {
  35835. if (!this._buffer) {
  35836. this.create();
  35837. return;
  35838. }
  35839. if (!this._dynamic && !this._needSync) {
  35840. return;
  35841. }
  35842. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  35843. this._needSync = false;
  35844. };
  35845. /**
  35846. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  35847. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  35848. * @param {number[]|Float32Array} data Flattened data
  35849. * @param {number} size Size of the data.
  35850. */
  35851. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  35852. var location = this._uniformLocations[uniformName];
  35853. if (location === undefined) {
  35854. if (this._buffer) {
  35855. // Cannot add an uniform if the buffer is already created
  35856. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  35857. return;
  35858. }
  35859. this.addUniform(uniformName, size);
  35860. location = this._uniformLocations[uniformName];
  35861. }
  35862. if (!this._buffer) {
  35863. this.create();
  35864. }
  35865. if (!this._dynamic) {
  35866. // Cache for static uniform buffers
  35867. var changed = false;
  35868. for (var i = 0; i < size; i++) {
  35869. if (this._bufferData[location + i] !== data[i]) {
  35870. changed = true;
  35871. this._bufferData[location + i] = data[i];
  35872. }
  35873. }
  35874. this._needSync = this._needSync || changed;
  35875. }
  35876. else {
  35877. // No cache for dynamic
  35878. for (var i = 0; i < size; i++) {
  35879. this._bufferData[location + i] = data[i];
  35880. }
  35881. }
  35882. };
  35883. // Update methods
  35884. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  35885. // To match std140, matrix must be realigned
  35886. for (var i = 0; i < 3; i++) {
  35887. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  35888. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  35889. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  35890. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35891. }
  35892. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  35893. };
  35894. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  35895. this._currentEffect.setMatrix3x3(name, matrix);
  35896. };
  35897. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  35898. this._currentEffect.setMatrix2x2(name, matrix);
  35899. };
  35900. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  35901. // To match std140, matrix must be realigned
  35902. for (var i = 0; i < 2; i++) {
  35903. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  35904. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  35905. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  35906. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35907. }
  35908. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  35909. };
  35910. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  35911. this._currentEffect.setFloat(name, x);
  35912. };
  35913. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  35914. UniformBuffer._tempBuffer[0] = x;
  35915. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  35916. };
  35917. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  35918. if (suffix === void 0) { suffix = ""; }
  35919. this._currentEffect.setFloat2(name + suffix, x, y);
  35920. };
  35921. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  35922. if (suffix === void 0) { suffix = ""; }
  35923. UniformBuffer._tempBuffer[0] = x;
  35924. UniformBuffer._tempBuffer[1] = y;
  35925. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  35926. };
  35927. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  35928. if (suffix === void 0) { suffix = ""; }
  35929. this._currentEffect.setFloat3(name + suffix, x, y, z);
  35930. };
  35931. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  35932. if (suffix === void 0) { suffix = ""; }
  35933. UniformBuffer._tempBuffer[0] = x;
  35934. UniformBuffer._tempBuffer[1] = y;
  35935. UniformBuffer._tempBuffer[2] = z;
  35936. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35937. };
  35938. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  35939. if (suffix === void 0) { suffix = ""; }
  35940. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  35941. };
  35942. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  35943. if (suffix === void 0) { suffix = ""; }
  35944. UniformBuffer._tempBuffer[0] = x;
  35945. UniformBuffer._tempBuffer[1] = y;
  35946. UniformBuffer._tempBuffer[2] = z;
  35947. UniformBuffer._tempBuffer[3] = w;
  35948. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35949. };
  35950. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  35951. this._currentEffect.setMatrix(name, mat);
  35952. };
  35953. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  35954. this.updateUniform(name, mat.toArray(), 16);
  35955. };
  35956. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  35957. this._currentEffect.setVector3(name, vector);
  35958. };
  35959. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  35960. vector.toArray(UniformBuffer._tempBuffer);
  35961. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35962. };
  35963. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  35964. this._currentEffect.setVector4(name, vector);
  35965. };
  35966. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  35967. vector.toArray(UniformBuffer._tempBuffer);
  35968. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35969. };
  35970. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  35971. if (suffix === void 0) { suffix = ""; }
  35972. this._currentEffect.setColor3(name + suffix, color);
  35973. };
  35974. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  35975. if (suffix === void 0) { suffix = ""; }
  35976. color.toArray(UniformBuffer._tempBuffer);
  35977. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35978. };
  35979. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  35980. if (suffix === void 0) { suffix = ""; }
  35981. this._currentEffect.setColor4(name + suffix, color, alpha);
  35982. };
  35983. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  35984. if (suffix === void 0) { suffix = ""; }
  35985. color.toArray(UniformBuffer._tempBuffer);
  35986. UniformBuffer._tempBuffer[3] = alpha;
  35987. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35988. };
  35989. /**
  35990. * Sets a sampler uniform on the effect.
  35991. * @param {string} name Name of the sampler.
  35992. * @param {Texture} texture
  35993. */
  35994. UniformBuffer.prototype.setTexture = function (name, texture) {
  35995. this._currentEffect.setTexture(name, texture);
  35996. };
  35997. /**
  35998. * Directly updates the value of the uniform in the cache AND on the GPU.
  35999. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36000. * @param {number[]|Float32Array} data Flattened data
  36001. */
  36002. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  36003. this.updateUniform(uniformName, data, data.length);
  36004. this.update();
  36005. };
  36006. /**
  36007. * Binds this uniform buffer to an effect.
  36008. * @param {Effect} effect
  36009. * @param {string} name Name of the uniform block in the shader.
  36010. */
  36011. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  36012. this._currentEffect = effect;
  36013. if (this._noUBO || !this._buffer) {
  36014. return;
  36015. }
  36016. effect.bindUniformBuffer(this._buffer, name);
  36017. };
  36018. /**
  36019. * Disposes the uniform buffer.
  36020. */
  36021. UniformBuffer.prototype.dispose = function () {
  36022. if (this._noUBO) {
  36023. return;
  36024. }
  36025. var index = this._engine._uniformBuffers.indexOf(this);
  36026. if (index !== -1) {
  36027. this._engine._uniformBuffers.splice(index, 1);
  36028. }
  36029. if (!this._buffer) {
  36030. return;
  36031. }
  36032. if (this._engine._releaseBuffer(this._buffer)) {
  36033. this._buffer = null;
  36034. }
  36035. };
  36036. // Pool for avoiding memory leaks
  36037. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  36038. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  36039. return UniformBuffer;
  36040. }());
  36041. BABYLON.UniformBuffer = UniformBuffer;
  36042. })(BABYLON || (BABYLON = {}));
  36043. //# sourceMappingURL=babylon.uniformBuffer.js.map
  36044. var BABYLON;
  36045. (function (BABYLON) {
  36046. /**
  36047. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  36048. */
  36049. var VertexData = /** @class */ (function () {
  36050. function VertexData() {
  36051. }
  36052. /**
  36053. * Uses the passed data array to set the set the values for the specified kind of data
  36054. * @param data a linear array of floating numbers
  36055. * @param kind the type of data that is being set, eg positions, colors etc
  36056. */
  36057. VertexData.prototype.set = function (data, kind) {
  36058. switch (kind) {
  36059. case BABYLON.VertexBuffer.PositionKind:
  36060. this.positions = data;
  36061. break;
  36062. case BABYLON.VertexBuffer.NormalKind:
  36063. this.normals = data;
  36064. break;
  36065. case BABYLON.VertexBuffer.TangentKind:
  36066. this.tangents = data;
  36067. break;
  36068. case BABYLON.VertexBuffer.UVKind:
  36069. this.uvs = data;
  36070. break;
  36071. case BABYLON.VertexBuffer.UV2Kind:
  36072. this.uvs2 = data;
  36073. break;
  36074. case BABYLON.VertexBuffer.UV3Kind:
  36075. this.uvs3 = data;
  36076. break;
  36077. case BABYLON.VertexBuffer.UV4Kind:
  36078. this.uvs4 = data;
  36079. break;
  36080. case BABYLON.VertexBuffer.UV5Kind:
  36081. this.uvs5 = data;
  36082. break;
  36083. case BABYLON.VertexBuffer.UV6Kind:
  36084. this.uvs6 = data;
  36085. break;
  36086. case BABYLON.VertexBuffer.ColorKind:
  36087. this.colors = data;
  36088. break;
  36089. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36090. this.matricesIndices = data;
  36091. break;
  36092. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36093. this.matricesWeights = data;
  36094. break;
  36095. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36096. this.matricesIndicesExtra = data;
  36097. break;
  36098. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36099. this.matricesWeightsExtra = data;
  36100. break;
  36101. }
  36102. };
  36103. /**
  36104. * Associates the vertexData to the passed Mesh.
  36105. * Sets it as updatable or not (default `false`)
  36106. * @param mesh the mesh the vertexData is applied to
  36107. * @param updatable when used and having the value true allows new data to update the vertexData
  36108. * @returns the VertexData
  36109. */
  36110. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36111. this._applyTo(mesh, updatable);
  36112. return this;
  36113. };
  36114. /**
  36115. * Associates the vertexData to the passed Geometry.
  36116. * Sets it as updatable or not (default `false`)
  36117. * @param geometry the geometry the vertexData is applied to
  36118. * @param updatable when used and having the value true allows new data to update the vertexData
  36119. * @returns VertexData
  36120. */
  36121. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36122. this._applyTo(geometry, updatable);
  36123. return this;
  36124. };
  36125. /**
  36126. * Updates the associated mesh
  36127. * @param mesh the mesh to be updated
  36128. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36129. * @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
  36130. * @returns VertexData
  36131. */
  36132. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36133. this._update(mesh);
  36134. return this;
  36135. };
  36136. /**
  36137. * Updates the associated geometry
  36138. * @param geometry the geometry to be updated
  36139. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36140. * @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
  36141. * @returns VertexData.
  36142. */
  36143. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36144. this._update(geometry);
  36145. return this;
  36146. };
  36147. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36148. if (updatable === void 0) { updatable = false; }
  36149. if (this.positions) {
  36150. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36151. }
  36152. if (this.normals) {
  36153. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36154. }
  36155. if (this.tangents) {
  36156. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36157. }
  36158. if (this.uvs) {
  36159. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36160. }
  36161. if (this.uvs2) {
  36162. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36163. }
  36164. if (this.uvs3) {
  36165. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36166. }
  36167. if (this.uvs4) {
  36168. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36169. }
  36170. if (this.uvs5) {
  36171. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36172. }
  36173. if (this.uvs6) {
  36174. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36175. }
  36176. if (this.colors) {
  36177. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36178. }
  36179. if (this.matricesIndices) {
  36180. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36181. }
  36182. if (this.matricesWeights) {
  36183. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36184. }
  36185. if (this.matricesIndicesExtra) {
  36186. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36187. }
  36188. if (this.matricesWeightsExtra) {
  36189. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36190. }
  36191. if (this.indices) {
  36192. meshOrGeometry.setIndices(this.indices, null, updatable);
  36193. }
  36194. else {
  36195. meshOrGeometry.setIndices([], null);
  36196. }
  36197. return this;
  36198. };
  36199. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36200. if (this.positions) {
  36201. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36202. }
  36203. if (this.normals) {
  36204. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36205. }
  36206. if (this.tangents) {
  36207. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36208. }
  36209. if (this.uvs) {
  36210. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36211. }
  36212. if (this.uvs2) {
  36213. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36214. }
  36215. if (this.uvs3) {
  36216. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36217. }
  36218. if (this.uvs4) {
  36219. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36220. }
  36221. if (this.uvs5) {
  36222. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36223. }
  36224. if (this.uvs6) {
  36225. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36226. }
  36227. if (this.colors) {
  36228. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36229. }
  36230. if (this.matricesIndices) {
  36231. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36232. }
  36233. if (this.matricesWeights) {
  36234. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36235. }
  36236. if (this.matricesIndicesExtra) {
  36237. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36238. }
  36239. if (this.matricesWeightsExtra) {
  36240. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36241. }
  36242. if (this.indices) {
  36243. meshOrGeometry.setIndices(this.indices, null);
  36244. }
  36245. return this;
  36246. };
  36247. /**
  36248. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36249. * @param matrix the transforming matrix
  36250. * @returns the VertexData
  36251. */
  36252. VertexData.prototype.transform = function (matrix) {
  36253. var flip = matrix.m[0] * matrix.m[5] * matrix.m[10] < 0;
  36254. var transformed = BABYLON.Vector3.Zero();
  36255. var index;
  36256. if (this.positions) {
  36257. var position = BABYLON.Vector3.Zero();
  36258. for (index = 0; index < this.positions.length; index += 3) {
  36259. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36260. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36261. this.positions[index] = transformed.x;
  36262. this.positions[index + 1] = transformed.y;
  36263. this.positions[index + 2] = transformed.z;
  36264. }
  36265. }
  36266. if (this.normals) {
  36267. var normal = BABYLON.Vector3.Zero();
  36268. for (index = 0; index < this.normals.length; index += 3) {
  36269. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36270. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36271. this.normals[index] = transformed.x;
  36272. this.normals[index + 1] = transformed.y;
  36273. this.normals[index + 2] = transformed.z;
  36274. }
  36275. }
  36276. if (this.tangents) {
  36277. var tangent = BABYLON.Vector4.Zero();
  36278. var tangentTransformed = BABYLON.Vector4.Zero();
  36279. for (index = 0; index < this.tangents.length; index += 4) {
  36280. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36281. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36282. this.tangents[index] = tangentTransformed.x;
  36283. this.tangents[index + 1] = tangentTransformed.y;
  36284. this.tangents[index + 2] = tangentTransformed.z;
  36285. this.tangents[index + 3] = tangentTransformed.w;
  36286. }
  36287. }
  36288. if (flip && this.indices) {
  36289. for (index = 0; index < this.indices.length; index += 3) {
  36290. var tmp = this.indices[index + 1];
  36291. this.indices[index + 1] = this.indices[index + 2];
  36292. this.indices[index + 2] = tmp;
  36293. }
  36294. }
  36295. return this;
  36296. };
  36297. /**
  36298. * Merges the passed VertexData into the current one
  36299. * @param other the VertexData to be merged into the current one
  36300. * @param use32BitsIndices defines a boolean indicating if indices must be store in a 32 bits array
  36301. * @returns the modified VertexData
  36302. */
  36303. VertexData.prototype.merge = function (other, use32BitsIndices) {
  36304. if (use32BitsIndices === void 0) { use32BitsIndices = false; }
  36305. this._validate();
  36306. other._validate();
  36307. if (!this.normals !== !other.normals ||
  36308. !this.tangents !== !other.tangents ||
  36309. !this.uvs !== !other.uvs ||
  36310. !this.uvs2 !== !other.uvs2 ||
  36311. !this.uvs3 !== !other.uvs3 ||
  36312. !this.uvs4 !== !other.uvs4 ||
  36313. !this.uvs5 !== !other.uvs5 ||
  36314. !this.uvs6 !== !other.uvs6 ||
  36315. !this.colors !== !other.colors ||
  36316. !this.matricesIndices !== !other.matricesIndices ||
  36317. !this.matricesWeights !== !other.matricesWeights ||
  36318. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36319. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36320. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36321. }
  36322. if (other.indices) {
  36323. if (!this.indices) {
  36324. this.indices = [];
  36325. }
  36326. var offset = this.positions ? this.positions.length / 3 : 0;
  36327. var isSrcTypedArray = this.indices.BYTES_PER_ELEMENT !== undefined;
  36328. if (isSrcTypedArray) {
  36329. var len = this.indices.length + other.indices.length;
  36330. var temp = use32BitsIndices || this.indices instanceof Uint32Array ? new Uint32Array(len) : new Uint16Array(len);
  36331. temp.set(this.indices);
  36332. var decal = this.indices.length;
  36333. for (var index = 0; index < other.indices.length; index++) {
  36334. temp[decal + index] = other.indices[index] + offset;
  36335. }
  36336. this.indices = temp;
  36337. }
  36338. else {
  36339. for (var index = 0; index < other.indices.length; index++) {
  36340. this.indices.push(other.indices[index] + offset);
  36341. }
  36342. }
  36343. }
  36344. this.positions = this._mergeElement(this.positions, other.positions);
  36345. this.normals = this._mergeElement(this.normals, other.normals);
  36346. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36347. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36348. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36349. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36350. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36351. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36352. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36353. this.colors = this._mergeElement(this.colors, other.colors);
  36354. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36355. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36356. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36357. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36358. return this;
  36359. };
  36360. VertexData.prototype._mergeElement = function (source, other) {
  36361. if (!source) {
  36362. return other;
  36363. }
  36364. if (!other) {
  36365. return source;
  36366. }
  36367. var len = other.length + source.length;
  36368. var isSrcTypedArray = source instanceof Float32Array;
  36369. var isOthTypedArray = other instanceof Float32Array;
  36370. // use non-loop method when the source is Float32Array
  36371. if (isSrcTypedArray) {
  36372. var ret32 = new Float32Array(len);
  36373. ret32.set(source);
  36374. ret32.set(other, source.length);
  36375. return ret32;
  36376. // source is number[], when other is also use concat
  36377. }
  36378. else if (!isOthTypedArray) {
  36379. return source.concat(other);
  36380. // source is a number[], but other is a Float32Array, loop required
  36381. }
  36382. else {
  36383. var ret = source.slice(0); // copy source to a separate array
  36384. for (var i = 0, len = other.length; i < len; i++) {
  36385. ret.push(other[i]);
  36386. }
  36387. return ret;
  36388. }
  36389. };
  36390. VertexData.prototype._validate = function () {
  36391. if (!this.positions) {
  36392. throw new Error("Positions are required");
  36393. }
  36394. var getElementCount = function (kind, values) {
  36395. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36396. if ((values.length % stride) !== 0) {
  36397. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36398. }
  36399. return values.length / stride;
  36400. };
  36401. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36402. var validateElementCount = function (kind, values) {
  36403. var elementCount = getElementCount(kind, values);
  36404. if (elementCount !== positionsElementCount) {
  36405. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36406. }
  36407. };
  36408. if (this.normals)
  36409. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36410. if (this.tangents)
  36411. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36412. if (this.uvs)
  36413. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36414. if (this.uvs2)
  36415. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36416. if (this.uvs3)
  36417. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36418. if (this.uvs4)
  36419. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36420. if (this.uvs5)
  36421. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36422. if (this.uvs6)
  36423. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36424. if (this.colors)
  36425. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36426. if (this.matricesIndices)
  36427. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36428. if (this.matricesWeights)
  36429. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36430. if (this.matricesIndicesExtra)
  36431. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36432. if (this.matricesWeightsExtra)
  36433. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36434. };
  36435. /**
  36436. * Serializes the VertexData
  36437. * @returns a serialized object
  36438. */
  36439. VertexData.prototype.serialize = function () {
  36440. var serializationObject = this.serialize();
  36441. if (this.positions) {
  36442. serializationObject.positions = this.positions;
  36443. }
  36444. if (this.normals) {
  36445. serializationObject.normals = this.normals;
  36446. }
  36447. if (this.tangents) {
  36448. serializationObject.tangents = this.tangents;
  36449. }
  36450. if (this.uvs) {
  36451. serializationObject.uvs = this.uvs;
  36452. }
  36453. if (this.uvs2) {
  36454. serializationObject.uvs2 = this.uvs2;
  36455. }
  36456. if (this.uvs3) {
  36457. serializationObject.uvs3 = this.uvs3;
  36458. }
  36459. if (this.uvs4) {
  36460. serializationObject.uvs4 = this.uvs4;
  36461. }
  36462. if (this.uvs5) {
  36463. serializationObject.uvs5 = this.uvs5;
  36464. }
  36465. if (this.uvs6) {
  36466. serializationObject.uvs6 = this.uvs6;
  36467. }
  36468. if (this.colors) {
  36469. serializationObject.colors = this.colors;
  36470. }
  36471. if (this.matricesIndices) {
  36472. serializationObject.matricesIndices = this.matricesIndices;
  36473. serializationObject.matricesIndices._isExpanded = true;
  36474. }
  36475. if (this.matricesWeights) {
  36476. serializationObject.matricesWeights = this.matricesWeights;
  36477. }
  36478. if (this.matricesIndicesExtra) {
  36479. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36480. serializationObject.matricesIndicesExtra._isExpanded = true;
  36481. }
  36482. if (this.matricesWeightsExtra) {
  36483. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36484. }
  36485. serializationObject.indices = this.indices;
  36486. return serializationObject;
  36487. };
  36488. // Statics
  36489. /**
  36490. * Extracts the vertexData from a mesh
  36491. * @param mesh the mesh from which to extract the VertexData
  36492. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  36493. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36494. * @returns the object VertexData associated to the passed mesh
  36495. */
  36496. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  36497. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  36498. };
  36499. /**
  36500. * Extracts the vertexData from the geometry
  36501. * @param geometry the geometry from which to extract the VertexData
  36502. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  36503. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36504. * @returns the object VertexData associated to the passed mesh
  36505. */
  36506. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  36507. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  36508. };
  36509. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  36510. var result = new VertexData();
  36511. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36512. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  36513. }
  36514. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36515. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  36516. }
  36517. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36518. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  36519. }
  36520. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36521. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  36522. }
  36523. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36524. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  36525. }
  36526. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36527. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  36528. }
  36529. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36530. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  36531. }
  36532. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36533. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  36534. }
  36535. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36536. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  36537. }
  36538. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36539. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  36540. }
  36541. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36542. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  36543. }
  36544. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36545. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  36546. }
  36547. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  36548. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  36549. }
  36550. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  36551. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  36552. }
  36553. result.indices = meshOrGeometry.getIndices(copyWhenShared, forceCopy);
  36554. return result;
  36555. };
  36556. /**
  36557. * Creates the VertexData for a Ribbon
  36558. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  36559. * * pathArray array of paths, each of which an array of successive Vector3
  36560. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  36561. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  36562. * * 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
  36563. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36564. * * 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)
  36565. * * 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)
  36566. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  36567. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  36568. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  36569. * @returns the VertexData of the ribbon
  36570. */
  36571. VertexData.CreateRibbon = function (options) {
  36572. var pathArray = options.pathArray;
  36573. var closeArray = options.closeArray || false;
  36574. var closePath = options.closePath || false;
  36575. var invertUV = options.invertUV || false;
  36576. var defaultOffset = Math.floor(pathArray[0].length / 2);
  36577. var offset = options.offset || defaultOffset;
  36578. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  36579. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36580. var customUV = options.uvs;
  36581. var customColors = options.colors;
  36582. var positions = [];
  36583. var indices = [];
  36584. var normals = [];
  36585. var uvs = [];
  36586. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  36587. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  36588. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  36589. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  36590. var minlg; // minimal length among all paths from pathArray
  36591. var lg = []; // array of path lengths : nb of vertex per path
  36592. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  36593. var p; // path iterator
  36594. var i; // point iterator
  36595. var j; // point iterator
  36596. // if single path in pathArray
  36597. if (pathArray.length < 2) {
  36598. var ar1 = [];
  36599. var ar2 = [];
  36600. for (i = 0; i < pathArray[0].length - offset; i++) {
  36601. ar1.push(pathArray[0][i]);
  36602. ar2.push(pathArray[0][i + offset]);
  36603. }
  36604. pathArray = [ar1, ar2];
  36605. }
  36606. // positions and horizontal distances (u)
  36607. var idc = 0;
  36608. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  36609. var path;
  36610. var l;
  36611. minlg = pathArray[0].length;
  36612. var vectlg;
  36613. var dist;
  36614. for (p = 0; p < pathArray.length; p++) {
  36615. uTotalDistance[p] = 0;
  36616. us[p] = [0];
  36617. path = pathArray[p];
  36618. l = path.length;
  36619. minlg = (minlg < l) ? minlg : l;
  36620. j = 0;
  36621. while (j < l) {
  36622. positions.push(path[j].x, path[j].y, path[j].z);
  36623. if (j > 0) {
  36624. vectlg = path[j].subtract(path[j - 1]).length();
  36625. dist = vectlg + uTotalDistance[p];
  36626. us[p].push(dist);
  36627. uTotalDistance[p] = dist;
  36628. }
  36629. j++;
  36630. }
  36631. if (closePath) { // an extra hidden vertex is added in the "positions" array
  36632. j--;
  36633. positions.push(path[0].x, path[0].y, path[0].z);
  36634. vectlg = path[j].subtract(path[0]).length();
  36635. dist = vectlg + uTotalDistance[p];
  36636. us[p].push(dist);
  36637. uTotalDistance[p] = dist;
  36638. }
  36639. lg[p] = l + closePathCorr;
  36640. idx[p] = idc;
  36641. idc += (l + closePathCorr);
  36642. }
  36643. // vertical distances (v)
  36644. var path1;
  36645. var path2;
  36646. var vertex1 = null;
  36647. var vertex2 = null;
  36648. for (i = 0; i < minlg + closePathCorr; i++) {
  36649. vTotalDistance[i] = 0;
  36650. vs[i] = [0];
  36651. for (p = 0; p < pathArray.length - 1; p++) {
  36652. path1 = pathArray[p];
  36653. path2 = pathArray[p + 1];
  36654. if (i === minlg) { // closePath
  36655. vertex1 = path1[0];
  36656. vertex2 = path2[0];
  36657. }
  36658. else {
  36659. vertex1 = path1[i];
  36660. vertex2 = path2[i];
  36661. }
  36662. vectlg = vertex2.subtract(vertex1).length();
  36663. dist = vectlg + vTotalDistance[i];
  36664. vs[i].push(dist);
  36665. vTotalDistance[i] = dist;
  36666. }
  36667. if (closeArray && vertex2 && vertex1) {
  36668. path1 = pathArray[p];
  36669. path2 = pathArray[0];
  36670. if (i === minlg) { // closePath
  36671. vertex2 = path2[0];
  36672. }
  36673. vectlg = vertex2.subtract(vertex1).length();
  36674. dist = vectlg + vTotalDistance[i];
  36675. vTotalDistance[i] = dist;
  36676. }
  36677. }
  36678. // uvs
  36679. var u;
  36680. var v;
  36681. if (customUV) {
  36682. for (p = 0; p < customUV.length; p++) {
  36683. uvs.push(customUV[p].x, customUV[p].y);
  36684. }
  36685. }
  36686. else {
  36687. for (p = 0; p < pathArray.length; p++) {
  36688. for (i = 0; i < minlg + closePathCorr; i++) {
  36689. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  36690. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  36691. if (invertUV) {
  36692. uvs.push(v, u);
  36693. }
  36694. else {
  36695. uvs.push(u, v);
  36696. }
  36697. }
  36698. }
  36699. }
  36700. // indices
  36701. p = 0; // path index
  36702. var pi = 0; // positions array index
  36703. var l1 = lg[p] - 1; // path1 length
  36704. var l2 = lg[p + 1] - 1; // path2 length
  36705. var min = (l1 < l2) ? l1 : l2; // current path stop index
  36706. var shft = idx[1] - idx[0]; // shift
  36707. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  36708. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  36709. // 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
  36710. indices.push(pi, pi + shft, pi + 1);
  36711. indices.push(pi + shft + 1, pi + 1, pi + shft);
  36712. pi += 1;
  36713. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  36714. p++;
  36715. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  36716. shft = idx[0] - idx[p];
  36717. l1 = lg[p] - 1;
  36718. l2 = lg[0] - 1;
  36719. }
  36720. else {
  36721. shft = idx[p + 1] - idx[p];
  36722. l1 = lg[p] - 1;
  36723. l2 = lg[p + 1] - 1;
  36724. }
  36725. pi = idx[p];
  36726. min = (l1 < l2) ? l1 + pi : l2 + pi;
  36727. }
  36728. }
  36729. // normals
  36730. VertexData.ComputeNormals(positions, indices, normals);
  36731. if (closePath) { // update both the first and last vertex normals to their average value
  36732. var indexFirst = 0;
  36733. var indexLast = 0;
  36734. for (p = 0; p < pathArray.length; p++) {
  36735. indexFirst = idx[p] * 3;
  36736. if (p + 1 < pathArray.length) {
  36737. indexLast = (idx[p + 1] - 1) * 3;
  36738. }
  36739. else {
  36740. indexLast = normals.length - 3;
  36741. }
  36742. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  36743. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  36744. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  36745. normals[indexLast] = normals[indexFirst];
  36746. normals[indexLast + 1] = normals[indexFirst + 1];
  36747. normals[indexLast + 2] = normals[indexFirst + 2];
  36748. }
  36749. }
  36750. // sides
  36751. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36752. // Colors
  36753. var colors = null;
  36754. if (customColors) {
  36755. colors = new Float32Array(customColors.length * 4);
  36756. for (var c = 0; c < customColors.length; c++) {
  36757. colors[c * 4] = customColors[c].r;
  36758. colors[c * 4 + 1] = customColors[c].g;
  36759. colors[c * 4 + 2] = customColors[c].b;
  36760. colors[c * 4 + 3] = customColors[c].a;
  36761. }
  36762. }
  36763. // Result
  36764. var vertexData = new VertexData();
  36765. var positions32 = new Float32Array(positions);
  36766. var normals32 = new Float32Array(normals);
  36767. var uvs32 = new Float32Array(uvs);
  36768. vertexData.indices = indices;
  36769. vertexData.positions = positions32;
  36770. vertexData.normals = normals32;
  36771. vertexData.uvs = uvs32;
  36772. if (colors) {
  36773. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  36774. }
  36775. if (closePath) {
  36776. vertexData._idx = idx;
  36777. }
  36778. return vertexData;
  36779. };
  36780. /**
  36781. * Creates the VertexData for a box
  36782. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36783. * * size sets the width, height and depth of the box to the value of size, optional default 1
  36784. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  36785. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  36786. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  36787. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  36788. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  36789. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36790. * * 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)
  36791. * * 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)
  36792. * @returns the VertexData of the box
  36793. */
  36794. VertexData.CreateBox = function (options) {
  36795. var normalsSource = [
  36796. new BABYLON.Vector3(0, 0, 1),
  36797. new BABYLON.Vector3(0, 0, -1),
  36798. new BABYLON.Vector3(1, 0, 0),
  36799. new BABYLON.Vector3(-1, 0, 0),
  36800. new BABYLON.Vector3(0, 1, 0),
  36801. new BABYLON.Vector3(0, -1, 0)
  36802. ];
  36803. var indices = [];
  36804. var positions = [];
  36805. var normals = [];
  36806. var uvs = [];
  36807. var width = options.width || options.size || 1;
  36808. var height = options.height || options.size || 1;
  36809. var depth = options.depth || options.size || 1;
  36810. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36811. var faceUV = options.faceUV || new Array(6);
  36812. var faceColors = options.faceColors;
  36813. var colors = [];
  36814. // default face colors and UV if undefined
  36815. for (var f = 0; f < 6; f++) {
  36816. if (faceUV[f] === undefined) {
  36817. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36818. }
  36819. if (faceColors && faceColors[f] === undefined) {
  36820. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36821. }
  36822. }
  36823. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  36824. // Create each face in turn.
  36825. for (var index = 0; index < normalsSource.length; index++) {
  36826. var normal = normalsSource[index];
  36827. // Get two vectors perpendicular to the face normal and to each other.
  36828. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  36829. var side2 = BABYLON.Vector3.Cross(normal, side1);
  36830. // Six indices (two triangles) per face.
  36831. var verticesLength = positions.length / 3;
  36832. indices.push(verticesLength);
  36833. indices.push(verticesLength + 1);
  36834. indices.push(verticesLength + 2);
  36835. indices.push(verticesLength);
  36836. indices.push(verticesLength + 2);
  36837. indices.push(verticesLength + 3);
  36838. // Four vertices per face.
  36839. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  36840. positions.push(vertex.x, vertex.y, vertex.z);
  36841. normals.push(normal.x, normal.y, normal.z);
  36842. uvs.push(faceUV[index].z, faceUV[index].w);
  36843. if (faceColors) {
  36844. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36845. }
  36846. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  36847. positions.push(vertex.x, vertex.y, vertex.z);
  36848. normals.push(normal.x, normal.y, normal.z);
  36849. uvs.push(faceUV[index].x, faceUV[index].w);
  36850. if (faceColors) {
  36851. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36852. }
  36853. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  36854. positions.push(vertex.x, vertex.y, vertex.z);
  36855. normals.push(normal.x, normal.y, normal.z);
  36856. uvs.push(faceUV[index].x, faceUV[index].y);
  36857. if (faceColors) {
  36858. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36859. }
  36860. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  36861. positions.push(vertex.x, vertex.y, vertex.z);
  36862. normals.push(normal.x, normal.y, normal.z);
  36863. uvs.push(faceUV[index].z, faceUV[index].y);
  36864. if (faceColors) {
  36865. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36866. }
  36867. }
  36868. // sides
  36869. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36870. // Result
  36871. var vertexData = new VertexData();
  36872. vertexData.indices = indices;
  36873. vertexData.positions = positions;
  36874. vertexData.normals = normals;
  36875. vertexData.uvs = uvs;
  36876. if (faceColors) {
  36877. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  36878. vertexData.colors = totalColors;
  36879. }
  36880. return vertexData;
  36881. };
  36882. /**
  36883. * Creates the VertexData for an ellipsoid, defaults to a sphere
  36884. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36885. * * segments sets the number of horizontal strips optional, default 32
  36886. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  36887. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  36888. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  36889. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  36890. * * 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
  36891. * * 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
  36892. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36893. * * 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)
  36894. * * 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)
  36895. * @returns the VertexData of the ellipsoid
  36896. */
  36897. VertexData.CreateSphere = function (options) {
  36898. var segments = options.segments || 32;
  36899. var diameterX = options.diameterX || options.diameter || 1;
  36900. var diameterY = options.diameterY || options.diameter || 1;
  36901. var diameterZ = options.diameterZ || options.diameter || 1;
  36902. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36903. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  36904. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36905. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  36906. var totalZRotationSteps = 2 + segments;
  36907. var totalYRotationSteps = 2 * totalZRotationSteps;
  36908. var indices = [];
  36909. var positions = [];
  36910. var normals = [];
  36911. var uvs = [];
  36912. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  36913. var normalizedZ = zRotationStep / totalZRotationSteps;
  36914. var angleZ = normalizedZ * Math.PI * slice;
  36915. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  36916. var normalizedY = yRotationStep / totalYRotationSteps;
  36917. var angleY = normalizedY * Math.PI * 2 * arc;
  36918. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  36919. var rotationY = BABYLON.Matrix.RotationY(angleY);
  36920. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  36921. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  36922. var vertex = complete.multiply(radius);
  36923. var normal = complete.divide(radius).normalize();
  36924. positions.push(vertex.x, vertex.y, vertex.z);
  36925. normals.push(normal.x, normal.y, normal.z);
  36926. uvs.push(normalizedY, normalizedZ);
  36927. }
  36928. if (zRotationStep > 0) {
  36929. var verticesCount = positions.length / 3;
  36930. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  36931. indices.push((firstIndex));
  36932. indices.push((firstIndex + 1));
  36933. indices.push(firstIndex + totalYRotationSteps + 1);
  36934. indices.push((firstIndex + totalYRotationSteps + 1));
  36935. indices.push((firstIndex + 1));
  36936. indices.push((firstIndex + totalYRotationSteps + 2));
  36937. }
  36938. }
  36939. }
  36940. // Sides
  36941. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36942. // Result
  36943. var vertexData = new VertexData();
  36944. vertexData.indices = indices;
  36945. vertexData.positions = positions;
  36946. vertexData.normals = normals;
  36947. vertexData.uvs = uvs;
  36948. return vertexData;
  36949. };
  36950. /**
  36951. * Creates the VertexData for a cylinder, cone or prism
  36952. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36953. * * height sets the height (y direction) of the cylinder, optional, default 2
  36954. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  36955. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  36956. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  36957. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  36958. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  36959. * * 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
  36960. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  36961. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  36962. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  36963. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  36964. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36965. * * 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)
  36966. * * 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)
  36967. * @returns the VertexData of the cylinder, cone or prism
  36968. */
  36969. VertexData.CreateCylinder = function (options) {
  36970. var height = options.height || 2;
  36971. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  36972. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  36973. var tessellation = options.tessellation || 24;
  36974. var subdivisions = options.subdivisions || 1;
  36975. var hasRings = options.hasRings ? true : false;
  36976. var enclose = options.enclose ? true : false;
  36977. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36978. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36979. var faceUV = options.faceUV || new Array(3);
  36980. var faceColors = options.faceColors;
  36981. // default face colors and UV if undefined
  36982. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  36983. var ringNb = (hasRings) ? subdivisions : 1;
  36984. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  36985. var f;
  36986. for (f = 0; f < surfaceNb; f++) {
  36987. if (faceColors && faceColors[f] === undefined) {
  36988. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36989. }
  36990. }
  36991. for (f = 0; f < surfaceNb; f++) {
  36992. if (faceUV && faceUV[f] === undefined) {
  36993. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36994. }
  36995. }
  36996. var indices = new Array();
  36997. var positions = new Array();
  36998. var normals = new Array();
  36999. var uvs = new Array();
  37000. var colors = new Array();
  37001. var angle_step = Math.PI * 2 * arc / tessellation;
  37002. var angle;
  37003. var h;
  37004. var radius;
  37005. var tan = (diameterBottom - diameterTop) / 2 / height;
  37006. var ringVertex = BABYLON.Vector3.Zero();
  37007. var ringNormal = BABYLON.Vector3.Zero();
  37008. var ringFirstVertex = BABYLON.Vector3.Zero();
  37009. var ringFirstNormal = BABYLON.Vector3.Zero();
  37010. var quadNormal = BABYLON.Vector3.Zero();
  37011. var Y = BABYLON.Axis.Y;
  37012. // positions, normals, uvs
  37013. var i;
  37014. var j;
  37015. var r;
  37016. var ringIdx = 1;
  37017. var s = 1; // surface index
  37018. var cs = 0;
  37019. var v = 0;
  37020. for (i = 0; i <= subdivisions; i++) {
  37021. h = i / subdivisions;
  37022. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  37023. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  37024. for (r = 0; r < ringIdx; r++) {
  37025. if (hasRings) {
  37026. s += r;
  37027. }
  37028. if (enclose) {
  37029. s += 2 * r;
  37030. }
  37031. for (j = 0; j <= tessellation; j++) {
  37032. angle = j * angle_step;
  37033. // position
  37034. ringVertex.x = Math.cos(-angle) * radius;
  37035. ringVertex.y = -height / 2 + h * height;
  37036. ringVertex.z = Math.sin(-angle) * radius;
  37037. // normal
  37038. if (diameterTop === 0 && i === subdivisions) {
  37039. // if no top cap, reuse former normals
  37040. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  37041. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  37042. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  37043. }
  37044. else {
  37045. ringNormal.x = ringVertex.x;
  37046. ringNormal.z = ringVertex.z;
  37047. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  37048. ringNormal.normalize();
  37049. }
  37050. // keep first ring vertex values for enclose
  37051. if (j === 0) {
  37052. ringFirstVertex.copyFrom(ringVertex);
  37053. ringFirstNormal.copyFrom(ringNormal);
  37054. }
  37055. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37056. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  37057. if (hasRings) {
  37058. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  37059. }
  37060. else {
  37061. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  37062. }
  37063. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  37064. if (faceColors) {
  37065. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  37066. }
  37067. }
  37068. // if enclose, add four vertices and their dedicated normals
  37069. if (arc !== 1 && enclose) {
  37070. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37071. positions.push(0, ringVertex.y, 0);
  37072. positions.push(0, ringVertex.y, 0);
  37073. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  37074. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  37075. quadNormal.normalize();
  37076. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37077. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  37078. quadNormal.normalize();
  37079. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37080. if (hasRings) {
  37081. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  37082. }
  37083. else {
  37084. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  37085. }
  37086. uvs.push(faceUV[s + 1].x, v);
  37087. uvs.push(faceUV[s + 1].z, v);
  37088. if (hasRings) {
  37089. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  37090. }
  37091. else {
  37092. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  37093. }
  37094. uvs.push(faceUV[s + 2].x, v);
  37095. uvs.push(faceUV[s + 2].z, v);
  37096. if (faceColors) {
  37097. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37098. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37099. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37100. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37101. }
  37102. }
  37103. if (cs !== s) {
  37104. cs = s;
  37105. }
  37106. }
  37107. }
  37108. // indices
  37109. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37110. var s;
  37111. i = 0;
  37112. for (s = 0; s < subdivisions; s++) {
  37113. var i0 = 0;
  37114. var i1 = 0;
  37115. var i2 = 0;
  37116. var i3 = 0;
  37117. for (j = 0; j < tessellation; j++) {
  37118. i0 = i * (e + 1) + j;
  37119. i1 = (i + 1) * (e + 1) + j;
  37120. i2 = i * (e + 1) + (j + 1);
  37121. i3 = (i + 1) * (e + 1) + (j + 1);
  37122. indices.push(i0, i1, i2);
  37123. indices.push(i3, i2, i1);
  37124. }
  37125. if (arc !== 1 && enclose) { // if enclose, add two quads
  37126. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37127. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37128. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37129. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37130. }
  37131. i = (hasRings) ? (i + 2) : (i + 1);
  37132. }
  37133. // Caps
  37134. var createCylinderCap = function (isTop) {
  37135. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37136. if (radius === 0) {
  37137. return;
  37138. }
  37139. // Cap positions, normals & uvs
  37140. var angle;
  37141. var circleVector;
  37142. var i;
  37143. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37144. var c = null;
  37145. if (faceColors) {
  37146. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37147. }
  37148. // cap center
  37149. var vbase = positions.length / 3;
  37150. var offset = isTop ? height / 2 : -height / 2;
  37151. var center = new BABYLON.Vector3(0, offset, 0);
  37152. positions.push(center.x, center.y, center.z);
  37153. normals.push(0, isTop ? 1 : -1, 0);
  37154. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37155. if (c) {
  37156. colors.push(c.r, c.g, c.b, c.a);
  37157. }
  37158. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37159. for (i = 0; i <= tessellation; i++) {
  37160. angle = Math.PI * 2 * i * arc / tessellation;
  37161. var cos = Math.cos(-angle);
  37162. var sin = Math.sin(-angle);
  37163. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37164. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37165. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37166. normals.push(0, isTop ? 1 : -1, 0);
  37167. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37168. if (c) {
  37169. colors.push(c.r, c.g, c.b, c.a);
  37170. }
  37171. }
  37172. // Cap indices
  37173. for (i = 0; i < tessellation; i++) {
  37174. if (!isTop) {
  37175. indices.push(vbase);
  37176. indices.push(vbase + (i + 1));
  37177. indices.push(vbase + (i + 2));
  37178. }
  37179. else {
  37180. indices.push(vbase);
  37181. indices.push(vbase + (i + 2));
  37182. indices.push(vbase + (i + 1));
  37183. }
  37184. }
  37185. };
  37186. // add caps to geometry
  37187. createCylinderCap(false);
  37188. createCylinderCap(true);
  37189. // Sides
  37190. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37191. var vertexData = new VertexData();
  37192. vertexData.indices = indices;
  37193. vertexData.positions = positions;
  37194. vertexData.normals = normals;
  37195. vertexData.uvs = uvs;
  37196. if (faceColors) {
  37197. vertexData.colors = colors;
  37198. }
  37199. return vertexData;
  37200. };
  37201. /**
  37202. * Creates the VertexData for a torus
  37203. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37204. * * diameter the diameter of the torus, optional default 1
  37205. * * thickness the diameter of the tube forming the torus, optional default 0.5
  37206. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37207. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37208. * * 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)
  37209. * * 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)
  37210. * @returns the VertexData of the torus
  37211. */
  37212. VertexData.CreateTorus = function (options) {
  37213. var indices = [];
  37214. var positions = [];
  37215. var normals = [];
  37216. var uvs = [];
  37217. var diameter = options.diameter || 1;
  37218. var thickness = options.thickness || 0.5;
  37219. var tessellation = options.tessellation || 16;
  37220. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37221. var stride = tessellation + 1;
  37222. for (var i = 0; i <= tessellation; i++) {
  37223. var u = i / tessellation;
  37224. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37225. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37226. for (var j = 0; j <= tessellation; j++) {
  37227. var v = 1 - j / tessellation;
  37228. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37229. var dx = Math.cos(innerAngle);
  37230. var dy = Math.sin(innerAngle);
  37231. // Create a vertex.
  37232. var normal = new BABYLON.Vector3(dx, dy, 0);
  37233. var position = normal.scale(thickness / 2);
  37234. var textureCoordinate = new BABYLON.Vector2(u, v);
  37235. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37236. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37237. positions.push(position.x, position.y, position.z);
  37238. normals.push(normal.x, normal.y, normal.z);
  37239. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37240. // And create indices for two triangles.
  37241. var nextI = (i + 1) % stride;
  37242. var nextJ = (j + 1) % stride;
  37243. indices.push(i * stride + j);
  37244. indices.push(i * stride + nextJ);
  37245. indices.push(nextI * stride + j);
  37246. indices.push(i * stride + nextJ);
  37247. indices.push(nextI * stride + nextJ);
  37248. indices.push(nextI * stride + j);
  37249. }
  37250. }
  37251. // Sides
  37252. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37253. // Result
  37254. var vertexData = new VertexData();
  37255. vertexData.indices = indices;
  37256. vertexData.positions = positions;
  37257. vertexData.normals = normals;
  37258. vertexData.uvs = uvs;
  37259. return vertexData;
  37260. };
  37261. /**
  37262. * Creates the VertexData of the LineSystem
  37263. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37264. * - lines an array of lines, each line being an array of successive Vector3
  37265. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37266. * @returns the VertexData of the LineSystem
  37267. */
  37268. VertexData.CreateLineSystem = function (options) {
  37269. var indices = [];
  37270. var positions = [];
  37271. var lines = options.lines;
  37272. var colors = options.colors;
  37273. var vertexColors = [];
  37274. var idx = 0;
  37275. for (var l = 0; l < lines.length; l++) {
  37276. var points = lines[l];
  37277. for (var index = 0; index < points.length; index++) {
  37278. positions.push(points[index].x, points[index].y, points[index].z);
  37279. if (colors) {
  37280. var color = colors[l];
  37281. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37282. }
  37283. if (index > 0) {
  37284. indices.push(idx - 1);
  37285. indices.push(idx);
  37286. }
  37287. idx++;
  37288. }
  37289. }
  37290. var vertexData = new VertexData();
  37291. vertexData.indices = indices;
  37292. vertexData.positions = positions;
  37293. if (colors) {
  37294. vertexData.colors = vertexColors;
  37295. }
  37296. return vertexData;
  37297. };
  37298. /**
  37299. * Create the VertexData for a DashedLines
  37300. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37301. * - points an array successive Vector3
  37302. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37303. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37304. * - dashNb the intended total number of dashes, optional, default 200
  37305. * @returns the VertexData for the DashedLines
  37306. */
  37307. VertexData.CreateDashedLines = function (options) {
  37308. var dashSize = options.dashSize || 3;
  37309. var gapSize = options.gapSize || 1;
  37310. var dashNb = options.dashNb || 200;
  37311. var points = options.points;
  37312. var positions = new Array();
  37313. var indices = new Array();
  37314. var curvect = BABYLON.Vector3.Zero();
  37315. var lg = 0;
  37316. var nb = 0;
  37317. var shft = 0;
  37318. var dashshft = 0;
  37319. var curshft = 0;
  37320. var idx = 0;
  37321. var i = 0;
  37322. for (i = 0; i < points.length - 1; i++) {
  37323. points[i + 1].subtractToRef(points[i], curvect);
  37324. lg += curvect.length();
  37325. }
  37326. shft = lg / dashNb;
  37327. dashshft = dashSize * shft / (dashSize + gapSize);
  37328. for (i = 0; i < points.length - 1; i++) {
  37329. points[i + 1].subtractToRef(points[i], curvect);
  37330. nb = Math.floor(curvect.length() / shft);
  37331. curvect.normalize();
  37332. for (var j = 0; j < nb; j++) {
  37333. curshft = shft * j;
  37334. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37335. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37336. indices.push(idx, idx + 1);
  37337. idx += 2;
  37338. }
  37339. }
  37340. // Result
  37341. var vertexData = new VertexData();
  37342. vertexData.positions = positions;
  37343. vertexData.indices = indices;
  37344. return vertexData;
  37345. };
  37346. /**
  37347. * Creates the VertexData for a Ground
  37348. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37349. * - width the width (x direction) of the ground, optional, default 1
  37350. * - height the height (z direction) of the ground, optional, default 1
  37351. * - subdivisions the number of subdivisions per side, optional, default 1
  37352. * @returns the VertexData of the Ground
  37353. */
  37354. VertexData.CreateGround = function (options) {
  37355. var indices = [];
  37356. var positions = [];
  37357. var normals = [];
  37358. var uvs = [];
  37359. var row, col;
  37360. var width = options.width || 1;
  37361. var height = options.height || 1;
  37362. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37363. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37364. for (row = 0; row <= subdivisionsY; row++) {
  37365. for (col = 0; col <= subdivisionsX; col++) {
  37366. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37367. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37368. positions.push(position.x, position.y, position.z);
  37369. normals.push(normal.x, normal.y, normal.z);
  37370. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37371. }
  37372. }
  37373. for (row = 0; row < subdivisionsY; row++) {
  37374. for (col = 0; col < subdivisionsX; col++) {
  37375. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37376. indices.push(col + 1 + row * (subdivisionsX + 1));
  37377. indices.push(col + row * (subdivisionsX + 1));
  37378. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37379. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37380. indices.push(col + row * (subdivisionsX + 1));
  37381. }
  37382. }
  37383. // Result
  37384. var vertexData = new VertexData();
  37385. vertexData.indices = indices;
  37386. vertexData.positions = positions;
  37387. vertexData.normals = normals;
  37388. vertexData.uvs = uvs;
  37389. return vertexData;
  37390. };
  37391. /**
  37392. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37393. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37394. * * xmin the ground minimum X coordinate, optional, default -1
  37395. * * zmin the ground minimum Z coordinate, optional, default -1
  37396. * * xmax the ground maximum X coordinate, optional, default 1
  37397. * * zmax the ground maximum Z coordinate, optional, default 1
  37398. * * 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}
  37399. * * 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}
  37400. * @returns the VertexData of the TiledGround
  37401. */
  37402. VertexData.CreateTiledGround = function (options) {
  37403. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37404. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37405. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37406. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37407. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37408. var precision = options.precision || { w: 1, h: 1 };
  37409. var indices = new Array();
  37410. var positions = new Array();
  37411. var normals = new Array();
  37412. var uvs = new Array();
  37413. var row, col, tileRow, tileCol;
  37414. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37415. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37416. precision.w = (precision.w < 1) ? 1 : precision.w;
  37417. precision.h = (precision.h < 1) ? 1 : precision.h;
  37418. var tileSize = {
  37419. 'w': (xmax - xmin) / subdivisions.w,
  37420. 'h': (zmax - zmin) / subdivisions.h
  37421. };
  37422. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37423. // Indices
  37424. var base = positions.length / 3;
  37425. var rowLength = precision.w + 1;
  37426. for (row = 0; row < precision.h; row++) {
  37427. for (col = 0; col < precision.w; col++) {
  37428. var square = [
  37429. base + col + row * rowLength,
  37430. base + (col + 1) + row * rowLength,
  37431. base + (col + 1) + (row + 1) * rowLength,
  37432. base + col + (row + 1) * rowLength
  37433. ];
  37434. indices.push(square[1]);
  37435. indices.push(square[2]);
  37436. indices.push(square[3]);
  37437. indices.push(square[0]);
  37438. indices.push(square[1]);
  37439. indices.push(square[3]);
  37440. }
  37441. }
  37442. // Position, normals and uvs
  37443. var position = BABYLON.Vector3.Zero();
  37444. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37445. for (row = 0; row <= precision.h; row++) {
  37446. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37447. for (col = 0; col <= precision.w; col++) {
  37448. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37449. position.y = 0;
  37450. positions.push(position.x, position.y, position.z);
  37451. normals.push(normal.x, normal.y, normal.z);
  37452. uvs.push(col / precision.w, row / precision.h);
  37453. }
  37454. }
  37455. }
  37456. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37457. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37458. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37459. }
  37460. }
  37461. // Result
  37462. var vertexData = new VertexData();
  37463. vertexData.indices = indices;
  37464. vertexData.positions = positions;
  37465. vertexData.normals = normals;
  37466. vertexData.uvs = uvs;
  37467. return vertexData;
  37468. };
  37469. /**
  37470. * Creates the VertexData of the Ground designed from a heightmap
  37471. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37472. * * width the width (x direction) of the ground
  37473. * * height the height (z direction) of the ground
  37474. * * subdivisions the number of subdivisions per side
  37475. * * minHeight the minimum altitude on the ground, optional, default 0
  37476. * * maxHeight the maximum altitude on the ground, optional default 1
  37477. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  37478. * * buffer the array holding the image color data
  37479. * * bufferWidth the width of image
  37480. * * bufferHeight the height of image
  37481. * @returns the VertexData of the Ground designed from a heightmap
  37482. */
  37483. VertexData.CreateGroundFromHeightMap = function (options) {
  37484. var indices = [];
  37485. var positions = [];
  37486. var normals = [];
  37487. var uvs = [];
  37488. var row, col;
  37489. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37490. // Vertices
  37491. for (row = 0; row <= options.subdivisions; row++) {
  37492. for (col = 0; col <= options.subdivisions; col++) {
  37493. 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));
  37494. // Compute height
  37495. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37496. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37497. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37498. var r = options.buffer[pos] / 255.0;
  37499. var g = options.buffer[pos + 1] / 255.0;
  37500. var b = options.buffer[pos + 2] / 255.0;
  37501. var gradient = r * filter.r + g * filter.g + b * filter.b;
  37502. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  37503. // Add vertex
  37504. positions.push(position.x, position.y, position.z);
  37505. normals.push(0, 0, 0);
  37506. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  37507. }
  37508. }
  37509. // Indices
  37510. for (row = 0; row < options.subdivisions; row++) {
  37511. for (col = 0; col < options.subdivisions; col++) {
  37512. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37513. indices.push(col + 1 + row * (options.subdivisions + 1));
  37514. indices.push(col + row * (options.subdivisions + 1));
  37515. indices.push(col + (row + 1) * (options.subdivisions + 1));
  37516. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37517. indices.push(col + row * (options.subdivisions + 1));
  37518. }
  37519. }
  37520. // Normals
  37521. VertexData.ComputeNormals(positions, indices, normals);
  37522. // Result
  37523. var vertexData = new VertexData();
  37524. vertexData.indices = indices;
  37525. vertexData.positions = positions;
  37526. vertexData.normals = normals;
  37527. vertexData.uvs = uvs;
  37528. return vertexData;
  37529. };
  37530. /**
  37531. * Creates the VertexData for a Plane
  37532. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  37533. * * size sets the width and height of the plane to the value of size, optional default 1
  37534. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  37535. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  37536. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37537. * * 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)
  37538. * * 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)
  37539. * @returns the VertexData of the box
  37540. */
  37541. VertexData.CreatePlane = function (options) {
  37542. var indices = [];
  37543. var positions = [];
  37544. var normals = [];
  37545. var uvs = [];
  37546. var width = options.width || options.size || 1;
  37547. var height = options.height || options.size || 1;
  37548. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37549. // Vertices
  37550. var halfWidth = width / 2.0;
  37551. var halfHeight = height / 2.0;
  37552. positions.push(-halfWidth, -halfHeight, 0);
  37553. normals.push(0, 0, -1.0);
  37554. uvs.push(0.0, 0.0);
  37555. positions.push(halfWidth, -halfHeight, 0);
  37556. normals.push(0, 0, -1.0);
  37557. uvs.push(1.0, 0.0);
  37558. positions.push(halfWidth, halfHeight, 0);
  37559. normals.push(0, 0, -1.0);
  37560. uvs.push(1.0, 1.0);
  37561. positions.push(-halfWidth, halfHeight, 0);
  37562. normals.push(0, 0, -1.0);
  37563. uvs.push(0.0, 1.0);
  37564. // Indices
  37565. indices.push(0);
  37566. indices.push(1);
  37567. indices.push(2);
  37568. indices.push(0);
  37569. indices.push(2);
  37570. indices.push(3);
  37571. // Sides
  37572. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37573. // Result
  37574. var vertexData = new VertexData();
  37575. vertexData.indices = indices;
  37576. vertexData.positions = positions;
  37577. vertexData.normals = normals;
  37578. vertexData.uvs = uvs;
  37579. return vertexData;
  37580. };
  37581. /**
  37582. * Creates the VertexData of the Disc or regular Polygon
  37583. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  37584. * * radius the radius of the disc, optional default 0.5
  37585. * * tessellation the number of polygon sides, optional, default 64
  37586. * * 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
  37587. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37588. * * 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)
  37589. * * 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)
  37590. * @returns the VertexData of the box
  37591. */
  37592. VertexData.CreateDisc = function (options) {
  37593. var positions = new Array();
  37594. var indices = new Array();
  37595. var normals = new Array();
  37596. var uvs = new Array();
  37597. var radius = options.radius || 0.5;
  37598. var tessellation = options.tessellation || 64;
  37599. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37600. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37601. // positions and uvs
  37602. positions.push(0, 0, 0); // disc center first
  37603. uvs.push(0.5, 0.5);
  37604. var theta = Math.PI * 2 * arc;
  37605. var step = theta / tessellation;
  37606. for (var a = 0; a < theta; a += step) {
  37607. var x = Math.cos(a);
  37608. var y = Math.sin(a);
  37609. var u = (x + 1) / 2;
  37610. var v = (1 - y) / 2;
  37611. positions.push(radius * x, radius * y, 0);
  37612. uvs.push(u, v);
  37613. }
  37614. if (arc === 1) {
  37615. positions.push(positions[3], positions[4], positions[5]); // close the circle
  37616. uvs.push(uvs[2], uvs[3]);
  37617. }
  37618. //indices
  37619. var vertexNb = positions.length / 3;
  37620. for (var i = 1; i < vertexNb - 1; i++) {
  37621. indices.push(i + 1, 0, i);
  37622. }
  37623. // result
  37624. VertexData.ComputeNormals(positions, indices, normals);
  37625. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37626. var vertexData = new VertexData();
  37627. vertexData.indices = indices;
  37628. vertexData.positions = positions;
  37629. vertexData.normals = normals;
  37630. vertexData.uvs = uvs;
  37631. return vertexData;
  37632. };
  37633. /**
  37634. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  37635. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  37636. * @param polygon a mesh built from polygonTriangulation.build()
  37637. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37638. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37639. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37640. * @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)
  37641. * @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)
  37642. * @returns the VertexData of the Polygon
  37643. */
  37644. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  37645. var faceUV = fUV || new Array(3);
  37646. var faceColors = fColors;
  37647. var colors = [];
  37648. // default face colors and UV if undefined
  37649. for (var f = 0; f < 3; f++) {
  37650. if (faceUV[f] === undefined) {
  37651. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37652. }
  37653. if (faceColors && faceColors[f] === undefined) {
  37654. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37655. }
  37656. }
  37657. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37658. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  37659. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37660. var indices = polygon.getIndices();
  37661. // set face colours and textures
  37662. var idx = 0;
  37663. var face = 0;
  37664. for (var index = 0; index < normals.length; index += 3) {
  37665. //Edge Face no. 1
  37666. if (Math.abs(normals[index + 1]) < 0.001) {
  37667. face = 1;
  37668. }
  37669. //Top Face no. 0
  37670. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  37671. face = 0;
  37672. }
  37673. //Bottom Face no. 2
  37674. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  37675. face = 2;
  37676. }
  37677. idx = index / 3;
  37678. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  37679. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  37680. if (faceColors) {
  37681. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  37682. }
  37683. }
  37684. // sides
  37685. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  37686. // Result
  37687. var vertexData = new VertexData();
  37688. vertexData.indices = indices;
  37689. vertexData.positions = positions;
  37690. vertexData.normals = normals;
  37691. vertexData.uvs = uvs;
  37692. if (faceColors) {
  37693. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37694. vertexData.colors = totalColors;
  37695. }
  37696. return vertexData;
  37697. };
  37698. /**
  37699. * Creates the VertexData of the IcoSphere
  37700. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  37701. * * radius the radius of the IcoSphere, optional default 1
  37702. * * radiusX allows stretching in the x direction, optional, default radius
  37703. * * radiusY allows stretching in the y direction, optional, default radius
  37704. * * radiusZ allows stretching in the z direction, optional, default radius
  37705. * * flat when true creates a flat shaded mesh, optional, default true
  37706. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37707. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37708. * * 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)
  37709. * * 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)
  37710. * @returns the VertexData of the IcoSphere
  37711. */
  37712. VertexData.CreateIcoSphere = function (options) {
  37713. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37714. var radius = options.radius || 1;
  37715. var flat = (options.flat === undefined) ? true : options.flat;
  37716. var subdivisions = options.subdivisions || 4;
  37717. var radiusX = options.radiusX || radius;
  37718. var radiusY = options.radiusY || radius;
  37719. var radiusZ = options.radiusZ || radius;
  37720. var t = (1 + Math.sqrt(5)) / 2;
  37721. // 12 vertex x,y,z
  37722. var ico_vertices = [
  37723. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  37724. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  37725. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  37726. ];
  37727. // index of 3 vertex makes a face of icopshere
  37728. var ico_indices = [
  37729. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  37730. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  37731. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  37732. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  37733. ];
  37734. // vertex for uv have aliased position, not for UV
  37735. var vertices_unalias_id = [
  37736. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  37737. // vertex alias
  37738. 0,
  37739. 2,
  37740. 3,
  37741. 3,
  37742. 3,
  37743. 4,
  37744. 7,
  37745. 8,
  37746. 9,
  37747. 9,
  37748. 10,
  37749. 11 // 23: B + 12
  37750. ];
  37751. // uv as integer step (not pixels !)
  37752. var ico_vertexuv = [
  37753. 5, 1, 3, 1, 6, 4, 0, 0,
  37754. 5, 3, 4, 2, 2, 2, 4, 0,
  37755. 2, 0, 1, 1, 6, 0, 6, 2,
  37756. // vertex alias (for same vertex on different faces)
  37757. 0, 4,
  37758. 3, 3,
  37759. 4, 4,
  37760. 3, 1,
  37761. 4, 2,
  37762. 4, 4,
  37763. 0, 2,
  37764. 1, 1,
  37765. 2, 2,
  37766. 3, 3,
  37767. 1, 3,
  37768. 2, 4 // 23: B + 12
  37769. ];
  37770. // Vertices[0, 1, ...9, A, B] : position on UV plane
  37771. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  37772. // First island of uv mapping
  37773. // v = 4h 3+ 2
  37774. // v = 3h 9+ 4
  37775. // v = 2h 9+ 5 B
  37776. // v = 1h 9 1 0
  37777. // v = 0h 3 8 7 A
  37778. // u = 0 1 2 3 4 5 6 *a
  37779. // Second island of uv mapping
  37780. // v = 4h 0+ B+ 4+
  37781. // v = 3h A+ 2+
  37782. // v = 2h 7+ 6 3+
  37783. // v = 1h 8+ 3+
  37784. // v = 0h
  37785. // u = 0 1 2 3 4 5 6 *a
  37786. // Face layout on texture UV mapping
  37787. // ============
  37788. // \ 4 /\ 16 / ======
  37789. // \ / \ / /\ 11 /
  37790. // \/ 7 \/ / \ /
  37791. // ======= / 10 \/
  37792. // /\ 17 /\ =======
  37793. // / \ / \ \ 15 /\
  37794. // / 8 \/ 12 \ \ / \
  37795. // ============ \/ 6 \
  37796. // \ 18 /\ ============
  37797. // \ / \ \ 5 /\ 0 /
  37798. // \/ 13 \ \ / \ /
  37799. // ======= \/ 1 \/
  37800. // =============
  37801. // /\ 19 /\ 2 /\
  37802. // / \ / \ / \
  37803. // / 14 \/ 9 \/ 3 \
  37804. // ===================
  37805. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  37806. var ustep = 138 / 1024;
  37807. var vstep = 239 / 1024;
  37808. var uoffset = 60 / 1024;
  37809. var voffset = 26 / 1024;
  37810. // Second island should have margin, not to touch the first island
  37811. // avoid any borderline artefact in pixel rounding
  37812. var island_u_offset = -40 / 1024;
  37813. var island_v_offset = +20 / 1024;
  37814. // face is either island 0 or 1 :
  37815. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  37816. var island = [
  37817. 0, 0, 0, 0, 1,
  37818. 0, 0, 1, 1, 0,
  37819. 0, 0, 1, 1, 0,
  37820. 0, 1, 1, 1, 0 // 15 - 19
  37821. ];
  37822. var indices = new Array();
  37823. var positions = new Array();
  37824. var normals = new Array();
  37825. var uvs = new Array();
  37826. var current_indice = 0;
  37827. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  37828. var face_vertex_pos = new Array(3);
  37829. var face_vertex_uv = new Array(3);
  37830. var v012;
  37831. for (v012 = 0; v012 < 3; v012++) {
  37832. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  37833. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  37834. }
  37835. // create all with normals
  37836. for (var face = 0; face < 20; face++) {
  37837. // 3 vertex per face
  37838. for (v012 = 0; v012 < 3; v012++) {
  37839. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  37840. var v_id = ico_indices[3 * face + v012];
  37841. // vertex have 3D position (x,y,z)
  37842. 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]);
  37843. // Normalize to get normal, then scale to radius
  37844. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  37845. // uv Coordinates from vertex ID
  37846. 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);
  37847. }
  37848. // Subdivide the face (interpolate pos, norm, uv)
  37849. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  37850. // - norm is linear interpolation of vertex corner normal
  37851. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  37852. // - uv is linear interpolation
  37853. //
  37854. // Topology is as below for sub-divide by 2
  37855. // vertex shown as v0,v1,v2
  37856. // interp index is i1 to progress in range [v0,v1[
  37857. // interp index is i2 to progress in range [v0,v2[
  37858. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  37859. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37860. //
  37861. //
  37862. // i2 v2
  37863. // ^ ^
  37864. // / / \
  37865. // / / \
  37866. // / / \
  37867. // / / (0,1) \
  37868. // / #---------\
  37869. // / / \ (0,0)'/ \
  37870. // / / \ / \
  37871. // / / \ / \
  37872. // / / (0,0) \ / (1,0) \
  37873. // / #---------#---------\
  37874. // v0 v1
  37875. //
  37876. // --------------------> i1
  37877. //
  37878. // interp of (i1,i2):
  37879. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  37880. // along i1 : lerp(x0,x1, i1/(S-i2))
  37881. //
  37882. // centroid of triangle is needed to get help normal computation
  37883. // (c1,c2) are used for centroid location
  37884. var interp_vertex = function (i1, i2, c1, c2) {
  37885. // vertex is interpolated from
  37886. // - face_vertex_pos[0..2]
  37887. // - face_vertex_uv[0..2]
  37888. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  37889. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  37890. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  37891. pos_interp.normalize();
  37892. var vertex_normal;
  37893. if (flat) {
  37894. // in flat mode, recalculate normal as face centroid normal
  37895. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  37896. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  37897. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  37898. }
  37899. else {
  37900. // in smooth mode, recalculate normal from each single vertex position
  37901. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  37902. }
  37903. // Vertex normal need correction due to X,Y,Z radius scaling
  37904. vertex_normal.x /= radiusX;
  37905. vertex_normal.y /= radiusY;
  37906. vertex_normal.z /= radiusZ;
  37907. vertex_normal.normalize();
  37908. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  37909. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  37910. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  37911. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  37912. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  37913. uvs.push(uv_interp.x, uv_interp.y);
  37914. // push each vertex has member of a face
  37915. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  37916. indices.push(current_indice);
  37917. current_indice++;
  37918. };
  37919. for (var i2 = 0; i2 < subdivisions; i2++) {
  37920. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  37921. // face : (i1,i2) for /\ :
  37922. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  37923. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37924. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37925. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37926. if (i1 + i2 + 1 < subdivisions) {
  37927. // face : (i1,i2)' for \/ :
  37928. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37929. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37930. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37931. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37932. }
  37933. }
  37934. }
  37935. }
  37936. // Sides
  37937. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37938. // Result
  37939. var vertexData = new VertexData();
  37940. vertexData.indices = indices;
  37941. vertexData.positions = positions;
  37942. vertexData.normals = normals;
  37943. vertexData.uvs = uvs;
  37944. return vertexData;
  37945. };
  37946. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  37947. /**
  37948. * Creates the VertexData for a Polyhedron
  37949. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  37950. * * type provided types are:
  37951. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  37952. * * 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)
  37953. * * size the size of the IcoSphere, optional default 1
  37954. * * sizeX allows stretching in the x direction, optional, default size
  37955. * * sizeY allows stretching in the y direction, optional, default size
  37956. * * sizeZ allows stretching in the z direction, optional, default size
  37957. * * 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
  37958. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37959. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37960. * * flat when true creates a flat shaded mesh, optional, default true
  37961. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37962. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37963. * * 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)
  37964. * * 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)
  37965. * @returns the VertexData of the Polyhedron
  37966. */
  37967. VertexData.CreatePolyhedron = function (options) {
  37968. // provided polyhedron types :
  37969. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  37970. // 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)
  37971. var polyhedra = [];
  37972. 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]] };
  37973. 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]] };
  37974. polyhedra[2] = {
  37975. 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]],
  37976. 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]]
  37977. };
  37978. polyhedra[3] = {
  37979. 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]],
  37980. 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]]
  37981. };
  37982. polyhedra[4] = {
  37983. 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]],
  37984. 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]]
  37985. };
  37986. 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]] };
  37987. 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]] };
  37988. 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]] };
  37989. 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]] };
  37990. 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]] };
  37991. 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]] };
  37992. 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]] };
  37993. 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]] };
  37994. 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]] };
  37995. polyhedra[14] = {
  37996. 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]],
  37997. 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]]
  37998. };
  37999. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  38000. var size = options.size;
  38001. var sizeX = options.sizeX || size || 1;
  38002. var sizeY = options.sizeY || size || 1;
  38003. var sizeZ = options.sizeZ || size || 1;
  38004. var data = options.custom || polyhedra[type];
  38005. var nbfaces = data.face.length;
  38006. var faceUV = options.faceUV || new Array(nbfaces);
  38007. var faceColors = options.faceColors;
  38008. var flat = (options.flat === undefined) ? true : options.flat;
  38009. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38010. var positions = new Array();
  38011. var indices = new Array();
  38012. var normals = new Array();
  38013. var uvs = new Array();
  38014. var colors = new Array();
  38015. var index = 0;
  38016. var faceIdx = 0; // face cursor in the array "indexes"
  38017. var indexes = new Array();
  38018. var i = 0;
  38019. var f = 0;
  38020. var u, v, ang, x, y, tmp;
  38021. // default face colors and UV if undefined
  38022. if (flat) {
  38023. for (f = 0; f < nbfaces; f++) {
  38024. if (faceColors && faceColors[f] === undefined) {
  38025. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38026. }
  38027. if (faceUV && faceUV[f] === undefined) {
  38028. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38029. }
  38030. }
  38031. }
  38032. if (!flat) {
  38033. for (i = 0; i < data.vertex.length; i++) {
  38034. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  38035. uvs.push(0, 0);
  38036. }
  38037. for (f = 0; f < nbfaces; f++) {
  38038. for (i = 0; i < data.face[f].length - 2; i++) {
  38039. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  38040. }
  38041. }
  38042. }
  38043. else {
  38044. for (f = 0; f < nbfaces; f++) {
  38045. var fl = data.face[f].length; // number of vertices of the current face
  38046. ang = 2 * Math.PI / fl;
  38047. x = 0.5 * Math.tan(ang / 2);
  38048. y = 0.5;
  38049. // positions, uvs, colors
  38050. for (i = 0; i < fl; i++) {
  38051. // positions
  38052. 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);
  38053. indexes.push(index);
  38054. index++;
  38055. // uvs
  38056. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  38057. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  38058. uvs.push(u, v);
  38059. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  38060. y = x * Math.sin(ang) + y * Math.cos(ang);
  38061. x = tmp;
  38062. // colors
  38063. if (faceColors) {
  38064. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  38065. }
  38066. }
  38067. // indices from indexes
  38068. for (i = 0; i < fl - 2; i++) {
  38069. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  38070. }
  38071. faceIdx += fl;
  38072. }
  38073. }
  38074. VertexData.ComputeNormals(positions, indices, normals);
  38075. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38076. var vertexData = new VertexData();
  38077. vertexData.positions = positions;
  38078. vertexData.indices = indices;
  38079. vertexData.normals = normals;
  38080. vertexData.uvs = uvs;
  38081. if (faceColors && flat) {
  38082. vertexData.colors = colors;
  38083. }
  38084. return vertexData;
  38085. };
  38086. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  38087. /**
  38088. * Creates the VertexData for a TorusKnot
  38089. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  38090. * * radius the radius of the torus knot, optional, default 2
  38091. * * tube the thickness of the tube, optional, default 0.5
  38092. * * radialSegments the number of sides on each tube segments, optional, default 32
  38093. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  38094. * * p the number of windings around the z axis, optional, default 2
  38095. * * q the number of windings around the x axis, optional, default 3
  38096. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38097. * * 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)
  38098. * * 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)
  38099. * @returns the VertexData of the Torus Knot
  38100. */
  38101. VertexData.CreateTorusKnot = function (options) {
  38102. var indices = new Array();
  38103. var positions = new Array();
  38104. var normals = new Array();
  38105. var uvs = new Array();
  38106. var radius = options.radius || 2;
  38107. var tube = options.tube || 0.5;
  38108. var radialSegments = options.radialSegments || 32;
  38109. var tubularSegments = options.tubularSegments || 32;
  38110. var p = options.p || 2;
  38111. var q = options.q || 3;
  38112. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38113. // Helper
  38114. var getPos = function (angle) {
  38115. var cu = Math.cos(angle);
  38116. var su = Math.sin(angle);
  38117. var quOverP = q / p * angle;
  38118. var cs = Math.cos(quOverP);
  38119. var tx = radius * (2 + cs) * 0.5 * cu;
  38120. var ty = radius * (2 + cs) * su * 0.5;
  38121. var tz = radius * Math.sin(quOverP) * 0.5;
  38122. return new BABYLON.Vector3(tx, ty, tz);
  38123. };
  38124. // Vertices
  38125. var i;
  38126. var j;
  38127. for (i = 0; i <= radialSegments; i++) {
  38128. var modI = i % radialSegments;
  38129. var u = modI / radialSegments * 2 * p * Math.PI;
  38130. var p1 = getPos(u);
  38131. var p2 = getPos(u + 0.01);
  38132. var tang = p2.subtract(p1);
  38133. var n = p2.add(p1);
  38134. var bitan = BABYLON.Vector3.Cross(tang, n);
  38135. n = BABYLON.Vector3.Cross(bitan, tang);
  38136. bitan.normalize();
  38137. n.normalize();
  38138. for (j = 0; j < tubularSegments; j++) {
  38139. var modJ = j % tubularSegments;
  38140. var v = modJ / tubularSegments * 2 * Math.PI;
  38141. var cx = -tube * Math.cos(v);
  38142. var cy = tube * Math.sin(v);
  38143. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38144. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38145. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38146. uvs.push(i / radialSegments);
  38147. uvs.push(j / tubularSegments);
  38148. }
  38149. }
  38150. for (i = 0; i < radialSegments; i++) {
  38151. for (j = 0; j < tubularSegments; j++) {
  38152. var jNext = (j + 1) % tubularSegments;
  38153. var a = i * tubularSegments + j;
  38154. var b = (i + 1) * tubularSegments + j;
  38155. var c = (i + 1) * tubularSegments + jNext;
  38156. var d = i * tubularSegments + jNext;
  38157. indices.push(d);
  38158. indices.push(b);
  38159. indices.push(a);
  38160. indices.push(d);
  38161. indices.push(c);
  38162. indices.push(b);
  38163. }
  38164. }
  38165. // Normals
  38166. VertexData.ComputeNormals(positions, indices, normals);
  38167. // Sides
  38168. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38169. // Result
  38170. var vertexData = new VertexData();
  38171. vertexData.indices = indices;
  38172. vertexData.positions = positions;
  38173. vertexData.normals = normals;
  38174. vertexData.uvs = uvs;
  38175. return vertexData;
  38176. };
  38177. // Tools
  38178. /**
  38179. * Compute normals for given positions and indices
  38180. * @param positions an array of vertex positions, [...., x, y, z, ......]
  38181. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  38182. * @param normals an array of vertex normals, [...., x, y, z, ......]
  38183. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  38184. * * facetNormals : optional array of facet normals (vector3)
  38185. * * facetPositions : optional array of facet positions (vector3)
  38186. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38187. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38188. * * bInfo : optional bounding info, required for facetPartitioning computation
  38189. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  38190. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38191. * * useRightHandedSystem: optional boolean to for right handed system computation
  38192. * * depthSort : optional boolean to enable the facet depth sort computation
  38193. * * distanceTo : optional Vector3 to compute the facet depth from this location
  38194. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  38195. */
  38196. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38197. // temporary scalar variables
  38198. var index = 0; // facet index
  38199. var p1p2x = 0.0; // p1p2 vector x coordinate
  38200. var p1p2y = 0.0; // p1p2 vector y coordinate
  38201. var p1p2z = 0.0; // p1p2 vector z coordinate
  38202. var p3p2x = 0.0; // p3p2 vector x coordinate
  38203. var p3p2y = 0.0; // p3p2 vector y coordinate
  38204. var p3p2z = 0.0; // p3p2 vector z coordinate
  38205. var faceNormalx = 0.0; // facet normal x coordinate
  38206. var faceNormaly = 0.0; // facet normal y coordinate
  38207. var faceNormalz = 0.0; // facet normal z coordinate
  38208. var length = 0.0; // facet normal length before normalization
  38209. var v1x = 0; // vector1 x index in the positions array
  38210. var v1y = 0; // vector1 y index in the positions array
  38211. var v1z = 0; // vector1 z index in the positions array
  38212. var v2x = 0; // vector2 x index in the positions array
  38213. var v2y = 0; // vector2 y index in the positions array
  38214. var v2z = 0; // vector2 z index in the positions array
  38215. var v3x = 0; // vector3 x index in the positions array
  38216. var v3y = 0; // vector3 y index in the positions array
  38217. var v3z = 0; // vector3 z index in the positions array
  38218. var computeFacetNormals = false;
  38219. var computeFacetPositions = false;
  38220. var computeFacetPartitioning = false;
  38221. var computeDepthSort = false;
  38222. var faceNormalSign = 1;
  38223. var ratio = 0;
  38224. var distanceTo = null;
  38225. if (options) {
  38226. computeFacetNormals = (options.facetNormals) ? true : false;
  38227. computeFacetPositions = (options.facetPositions) ? true : false;
  38228. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38229. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38230. ratio = options.ratio || 0;
  38231. computeDepthSort = (options.depthSort) ? true : false;
  38232. distanceTo = (options.distanceTo);
  38233. if (computeDepthSort) {
  38234. if (distanceTo === undefined) {
  38235. distanceTo = BABYLON.Vector3.Zero();
  38236. }
  38237. var depthSortedFacets = options.depthSortedFacets;
  38238. }
  38239. }
  38240. // facetPartitioning reinit if needed
  38241. var xSubRatio = 0;
  38242. var ySubRatio = 0;
  38243. var zSubRatio = 0;
  38244. var subSq = 0;
  38245. if (computeFacetPartitioning && options && options.bbSize) {
  38246. var ox = 0; // X partitioning index for facet position
  38247. var oy = 0; // Y partinioning index for facet position
  38248. var oz = 0; // Z partinioning index for facet position
  38249. var b1x = 0; // X partitioning index for facet v1 vertex
  38250. var b1y = 0; // Y partitioning index for facet v1 vertex
  38251. var b1z = 0; // z partitioning index for facet v1 vertex
  38252. var b2x = 0; // X partitioning index for facet v2 vertex
  38253. var b2y = 0; // Y partitioning index for facet v2 vertex
  38254. var b2z = 0; // Z partitioning index for facet v2 vertex
  38255. var b3x = 0; // X partitioning index for facet v3 vertex
  38256. var b3y = 0; // Y partitioning index for facet v3 vertex
  38257. var b3z = 0; // Z partitioning index for facet v3 vertex
  38258. var block_idx_o = 0; // facet barycenter block index
  38259. var block_idx_v1 = 0; // v1 vertex block index
  38260. var block_idx_v2 = 0; // v2 vertex block index
  38261. var block_idx_v3 = 0; // v3 vertex block index
  38262. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38263. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38264. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38265. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38266. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38267. subSq = options.subDiv.max * options.subDiv.max;
  38268. options.facetPartitioning.length = 0;
  38269. }
  38270. // reset the normals
  38271. for (index = 0; index < positions.length; index++) {
  38272. normals[index] = 0.0;
  38273. }
  38274. // Loop : 1 indice triplet = 1 facet
  38275. var nbFaces = (indices.length / 3) | 0;
  38276. for (index = 0; index < nbFaces; index++) {
  38277. // get the indexes of the coordinates of each vertex of the facet
  38278. v1x = indices[index * 3] * 3;
  38279. v1y = v1x + 1;
  38280. v1z = v1x + 2;
  38281. v2x = indices[index * 3 + 1] * 3;
  38282. v2y = v2x + 1;
  38283. v2z = v2x + 2;
  38284. v3x = indices[index * 3 + 2] * 3;
  38285. v3y = v3x + 1;
  38286. v3z = v3x + 2;
  38287. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38288. p1p2y = positions[v1y] - positions[v2y];
  38289. p1p2z = positions[v1z] - positions[v2z];
  38290. p3p2x = positions[v3x] - positions[v2x];
  38291. p3p2y = positions[v3y] - positions[v2y];
  38292. p3p2z = positions[v3z] - positions[v2z];
  38293. // compute the face normal with the cross product
  38294. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38295. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38296. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38297. // normalize this normal and store it in the array facetData
  38298. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38299. length = (length === 0) ? 1.0 : length;
  38300. faceNormalx /= length;
  38301. faceNormaly /= length;
  38302. faceNormalz /= length;
  38303. if (computeFacetNormals && options) {
  38304. options.facetNormals[index].x = faceNormalx;
  38305. options.facetNormals[index].y = faceNormaly;
  38306. options.facetNormals[index].z = faceNormalz;
  38307. }
  38308. if (computeFacetPositions && options) {
  38309. // compute and the facet barycenter coordinates in the array facetPositions
  38310. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38311. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38312. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38313. }
  38314. if (computeFacetPartitioning && options) {
  38315. // store the facet indexes in arrays in the main facetPartitioning array :
  38316. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38317. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38318. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38319. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38320. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38321. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38322. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38323. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38324. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38325. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38326. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38327. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38328. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38329. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38330. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38331. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38332. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38333. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38334. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38335. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38336. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38337. // push each facet index in each block containing the vertex
  38338. options.facetPartitioning[block_idx_v1].push(index);
  38339. if (block_idx_v2 != block_idx_v1) {
  38340. options.facetPartitioning[block_idx_v2].push(index);
  38341. }
  38342. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38343. options.facetPartitioning[block_idx_v3].push(index);
  38344. }
  38345. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38346. options.facetPartitioning[block_idx_o].push(index);
  38347. }
  38348. }
  38349. if (computeDepthSort && options && options.facetPositions) {
  38350. var dsf = depthSortedFacets[index];
  38351. dsf.ind = index * 3;
  38352. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38353. }
  38354. // compute the normals anyway
  38355. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38356. normals[v1y] += faceNormaly;
  38357. normals[v1z] += faceNormalz;
  38358. normals[v2x] += faceNormalx;
  38359. normals[v2y] += faceNormaly;
  38360. normals[v2z] += faceNormalz;
  38361. normals[v3x] += faceNormalx;
  38362. normals[v3y] += faceNormaly;
  38363. normals[v3z] += faceNormalz;
  38364. }
  38365. // last normalization of each normal
  38366. for (index = 0; index < normals.length / 3; index++) {
  38367. faceNormalx = normals[index * 3];
  38368. faceNormaly = normals[index * 3 + 1];
  38369. faceNormalz = normals[index * 3 + 2];
  38370. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38371. length = (length === 0) ? 1.0 : length;
  38372. faceNormalx /= length;
  38373. faceNormaly /= length;
  38374. faceNormalz /= length;
  38375. normals[index * 3] = faceNormalx;
  38376. normals[index * 3 + 1] = faceNormaly;
  38377. normals[index * 3 + 2] = faceNormalz;
  38378. }
  38379. };
  38380. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38381. var li = indices.length;
  38382. var ln = normals.length;
  38383. var i;
  38384. var n;
  38385. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38386. switch (sideOrientation) {
  38387. case BABYLON.Mesh.FRONTSIDE:
  38388. // nothing changed
  38389. break;
  38390. case BABYLON.Mesh.BACKSIDE:
  38391. var tmp;
  38392. // indices
  38393. for (i = 0; i < li; i += 3) {
  38394. tmp = indices[i];
  38395. indices[i] = indices[i + 2];
  38396. indices[i + 2] = tmp;
  38397. }
  38398. // normals
  38399. for (n = 0; n < ln; n++) {
  38400. normals[n] = -normals[n];
  38401. }
  38402. break;
  38403. case BABYLON.Mesh.DOUBLESIDE:
  38404. // positions
  38405. var lp = positions.length;
  38406. var l = lp / 3;
  38407. for (var p = 0; p < lp; p++) {
  38408. positions[lp + p] = positions[p];
  38409. }
  38410. // indices
  38411. for (i = 0; i < li; i += 3) {
  38412. indices[i + li] = indices[i + 2] + l;
  38413. indices[i + 1 + li] = indices[i + 1] + l;
  38414. indices[i + 2 + li] = indices[i] + l;
  38415. }
  38416. // normals
  38417. for (n = 0; n < ln; n++) {
  38418. normals[ln + n] = -normals[n];
  38419. }
  38420. // uvs
  38421. var lu = uvs.length;
  38422. var u = 0;
  38423. for (u = 0; u < lu; u++) {
  38424. uvs[u + lu] = uvs[u];
  38425. }
  38426. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38427. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38428. u = 0;
  38429. for (i = 0; i < lu / 2; i++) {
  38430. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38431. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38432. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38433. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38434. u += 2;
  38435. }
  38436. break;
  38437. }
  38438. };
  38439. /**
  38440. * Applies VertexData created from the imported parameters to the geometry
  38441. * @param parsedVertexData the parsed data from an imported file
  38442. * @param geometry the geometry to apply the VertexData to
  38443. */
  38444. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38445. var vertexData = new VertexData();
  38446. // positions
  38447. var positions = parsedVertexData.positions;
  38448. if (positions) {
  38449. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38450. }
  38451. // normals
  38452. var normals = parsedVertexData.normals;
  38453. if (normals) {
  38454. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38455. }
  38456. // tangents
  38457. var tangents = parsedVertexData.tangents;
  38458. if (tangents) {
  38459. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38460. }
  38461. // uvs
  38462. var uvs = parsedVertexData.uvs;
  38463. if (uvs) {
  38464. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38465. }
  38466. // uv2s
  38467. var uv2s = parsedVertexData.uv2s;
  38468. if (uv2s) {
  38469. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38470. }
  38471. // uv3s
  38472. var uv3s = parsedVertexData.uv3s;
  38473. if (uv3s) {
  38474. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38475. }
  38476. // uv4s
  38477. var uv4s = parsedVertexData.uv4s;
  38478. if (uv4s) {
  38479. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38480. }
  38481. // uv5s
  38482. var uv5s = parsedVertexData.uv5s;
  38483. if (uv5s) {
  38484. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38485. }
  38486. // uv6s
  38487. var uv6s = parsedVertexData.uv6s;
  38488. if (uv6s) {
  38489. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38490. }
  38491. // colors
  38492. var colors = parsedVertexData.colors;
  38493. if (colors) {
  38494. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38495. }
  38496. // matricesIndices
  38497. var matricesIndices = parsedVertexData.matricesIndices;
  38498. if (matricesIndices) {
  38499. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38500. }
  38501. // matricesWeights
  38502. var matricesWeights = parsedVertexData.matricesWeights;
  38503. if (matricesWeights) {
  38504. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38505. }
  38506. // indices
  38507. var indices = parsedVertexData.indices;
  38508. if (indices) {
  38509. vertexData.indices = indices;
  38510. }
  38511. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  38512. };
  38513. return VertexData;
  38514. }());
  38515. BABYLON.VertexData = VertexData;
  38516. })(BABYLON || (BABYLON = {}));
  38517. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  38518. var BABYLON;
  38519. (function (BABYLON) {
  38520. /**
  38521. * Class used to store geometry data (vertex buffers + index buffer)
  38522. */
  38523. var Geometry = /** @class */ (function () {
  38524. /**
  38525. * Creates a new geometry
  38526. * @param id defines the unique ID
  38527. * @param scene defines the hosting scene
  38528. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  38529. * @param updatable defines if geometry must be updatable (false by default)
  38530. * @param mesh defines the mesh that will be associated with the geometry
  38531. */
  38532. function Geometry(id, scene, vertexData, updatable, mesh) {
  38533. if (updatable === void 0) { updatable = false; }
  38534. if (mesh === void 0) { mesh = null; }
  38535. /**
  38536. * Gets the delay loading state of the geometry (none by default which means not delayed)
  38537. */
  38538. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38539. this._totalVertices = 0;
  38540. this._isDisposed = false;
  38541. this._indexBufferIsUpdatable = false;
  38542. this.id = id;
  38543. this._engine = scene.getEngine();
  38544. this._meshes = [];
  38545. this._scene = scene;
  38546. //Init vertex buffer cache
  38547. this._vertexBuffers = {};
  38548. this._indices = [];
  38549. this._updatable = updatable;
  38550. // vertexData
  38551. if (vertexData) {
  38552. this.setAllVerticesData(vertexData, updatable);
  38553. }
  38554. else {
  38555. this._totalVertices = 0;
  38556. this._indices = [];
  38557. }
  38558. if (this._engine.getCaps().vertexArrayObject) {
  38559. this._vertexArrayObjects = {};
  38560. }
  38561. // applyToMesh
  38562. if (mesh) {
  38563. if (mesh.getClassName() === "LinesMesh") {
  38564. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  38565. this._updateExtend();
  38566. }
  38567. this.applyToMesh(mesh);
  38568. mesh.computeWorldMatrix(true);
  38569. }
  38570. }
  38571. Object.defineProperty(Geometry.prototype, "boundingBias", {
  38572. /**
  38573. * 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
  38574. */
  38575. get: function () {
  38576. return this._boundingBias;
  38577. },
  38578. /**
  38579. * 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
  38580. */
  38581. set: function (value) {
  38582. if (this._boundingBias && this._boundingBias.equals(value)) {
  38583. return;
  38584. }
  38585. this._boundingBias = value.clone();
  38586. this._updateBoundingInfo(true, null);
  38587. },
  38588. enumerable: true,
  38589. configurable: true
  38590. });
  38591. /**
  38592. * Static function used to attach a new empty geometry to a mesh
  38593. * @param mesh defines the mesh to attach the geometry to
  38594. * @returns the new {BABYLON.Geometry}
  38595. */
  38596. Geometry.CreateGeometryForMesh = function (mesh) {
  38597. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  38598. geometry.applyToMesh(mesh);
  38599. return geometry;
  38600. };
  38601. Object.defineProperty(Geometry.prototype, "extend", {
  38602. /**
  38603. * Gets the current extend of the geometry
  38604. */
  38605. get: function () {
  38606. return this._extend;
  38607. },
  38608. enumerable: true,
  38609. configurable: true
  38610. });
  38611. /**
  38612. * Gets the hosting scene
  38613. * @returns the hosting {BABYLON.Scene}
  38614. */
  38615. Geometry.prototype.getScene = function () {
  38616. return this._scene;
  38617. };
  38618. /**
  38619. * Gets the hosting engine
  38620. * @returns the hosting {BABYLON.Engine}
  38621. */
  38622. Geometry.prototype.getEngine = function () {
  38623. return this._engine;
  38624. };
  38625. /**
  38626. * Defines if the geometry is ready to use
  38627. * @returns true if the geometry is ready to be used
  38628. */
  38629. Geometry.prototype.isReady = function () {
  38630. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  38631. };
  38632. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  38633. /**
  38634. * Gets a value indicating that the geometry should not be serialized
  38635. */
  38636. get: function () {
  38637. for (var index = 0; index < this._meshes.length; index++) {
  38638. if (!this._meshes[index].doNotSerialize) {
  38639. return false;
  38640. }
  38641. }
  38642. return true;
  38643. },
  38644. enumerable: true,
  38645. configurable: true
  38646. });
  38647. /** @hidden */
  38648. Geometry.prototype._rebuild = function () {
  38649. if (this._vertexArrayObjects) {
  38650. this._vertexArrayObjects = {};
  38651. }
  38652. // Index buffer
  38653. if (this._meshes.length !== 0 && this._indices) {
  38654. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  38655. }
  38656. // Vertex buffers
  38657. for (var key in this._vertexBuffers) {
  38658. var vertexBuffer = this._vertexBuffers[key];
  38659. vertexBuffer._rebuild();
  38660. }
  38661. };
  38662. /**
  38663. * Affects all geometry data in one call
  38664. * @param vertexData defines the geometry data
  38665. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  38666. */
  38667. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  38668. vertexData.applyToGeometry(this, updatable);
  38669. this.notifyUpdate();
  38670. };
  38671. /**
  38672. * Set specific vertex data
  38673. * @param kind defines the data kind (Position, normal, etc...)
  38674. * @param data defines the vertex data to use
  38675. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  38676. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  38677. */
  38678. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  38679. if (updatable === void 0) { updatable = false; }
  38680. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  38681. this.setVerticesBuffer(buffer);
  38682. };
  38683. /**
  38684. * Removes a specific vertex data
  38685. * @param kind defines the data kind (Position, normal, etc...)
  38686. */
  38687. Geometry.prototype.removeVerticesData = function (kind) {
  38688. if (this._vertexBuffers[kind]) {
  38689. this._vertexBuffers[kind].dispose();
  38690. delete this._vertexBuffers[kind];
  38691. }
  38692. };
  38693. /**
  38694. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  38695. * @param buffer defines the vertex buffer to use
  38696. * @param totalVertices defines the total number of vertices for position kind (could be null)
  38697. */
  38698. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  38699. if (totalVertices === void 0) { totalVertices = null; }
  38700. var kind = buffer.getKind();
  38701. if (this._vertexBuffers[kind]) {
  38702. this._vertexBuffers[kind].dispose();
  38703. }
  38704. this._vertexBuffers[kind] = buffer;
  38705. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38706. var data = buffer.getData();
  38707. if (totalVertices != null) {
  38708. this._totalVertices = totalVertices;
  38709. }
  38710. else {
  38711. if (data != null) {
  38712. this._totalVertices = data.length / (buffer.byteStride / 4);
  38713. }
  38714. }
  38715. this._updateExtend(data);
  38716. this._resetPointsArrayCache();
  38717. var meshes = this._meshes;
  38718. var numOfMeshes = meshes.length;
  38719. for (var index = 0; index < numOfMeshes; index++) {
  38720. var mesh = meshes[index];
  38721. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38722. mesh._createGlobalSubMesh(false);
  38723. mesh.computeWorldMatrix(true);
  38724. }
  38725. }
  38726. this.notifyUpdate(kind);
  38727. if (this._vertexArrayObjects) {
  38728. this._disposeVertexArrayObjects();
  38729. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  38730. }
  38731. };
  38732. /**
  38733. * Update a specific vertex buffer
  38734. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  38735. * It will do nothing if the buffer is not updatable
  38736. * @param kind defines the data kind (Position, normal, etc...)
  38737. * @param data defines the data to use
  38738. * @param offset defines the offset in the target buffer where to store the data
  38739. * @param useBytes set to true if the offset is in bytes
  38740. */
  38741. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  38742. if (useBytes === void 0) { useBytes = false; }
  38743. var vertexBuffer = this.getVertexBuffer(kind);
  38744. if (!vertexBuffer) {
  38745. return;
  38746. }
  38747. vertexBuffer.updateDirectly(data, offset, useBytes);
  38748. this.notifyUpdate(kind);
  38749. };
  38750. /**
  38751. * Update a specific vertex buffer
  38752. * This function will create a new buffer if the current one is not updatable
  38753. * @param kind defines the data kind (Position, normal, etc...)
  38754. * @param data defines the data to use
  38755. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  38756. */
  38757. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  38758. if (updateExtends === void 0) { updateExtends = false; }
  38759. var vertexBuffer = this.getVertexBuffer(kind);
  38760. if (!vertexBuffer) {
  38761. return;
  38762. }
  38763. vertexBuffer.update(data);
  38764. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38765. this._updateBoundingInfo(updateExtends, data);
  38766. }
  38767. this.notifyUpdate(kind);
  38768. };
  38769. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  38770. if (updateExtends) {
  38771. this._updateExtend(data);
  38772. }
  38773. var meshes = this._meshes;
  38774. var numOfMeshes = meshes.length;
  38775. this._resetPointsArrayCache();
  38776. for (var index = 0; index < numOfMeshes; index++) {
  38777. var mesh = meshes[index];
  38778. if (updateExtends) {
  38779. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38780. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  38781. var subMesh = mesh.subMeshes[subIndex];
  38782. subMesh.refreshBoundingInfo();
  38783. }
  38784. }
  38785. }
  38786. };
  38787. /** @hidden */
  38788. Geometry.prototype._bind = function (effect, indexToBind) {
  38789. if (!effect) {
  38790. return;
  38791. }
  38792. if (indexToBind === undefined) {
  38793. indexToBind = this._indexBuffer;
  38794. }
  38795. var vbs = this.getVertexBuffers();
  38796. if (!vbs) {
  38797. return;
  38798. }
  38799. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  38800. this._engine.bindBuffers(vbs, indexToBind, effect);
  38801. return;
  38802. }
  38803. // Using VAO
  38804. if (!this._vertexArrayObjects[effect.key]) {
  38805. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  38806. }
  38807. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  38808. };
  38809. /**
  38810. * Gets total number of vertices
  38811. * @returns the total number of vertices
  38812. */
  38813. Geometry.prototype.getTotalVertices = function () {
  38814. if (!this.isReady()) {
  38815. return 0;
  38816. }
  38817. return this._totalVertices;
  38818. };
  38819. /**
  38820. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  38821. * @param kind defines the data kind (Position, normal, etc...)
  38822. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  38823. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  38824. * @returns a float array containing vertex data
  38825. */
  38826. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  38827. var vertexBuffer = this.getVertexBuffer(kind);
  38828. if (!vertexBuffer) {
  38829. return null;
  38830. }
  38831. var data = vertexBuffer.getData();
  38832. if (!data) {
  38833. return null;
  38834. }
  38835. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  38836. var count = this._totalVertices * vertexBuffer.getSize();
  38837. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  38838. var copy_1 = new Array(count);
  38839. vertexBuffer.forEach(count, function (value, index) {
  38840. copy_1[index] = value;
  38841. });
  38842. return copy_1;
  38843. }
  38844. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  38845. if (data instanceof Array) {
  38846. var offset = vertexBuffer.byteOffset / 4;
  38847. return BABYLON.Tools.Slice(data, offset, offset + count);
  38848. }
  38849. else if (data instanceof ArrayBuffer) {
  38850. return new Float32Array(data, vertexBuffer.byteOffset, count);
  38851. }
  38852. else {
  38853. var offset = data.byteOffset + vertexBuffer.byteOffset;
  38854. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  38855. var result = new Float32Array(count);
  38856. var source = new Float32Array(data.buffer, offset, count);
  38857. result.set(source);
  38858. return result;
  38859. }
  38860. return new Float32Array(data.buffer, offset, count);
  38861. }
  38862. }
  38863. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  38864. return BABYLON.Tools.Slice(data);
  38865. }
  38866. return data;
  38867. };
  38868. /**
  38869. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  38870. * @param kind defines the data kind (Position, normal, etc...)
  38871. * @returns true if the vertex buffer with the specified kind is updatable
  38872. */
  38873. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  38874. var vb = this._vertexBuffers[kind];
  38875. if (!vb) {
  38876. return false;
  38877. }
  38878. return vb.isUpdatable();
  38879. };
  38880. /**
  38881. * Gets a specific vertex buffer
  38882. * @param kind defines the data kind (Position, normal, etc...)
  38883. * @returns a {BABYLON.VertexBuffer}
  38884. */
  38885. Geometry.prototype.getVertexBuffer = function (kind) {
  38886. if (!this.isReady()) {
  38887. return null;
  38888. }
  38889. return this._vertexBuffers[kind];
  38890. };
  38891. /**
  38892. * Returns all vertex buffers
  38893. * @return an object holding all vertex buffers indexed by kind
  38894. */
  38895. Geometry.prototype.getVertexBuffers = function () {
  38896. if (!this.isReady()) {
  38897. return null;
  38898. }
  38899. return this._vertexBuffers;
  38900. };
  38901. /**
  38902. * Gets a boolean indicating if specific vertex buffer is present
  38903. * @param kind defines the data kind (Position, normal, etc...)
  38904. * @returns true if data is present
  38905. */
  38906. Geometry.prototype.isVerticesDataPresent = function (kind) {
  38907. if (!this._vertexBuffers) {
  38908. if (this._delayInfo) {
  38909. return this._delayInfo.indexOf(kind) !== -1;
  38910. }
  38911. return false;
  38912. }
  38913. return this._vertexBuffers[kind] !== undefined;
  38914. };
  38915. /**
  38916. * Gets a list of all attached data kinds (Position, normal, etc...)
  38917. * @returns a list of string containing all kinds
  38918. */
  38919. Geometry.prototype.getVerticesDataKinds = function () {
  38920. var result = [];
  38921. var kind;
  38922. if (!this._vertexBuffers && this._delayInfo) {
  38923. for (kind in this._delayInfo) {
  38924. result.push(kind);
  38925. }
  38926. }
  38927. else {
  38928. for (kind in this._vertexBuffers) {
  38929. result.push(kind);
  38930. }
  38931. }
  38932. return result;
  38933. };
  38934. /**
  38935. * Update index buffer
  38936. * @param indices defines the indices to store in the index buffer
  38937. * @param offset defines the offset in the target buffer where to store the data
  38938. */
  38939. Geometry.prototype.updateIndices = function (indices, offset) {
  38940. if (!this._indexBuffer) {
  38941. return;
  38942. }
  38943. if (!this._indexBufferIsUpdatable) {
  38944. this.setIndices(indices, null, true);
  38945. }
  38946. else {
  38947. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  38948. }
  38949. };
  38950. /**
  38951. * Creates a new index buffer
  38952. * @param indices defines the indices to store in the index buffer
  38953. * @param totalVertices defines the total number of vertices (could be null)
  38954. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  38955. */
  38956. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  38957. if (totalVertices === void 0) { totalVertices = null; }
  38958. if (updatable === void 0) { updatable = false; }
  38959. if (this._indexBuffer) {
  38960. this._engine._releaseBuffer(this._indexBuffer);
  38961. }
  38962. this._disposeVertexArrayObjects();
  38963. this._indices = indices;
  38964. this._indexBufferIsUpdatable = updatable;
  38965. if (this._meshes.length !== 0 && this._indices) {
  38966. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  38967. }
  38968. if (totalVertices != undefined) { // including null and undefined
  38969. this._totalVertices = totalVertices;
  38970. }
  38971. var meshes = this._meshes;
  38972. var numOfMeshes = meshes.length;
  38973. for (var index = 0; index < numOfMeshes; index++) {
  38974. meshes[index]._createGlobalSubMesh(true);
  38975. }
  38976. this.notifyUpdate();
  38977. };
  38978. /**
  38979. * Return the total number of indices
  38980. * @returns the total number of indices
  38981. */
  38982. Geometry.prototype.getTotalIndices = function () {
  38983. if (!this.isReady()) {
  38984. return 0;
  38985. }
  38986. return this._indices.length;
  38987. };
  38988. /**
  38989. * Gets the index buffer array
  38990. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  38991. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  38992. * @returns the index buffer array
  38993. */
  38994. Geometry.prototype.getIndices = function (copyWhenShared, forceCopy) {
  38995. if (!this.isReady()) {
  38996. return null;
  38997. }
  38998. var orig = this._indices;
  38999. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  39000. return orig;
  39001. }
  39002. else {
  39003. var len = orig.length;
  39004. var copy = [];
  39005. for (var i = 0; i < len; i++) {
  39006. copy.push(orig[i]);
  39007. }
  39008. return copy;
  39009. }
  39010. };
  39011. /**
  39012. * Gets the index buffer
  39013. * @return the index buffer
  39014. */
  39015. Geometry.prototype.getIndexBuffer = function () {
  39016. if (!this.isReady()) {
  39017. return null;
  39018. }
  39019. return this._indexBuffer;
  39020. };
  39021. /** @hidden */
  39022. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  39023. if (effect === void 0) { effect = null; }
  39024. if (!effect || !this._vertexArrayObjects) {
  39025. return;
  39026. }
  39027. if (this._vertexArrayObjects[effect.key]) {
  39028. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  39029. delete this._vertexArrayObjects[effect.key];
  39030. }
  39031. };
  39032. /**
  39033. * Release the associated resources for a specific mesh
  39034. * @param mesh defines the source mesh
  39035. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  39036. */
  39037. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  39038. var meshes = this._meshes;
  39039. var index = meshes.indexOf(mesh);
  39040. if (index === -1) {
  39041. return;
  39042. }
  39043. meshes.splice(index, 1);
  39044. mesh._geometry = null;
  39045. if (meshes.length === 0 && shouldDispose) {
  39046. this.dispose();
  39047. }
  39048. };
  39049. /**
  39050. * Apply current geometry to a given mesh
  39051. * @param mesh defines the mesh to apply geometry to
  39052. */
  39053. Geometry.prototype.applyToMesh = function (mesh) {
  39054. if (mesh._geometry === this) {
  39055. return;
  39056. }
  39057. var previousGeometry = mesh._geometry;
  39058. if (previousGeometry) {
  39059. previousGeometry.releaseForMesh(mesh);
  39060. }
  39061. var meshes = this._meshes;
  39062. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  39063. mesh._geometry = this;
  39064. this._scene.pushGeometry(this);
  39065. meshes.push(mesh);
  39066. if (this.isReady()) {
  39067. this._applyToMesh(mesh);
  39068. }
  39069. else {
  39070. mesh._boundingInfo = this._boundingInfo;
  39071. }
  39072. };
  39073. Geometry.prototype._updateExtend = function (data) {
  39074. if (data === void 0) { data = null; }
  39075. if (!data) {
  39076. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39077. }
  39078. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  39079. };
  39080. Geometry.prototype._applyToMesh = function (mesh) {
  39081. var numOfMeshes = this._meshes.length;
  39082. // vertexBuffers
  39083. for (var kind in this._vertexBuffers) {
  39084. if (numOfMeshes === 1) {
  39085. this._vertexBuffers[kind].create();
  39086. }
  39087. var buffer = this._vertexBuffers[kind].getBuffer();
  39088. if (buffer)
  39089. buffer.references = numOfMeshes;
  39090. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39091. if (!this._extend) {
  39092. this._updateExtend();
  39093. }
  39094. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39095. mesh._createGlobalSubMesh(false);
  39096. //bounding info was just created again, world matrix should be applied again.
  39097. mesh._updateBoundingInfo();
  39098. }
  39099. }
  39100. // indexBuffer
  39101. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  39102. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39103. }
  39104. if (this._indexBuffer) {
  39105. this._indexBuffer.references = numOfMeshes;
  39106. }
  39107. };
  39108. Geometry.prototype.notifyUpdate = function (kind) {
  39109. if (this.onGeometryUpdated) {
  39110. this.onGeometryUpdated(this, kind);
  39111. }
  39112. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  39113. var mesh = _a[_i];
  39114. mesh._markSubMeshesAsAttributesDirty();
  39115. }
  39116. };
  39117. /**
  39118. * Load the geometry if it was flagged as delay loaded
  39119. * @param scene defines the hosting scene
  39120. * @param onLoaded defines a callback called when the geometry is loaded
  39121. */
  39122. Geometry.prototype.load = function (scene, onLoaded) {
  39123. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  39124. return;
  39125. }
  39126. if (this.isReady()) {
  39127. if (onLoaded) {
  39128. onLoaded();
  39129. }
  39130. return;
  39131. }
  39132. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  39133. this._queueLoad(scene, onLoaded);
  39134. };
  39135. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  39136. var _this = this;
  39137. if (!this.delayLoadingFile) {
  39138. return;
  39139. }
  39140. scene._addPendingData(this);
  39141. scene._loadFile(this.delayLoadingFile, function (data) {
  39142. if (!_this._delayLoadingFunction) {
  39143. return;
  39144. }
  39145. _this._delayLoadingFunction(JSON.parse(data), _this);
  39146. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39147. _this._delayInfo = [];
  39148. scene._removePendingData(_this);
  39149. var meshes = _this._meshes;
  39150. var numOfMeshes = meshes.length;
  39151. for (var index = 0; index < numOfMeshes; index++) {
  39152. _this._applyToMesh(meshes[index]);
  39153. }
  39154. if (onLoaded) {
  39155. onLoaded();
  39156. }
  39157. }, undefined, true);
  39158. };
  39159. /**
  39160. * Invert the geometry to move from a right handed system to a left handed one.
  39161. */
  39162. Geometry.prototype.toLeftHanded = function () {
  39163. // Flip faces
  39164. var tIndices = this.getIndices(false);
  39165. if (tIndices != null && tIndices.length > 0) {
  39166. for (var i = 0; i < tIndices.length; i += 3) {
  39167. var tTemp = tIndices[i + 0];
  39168. tIndices[i + 0] = tIndices[i + 2];
  39169. tIndices[i + 2] = tTemp;
  39170. }
  39171. this.setIndices(tIndices);
  39172. }
  39173. // Negate position.z
  39174. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39175. if (tPositions != null && tPositions.length > 0) {
  39176. for (var i = 0; i < tPositions.length; i += 3) {
  39177. tPositions[i + 2] = -tPositions[i + 2];
  39178. }
  39179. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39180. }
  39181. // Negate normal.z
  39182. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39183. if (tNormals != null && tNormals.length > 0) {
  39184. for (var i = 0; i < tNormals.length; i += 3) {
  39185. tNormals[i + 2] = -tNormals[i + 2];
  39186. }
  39187. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39188. }
  39189. };
  39190. // Cache
  39191. /** @hidden */
  39192. Geometry.prototype._resetPointsArrayCache = function () {
  39193. this._positions = null;
  39194. };
  39195. /** @hidden */
  39196. Geometry.prototype._generatePointsArray = function () {
  39197. if (this._positions)
  39198. return true;
  39199. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39200. if (!data || data.length === 0) {
  39201. return false;
  39202. }
  39203. this._positions = [];
  39204. for (var index = 0; index < data.length; index += 3) {
  39205. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  39206. }
  39207. return true;
  39208. };
  39209. /**
  39210. * Gets a value indicating if the geometry is disposed
  39211. * @returns true if the geometry was disposed
  39212. */
  39213. Geometry.prototype.isDisposed = function () {
  39214. return this._isDisposed;
  39215. };
  39216. Geometry.prototype._disposeVertexArrayObjects = function () {
  39217. if (this._vertexArrayObjects) {
  39218. for (var kind in this._vertexArrayObjects) {
  39219. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39220. }
  39221. this._vertexArrayObjects = {};
  39222. }
  39223. };
  39224. /**
  39225. * Free all associated resources
  39226. */
  39227. Geometry.prototype.dispose = function () {
  39228. var meshes = this._meshes;
  39229. var numOfMeshes = meshes.length;
  39230. var index;
  39231. for (index = 0; index < numOfMeshes; index++) {
  39232. this.releaseForMesh(meshes[index]);
  39233. }
  39234. this._meshes = [];
  39235. this._disposeVertexArrayObjects();
  39236. for (var kind in this._vertexBuffers) {
  39237. this._vertexBuffers[kind].dispose();
  39238. }
  39239. this._vertexBuffers = {};
  39240. this._totalVertices = 0;
  39241. if (this._indexBuffer) {
  39242. this._engine._releaseBuffer(this._indexBuffer);
  39243. }
  39244. this._indexBuffer = null;
  39245. this._indices = [];
  39246. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39247. this.delayLoadingFile = null;
  39248. this._delayLoadingFunction = null;
  39249. this._delayInfo = [];
  39250. this._boundingInfo = null;
  39251. this._scene.removeGeometry(this);
  39252. this._isDisposed = true;
  39253. };
  39254. /**
  39255. * Clone the current geometry into a new geometry
  39256. * @param id defines the unique ID of the new geometry
  39257. * @returns a new geometry object
  39258. */
  39259. Geometry.prototype.copy = function (id) {
  39260. var vertexData = new BABYLON.VertexData();
  39261. vertexData.indices = [];
  39262. var indices = this.getIndices();
  39263. if (indices) {
  39264. for (var index = 0; index < indices.length; index++) {
  39265. vertexData.indices.push(indices[index]);
  39266. }
  39267. }
  39268. var updatable = false;
  39269. var stopChecking = false;
  39270. var kind;
  39271. for (kind in this._vertexBuffers) {
  39272. // using slice() to make a copy of the array and not just reference it
  39273. var data = this.getVerticesData(kind);
  39274. if (data instanceof Float32Array) {
  39275. vertexData.set(new Float32Array(data), kind);
  39276. }
  39277. else {
  39278. vertexData.set(data.slice(0), kind);
  39279. }
  39280. if (!stopChecking) {
  39281. var vb = this.getVertexBuffer(kind);
  39282. if (vb) {
  39283. updatable = vb.isUpdatable();
  39284. stopChecking = !updatable;
  39285. }
  39286. }
  39287. }
  39288. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39289. geometry.delayLoadState = this.delayLoadState;
  39290. geometry.delayLoadingFile = this.delayLoadingFile;
  39291. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39292. for (kind in this._delayInfo) {
  39293. geometry._delayInfo = geometry._delayInfo || [];
  39294. geometry._delayInfo.push(kind);
  39295. }
  39296. // Bounding info
  39297. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39298. return geometry;
  39299. };
  39300. /**
  39301. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39302. * @return a JSON representation of the current geometry data (without the vertices data)
  39303. */
  39304. Geometry.prototype.serialize = function () {
  39305. var serializationObject = {};
  39306. serializationObject.id = this.id;
  39307. serializationObject.updatable = this._updatable;
  39308. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39309. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39310. }
  39311. return serializationObject;
  39312. };
  39313. Geometry.prototype.toNumberArray = function (origin) {
  39314. if (Array.isArray(origin)) {
  39315. return origin;
  39316. }
  39317. else {
  39318. return Array.prototype.slice.call(origin);
  39319. }
  39320. };
  39321. /**
  39322. * Serialize all vertices data into a JSON oject
  39323. * @returns a JSON representation of the current geometry data
  39324. */
  39325. Geometry.prototype.serializeVerticeData = function () {
  39326. var serializationObject = this.serialize();
  39327. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39328. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39329. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39330. serializationObject.positions._updatable = true;
  39331. }
  39332. }
  39333. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39334. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39335. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39336. serializationObject.normals._updatable = true;
  39337. }
  39338. }
  39339. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39340. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39341. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39342. serializationObject.tangets._updatable = true;
  39343. }
  39344. }
  39345. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39346. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39347. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39348. serializationObject.uvs._updatable = true;
  39349. }
  39350. }
  39351. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39352. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39353. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39354. serializationObject.uv2s._updatable = true;
  39355. }
  39356. }
  39357. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39358. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39359. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39360. serializationObject.uv3s._updatable = true;
  39361. }
  39362. }
  39363. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39364. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39365. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39366. serializationObject.uv4s._updatable = true;
  39367. }
  39368. }
  39369. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39370. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39371. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39372. serializationObject.uv5s._updatable = true;
  39373. }
  39374. }
  39375. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39376. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39377. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39378. serializationObject.uv6s._updatable = true;
  39379. }
  39380. }
  39381. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39382. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39383. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39384. serializationObject.colors._updatable = true;
  39385. }
  39386. }
  39387. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39388. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39389. serializationObject.matricesIndices._isExpanded = true;
  39390. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39391. serializationObject.matricesIndices._updatable = true;
  39392. }
  39393. }
  39394. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39395. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39396. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39397. serializationObject.matricesWeights._updatable = true;
  39398. }
  39399. }
  39400. serializationObject.indices = this.toNumberArray(this.getIndices());
  39401. return serializationObject;
  39402. };
  39403. // Statics
  39404. /**
  39405. * Extracts a clone of a mesh geometry
  39406. * @param mesh defines the source mesh
  39407. * @param id defines the unique ID of the new geometry object
  39408. * @returns the new geometry object
  39409. */
  39410. Geometry.ExtractFromMesh = function (mesh, id) {
  39411. var geometry = mesh._geometry;
  39412. if (!geometry) {
  39413. return null;
  39414. }
  39415. return geometry.copy(id);
  39416. };
  39417. /**
  39418. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39419. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39420. * Be aware Math.random() could cause collisions, but:
  39421. * "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"
  39422. * @returns a string containing a new GUID
  39423. */
  39424. Geometry.RandomId = function () {
  39425. return BABYLON.Tools.RandomId();
  39426. };
  39427. /** @hidden */
  39428. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39429. var scene = mesh.getScene();
  39430. // Geometry
  39431. var geometryId = parsedGeometry.geometryId;
  39432. if (geometryId) {
  39433. var geometry = scene.getGeometryByID(geometryId);
  39434. if (geometry) {
  39435. geometry.applyToMesh(mesh);
  39436. }
  39437. }
  39438. else if (parsedGeometry instanceof ArrayBuffer) {
  39439. var binaryInfo = mesh._binaryInfo;
  39440. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39441. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39442. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39443. }
  39444. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39445. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39446. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39447. }
  39448. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39449. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39450. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39451. }
  39452. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39453. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39454. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39455. }
  39456. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39457. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39458. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39459. }
  39460. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39461. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39462. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39463. }
  39464. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39465. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39466. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39467. }
  39468. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39469. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39470. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39471. }
  39472. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39473. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39474. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39475. }
  39476. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39477. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39478. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39479. }
  39480. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39481. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39482. var floatIndices = [];
  39483. for (var i = 0; i < matricesIndicesData.length; i++) {
  39484. var index = matricesIndicesData[i];
  39485. floatIndices.push(index & 0x000000FF);
  39486. floatIndices.push((index & 0x0000FF00) >> 8);
  39487. floatIndices.push((index & 0x00FF0000) >> 16);
  39488. floatIndices.push(index >> 24);
  39489. }
  39490. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  39491. }
  39492. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  39493. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  39494. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  39495. }
  39496. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  39497. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  39498. mesh.setIndices(indicesData, null);
  39499. }
  39500. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  39501. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  39502. mesh.subMeshes = [];
  39503. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  39504. var materialIndex = subMeshesData[(i * 5) + 0];
  39505. var verticesStart = subMeshesData[(i * 5) + 1];
  39506. var verticesCount = subMeshesData[(i * 5) + 2];
  39507. var indexStart = subMeshesData[(i * 5) + 3];
  39508. var indexCount = subMeshesData[(i * 5) + 4];
  39509. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  39510. }
  39511. }
  39512. }
  39513. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  39514. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  39515. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  39516. if (parsedGeometry.tangents) {
  39517. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  39518. }
  39519. if (parsedGeometry.uvs) {
  39520. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  39521. }
  39522. if (parsedGeometry.uvs2) {
  39523. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  39524. }
  39525. if (parsedGeometry.uvs3) {
  39526. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  39527. }
  39528. if (parsedGeometry.uvs4) {
  39529. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  39530. }
  39531. if (parsedGeometry.uvs5) {
  39532. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  39533. }
  39534. if (parsedGeometry.uvs6) {
  39535. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  39536. }
  39537. if (parsedGeometry.colors) {
  39538. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  39539. }
  39540. if (parsedGeometry.matricesIndices) {
  39541. if (!parsedGeometry.matricesIndices._isExpanded) {
  39542. var floatIndices = [];
  39543. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  39544. var matricesIndex = parsedGeometry.matricesIndices[i];
  39545. floatIndices.push(matricesIndex & 0x000000FF);
  39546. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39547. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39548. floatIndices.push(matricesIndex >> 24);
  39549. }
  39550. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  39551. }
  39552. else {
  39553. delete parsedGeometry.matricesIndices._isExpanded;
  39554. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  39555. }
  39556. }
  39557. if (parsedGeometry.matricesIndicesExtra) {
  39558. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  39559. var floatIndices = [];
  39560. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  39561. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  39562. floatIndices.push(matricesIndex & 0x000000FF);
  39563. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39564. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39565. floatIndices.push(matricesIndex >> 24);
  39566. }
  39567. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  39568. }
  39569. else {
  39570. delete parsedGeometry.matricesIndices._isExpanded;
  39571. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  39572. }
  39573. }
  39574. if (parsedGeometry.matricesWeights) {
  39575. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  39576. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  39577. }
  39578. if (parsedGeometry.matricesWeightsExtra) {
  39579. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  39580. }
  39581. mesh.setIndices(parsedGeometry.indices, null);
  39582. }
  39583. // SubMeshes
  39584. if (parsedGeometry.subMeshes) {
  39585. mesh.subMeshes = [];
  39586. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  39587. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  39588. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  39589. }
  39590. }
  39591. // Flat shading
  39592. if (mesh._shouldGenerateFlatShading) {
  39593. mesh.convertToFlatShadedMesh();
  39594. delete mesh._shouldGenerateFlatShading;
  39595. }
  39596. // Update
  39597. mesh.computeWorldMatrix(true);
  39598. scene.onMeshImportedObservable.notifyObservers(mesh);
  39599. };
  39600. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  39601. var epsilon = 1e-3;
  39602. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  39603. return;
  39604. }
  39605. var noInfluenceBoneIndex = 0.0;
  39606. if (parsedGeometry.skeletonId > -1) {
  39607. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  39608. if (!skeleton) {
  39609. return;
  39610. }
  39611. noInfluenceBoneIndex = skeleton.bones.length;
  39612. }
  39613. else {
  39614. return;
  39615. }
  39616. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  39617. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39618. var matricesWeights = parsedGeometry.matricesWeights;
  39619. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  39620. var influencers = parsedGeometry.numBoneInfluencer;
  39621. var size = matricesWeights.length;
  39622. for (var i = 0; i < size; i += 4) {
  39623. var weight = 0.0;
  39624. var firstZeroWeight = -1;
  39625. for (var j = 0; j < 4; j++) {
  39626. var w = matricesWeights[i + j];
  39627. weight += w;
  39628. if (w < epsilon && firstZeroWeight < 0) {
  39629. firstZeroWeight = j;
  39630. }
  39631. }
  39632. if (matricesWeightsExtra) {
  39633. for (var j = 0; j < 4; j++) {
  39634. var w = matricesWeightsExtra[i + j];
  39635. weight += w;
  39636. if (w < epsilon && firstZeroWeight < 0) {
  39637. firstZeroWeight = j + 4;
  39638. }
  39639. }
  39640. }
  39641. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  39642. firstZeroWeight = influencers - 1;
  39643. }
  39644. if (weight > epsilon) {
  39645. var mweight = 1.0 / weight;
  39646. for (var j = 0; j < 4; j++) {
  39647. matricesWeights[i + j] *= mweight;
  39648. }
  39649. if (matricesWeightsExtra) {
  39650. for (var j = 0; j < 4; j++) {
  39651. matricesWeightsExtra[i + j] *= mweight;
  39652. }
  39653. }
  39654. }
  39655. else {
  39656. if (firstZeroWeight >= 4) {
  39657. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  39658. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  39659. }
  39660. else {
  39661. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  39662. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  39663. }
  39664. }
  39665. }
  39666. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  39667. if (parsedGeometry.matricesWeightsExtra) {
  39668. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  39669. }
  39670. };
  39671. /**
  39672. * Create a new geometry from persisted data (Using .babylon file format)
  39673. * @param parsedVertexData defines the persisted data
  39674. * @param scene defines the hosting scene
  39675. * @param rootUrl defines the root url to use to load assets (like delayed data)
  39676. * @returns the new geometry object
  39677. */
  39678. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  39679. if (scene.getGeometryByID(parsedVertexData.id)) {
  39680. return null; // null since geometry could be something else than a box...
  39681. }
  39682. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  39683. if (BABYLON.Tags) {
  39684. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  39685. }
  39686. if (parsedVertexData.delayLoadingFile) {
  39687. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  39688. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  39689. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  39690. geometry._delayInfo = [];
  39691. if (parsedVertexData.hasUVs) {
  39692. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  39693. }
  39694. if (parsedVertexData.hasUVs2) {
  39695. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  39696. }
  39697. if (parsedVertexData.hasUVs3) {
  39698. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  39699. }
  39700. if (parsedVertexData.hasUVs4) {
  39701. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  39702. }
  39703. if (parsedVertexData.hasUVs5) {
  39704. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  39705. }
  39706. if (parsedVertexData.hasUVs6) {
  39707. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  39708. }
  39709. if (parsedVertexData.hasColors) {
  39710. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  39711. }
  39712. if (parsedVertexData.hasMatricesIndices) {
  39713. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39714. }
  39715. if (parsedVertexData.hasMatricesWeights) {
  39716. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39717. }
  39718. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  39719. }
  39720. else {
  39721. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  39722. }
  39723. scene.pushGeometry(geometry, true);
  39724. return geometry;
  39725. };
  39726. return Geometry;
  39727. }());
  39728. BABYLON.Geometry = Geometry;
  39729. // Primitives
  39730. /// Abstract class
  39731. /**
  39732. * Abstract class used to provide common services for all typed geometries
  39733. * @hidden
  39734. */
  39735. var _PrimitiveGeometry = /** @class */ (function (_super) {
  39736. __extends(_PrimitiveGeometry, _super);
  39737. /**
  39738. * Creates a new typed geometry
  39739. * @param id defines the unique ID of the geometry
  39740. * @param scene defines the hosting scene
  39741. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39742. * @param mesh defines the hosting mesh (can be null)
  39743. */
  39744. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  39745. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  39746. if (mesh === void 0) { mesh = null; }
  39747. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  39748. _this._canBeRegenerated = _canBeRegenerated;
  39749. _this._beingRegenerated = true;
  39750. _this.regenerate();
  39751. _this._beingRegenerated = false;
  39752. return _this;
  39753. }
  39754. /**
  39755. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  39756. * @returns true if the geometry can be regenerated
  39757. */
  39758. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  39759. return this._canBeRegenerated;
  39760. };
  39761. /**
  39762. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  39763. */
  39764. _PrimitiveGeometry.prototype.regenerate = function () {
  39765. if (!this._canBeRegenerated) {
  39766. return;
  39767. }
  39768. this._beingRegenerated = true;
  39769. this.setAllVerticesData(this._regenerateVertexData(), false);
  39770. this._beingRegenerated = false;
  39771. };
  39772. /**
  39773. * Clone the geometry
  39774. * @param id defines the unique ID of the new geometry
  39775. * @returns the new geometry
  39776. */
  39777. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  39778. return _super.prototype.copy.call(this, id);
  39779. };
  39780. // overrides
  39781. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39782. if (!this._beingRegenerated) {
  39783. return;
  39784. }
  39785. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  39786. };
  39787. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  39788. if (!this._beingRegenerated) {
  39789. return;
  39790. }
  39791. _super.prototype.setVerticesData.call(this, kind, data, false);
  39792. };
  39793. // to override
  39794. /** @hidden */
  39795. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  39796. throw new Error("Abstract method");
  39797. };
  39798. _PrimitiveGeometry.prototype.copy = function (id) {
  39799. throw new Error("Must be overriden in sub-classes.");
  39800. };
  39801. _PrimitiveGeometry.prototype.serialize = function () {
  39802. var serializationObject = _super.prototype.serialize.call(this);
  39803. serializationObject.canBeRegenerated = this.canBeRegenerated();
  39804. return serializationObject;
  39805. };
  39806. return _PrimitiveGeometry;
  39807. }(Geometry));
  39808. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  39809. /**
  39810. * Creates a ribbon geometry
  39811. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  39812. */
  39813. var RibbonGeometry = /** @class */ (function (_super) {
  39814. __extends(RibbonGeometry, _super);
  39815. /**
  39816. * Creates a ribbon geometry
  39817. * @param id defines the unique ID of the geometry
  39818. * @param scene defines the hosting scene
  39819. * @param pathArray defines the array of paths to use
  39820. * @param closeArray defines if the last path and the first path must be joined
  39821. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  39822. * @param offset defines the offset between points
  39823. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39824. * @param mesh defines the hosting mesh (can be null)
  39825. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39826. */
  39827. function RibbonGeometry(id, scene,
  39828. /**
  39829. * Defines the array of paths to use
  39830. */
  39831. pathArray,
  39832. /**
  39833. * Defines if the last and first points of each path in your pathArray must be joined
  39834. */
  39835. closeArray,
  39836. /**
  39837. * Defines if the last and first points of each path in your pathArray must be joined
  39838. */
  39839. closePath,
  39840. /**
  39841. * Defines the offset between points
  39842. */
  39843. offset, canBeRegenerated, mesh,
  39844. /**
  39845. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39846. */
  39847. side) {
  39848. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39849. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39850. _this.pathArray = pathArray;
  39851. _this.closeArray = closeArray;
  39852. _this.closePath = closePath;
  39853. _this.offset = offset;
  39854. _this.side = side;
  39855. return _this;
  39856. }
  39857. /** @hidden */
  39858. RibbonGeometry.prototype._regenerateVertexData = function () {
  39859. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  39860. };
  39861. RibbonGeometry.prototype.copy = function (id) {
  39862. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  39863. };
  39864. return RibbonGeometry;
  39865. }(_PrimitiveGeometry));
  39866. BABYLON.RibbonGeometry = RibbonGeometry;
  39867. /**
  39868. * Creates a box geometry
  39869. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  39870. */
  39871. var BoxGeometry = /** @class */ (function (_super) {
  39872. __extends(BoxGeometry, _super);
  39873. /**
  39874. * Creates a box geometry
  39875. * @param id defines the unique ID of the geometry
  39876. * @param scene defines the hosting scene
  39877. * @param size defines the zise of the box (width, height and depth are the same)
  39878. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39879. * @param mesh defines the hosting mesh (can be null)
  39880. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39881. */
  39882. function BoxGeometry(id, scene,
  39883. /**
  39884. * Defines the zise of the box (width, height and depth are the same)
  39885. */
  39886. size, canBeRegenerated, mesh,
  39887. /**
  39888. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39889. */
  39890. side) {
  39891. if (mesh === void 0) { mesh = null; }
  39892. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39893. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39894. _this.size = size;
  39895. _this.side = side;
  39896. return _this;
  39897. }
  39898. /** @hidden */
  39899. BoxGeometry.prototype._regenerateVertexData = function () {
  39900. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  39901. };
  39902. BoxGeometry.prototype.copy = function (id) {
  39903. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  39904. };
  39905. BoxGeometry.prototype.serialize = function () {
  39906. var serializationObject = _super.prototype.serialize.call(this);
  39907. serializationObject.size = this.size;
  39908. return serializationObject;
  39909. };
  39910. BoxGeometry.Parse = function (parsedBox, scene) {
  39911. if (scene.getGeometryByID(parsedBox.id)) {
  39912. return null; // null since geometry could be something else than a box...
  39913. }
  39914. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  39915. if (BABYLON.Tags) {
  39916. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  39917. }
  39918. scene.pushGeometry(box, true);
  39919. return box;
  39920. };
  39921. return BoxGeometry;
  39922. }(_PrimitiveGeometry));
  39923. BABYLON.BoxGeometry = BoxGeometry;
  39924. /**
  39925. * Creates a sphere geometry
  39926. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  39927. */
  39928. var SphereGeometry = /** @class */ (function (_super) {
  39929. __extends(SphereGeometry, _super);
  39930. /**
  39931. * Create a new sphere geometry
  39932. * @param id defines the unique ID of the geometry
  39933. * @param scene defines the hosting scene
  39934. * @param segments defines the number of segments to use to create the sphere
  39935. * @param diameter defines the diameter of the sphere
  39936. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39937. * @param mesh defines the hosting mesh (can be null)
  39938. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39939. */
  39940. function SphereGeometry(id, scene,
  39941. /**
  39942. * Defines the number of segments to use to create the sphere
  39943. */
  39944. segments,
  39945. /**
  39946. * Defines the diameter of the sphere
  39947. */
  39948. diameter, canBeRegenerated, mesh,
  39949. /**
  39950. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39951. */
  39952. side) {
  39953. if (mesh === void 0) { mesh = null; }
  39954. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39955. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39956. _this.segments = segments;
  39957. _this.diameter = diameter;
  39958. _this.side = side;
  39959. return _this;
  39960. }
  39961. /** @hidden */
  39962. SphereGeometry.prototype._regenerateVertexData = function () {
  39963. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  39964. };
  39965. SphereGeometry.prototype.copy = function (id) {
  39966. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  39967. };
  39968. SphereGeometry.prototype.serialize = function () {
  39969. var serializationObject = _super.prototype.serialize.call(this);
  39970. serializationObject.segments = this.segments;
  39971. serializationObject.diameter = this.diameter;
  39972. return serializationObject;
  39973. };
  39974. SphereGeometry.Parse = function (parsedSphere, scene) {
  39975. if (scene.getGeometryByID(parsedSphere.id)) {
  39976. return null; // null since geometry could be something else than a sphere...
  39977. }
  39978. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  39979. if (BABYLON.Tags) {
  39980. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  39981. }
  39982. scene.pushGeometry(sphere, true);
  39983. return sphere;
  39984. };
  39985. return SphereGeometry;
  39986. }(_PrimitiveGeometry));
  39987. BABYLON.SphereGeometry = SphereGeometry;
  39988. /**
  39989. * Creates a disc geometry
  39990. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  39991. */
  39992. var DiscGeometry = /** @class */ (function (_super) {
  39993. __extends(DiscGeometry, _super);
  39994. /**
  39995. * Creates a new disc geometry
  39996. * @param id defines the unique ID of the geometry
  39997. * @param scene defines the hosting scene
  39998. * @param radius defines the radius of the disc
  39999. * @param tessellation defines the tesselation factor to apply to the disc
  40000. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40001. * @param mesh defines the hosting mesh (can be null)
  40002. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40003. */
  40004. function DiscGeometry(id, scene,
  40005. /**
  40006. * Defines the radius of the disc
  40007. */
  40008. radius,
  40009. /**
  40010. * Defines the tesselation factor to apply to the disc
  40011. */
  40012. tessellation, canBeRegenerated, mesh,
  40013. /**
  40014. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40015. */
  40016. side) {
  40017. if (mesh === void 0) { mesh = null; }
  40018. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40019. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40020. _this.radius = radius;
  40021. _this.tessellation = tessellation;
  40022. _this.side = side;
  40023. return _this;
  40024. }
  40025. /** @hidden */
  40026. DiscGeometry.prototype._regenerateVertexData = function () {
  40027. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  40028. };
  40029. DiscGeometry.prototype.copy = function (id) {
  40030. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  40031. };
  40032. return DiscGeometry;
  40033. }(_PrimitiveGeometry));
  40034. BABYLON.DiscGeometry = DiscGeometry;
  40035. /**
  40036. * Creates a new cylinder geometry
  40037. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  40038. */
  40039. var CylinderGeometry = /** @class */ (function (_super) {
  40040. __extends(CylinderGeometry, _super);
  40041. /**
  40042. * Creates a new cylinder geometry
  40043. * @param id defines the unique ID of the geometry
  40044. * @param scene defines the hosting scene
  40045. * @param height defines the height of the cylinder
  40046. * @param diameterTop defines the diameter of the cylinder's top cap
  40047. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  40048. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  40049. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  40050. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40051. * @param mesh defines the hosting mesh (can be null)
  40052. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40053. */
  40054. function CylinderGeometry(id, scene,
  40055. /**
  40056. * Defines the height of the cylinder
  40057. */
  40058. height,
  40059. /**
  40060. * Defines the diameter of the cylinder's top cap
  40061. */
  40062. diameterTop,
  40063. /**
  40064. * Defines the diameter of the cylinder's bottom cap
  40065. */
  40066. diameterBottom,
  40067. /**
  40068. * Defines the tessellation factor to apply to the cylinder
  40069. */
  40070. tessellation,
  40071. /**
  40072. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  40073. */
  40074. subdivisions, canBeRegenerated, mesh,
  40075. /**
  40076. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40077. */
  40078. side) {
  40079. if (subdivisions === void 0) { subdivisions = 1; }
  40080. if (mesh === void 0) { mesh = null; }
  40081. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40082. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40083. _this.height = height;
  40084. _this.diameterTop = diameterTop;
  40085. _this.diameterBottom = diameterBottom;
  40086. _this.tessellation = tessellation;
  40087. _this.subdivisions = subdivisions;
  40088. _this.side = side;
  40089. return _this;
  40090. }
  40091. /** @hidden */
  40092. CylinderGeometry.prototype._regenerateVertexData = function () {
  40093. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  40094. };
  40095. CylinderGeometry.prototype.copy = function (id) {
  40096. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  40097. };
  40098. CylinderGeometry.prototype.serialize = function () {
  40099. var serializationObject = _super.prototype.serialize.call(this);
  40100. serializationObject.height = this.height;
  40101. serializationObject.diameterTop = this.diameterTop;
  40102. serializationObject.diameterBottom = this.diameterBottom;
  40103. serializationObject.tessellation = this.tessellation;
  40104. return serializationObject;
  40105. };
  40106. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  40107. if (scene.getGeometryByID(parsedCylinder.id)) {
  40108. return null; // null since geometry could be something else than a cylinder...
  40109. }
  40110. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  40111. if (BABYLON.Tags) {
  40112. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  40113. }
  40114. scene.pushGeometry(cylinder, true);
  40115. return cylinder;
  40116. };
  40117. return CylinderGeometry;
  40118. }(_PrimitiveGeometry));
  40119. BABYLON.CylinderGeometry = CylinderGeometry;
  40120. /**
  40121. * Creates a new torus geometry
  40122. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  40123. */
  40124. var TorusGeometry = /** @class */ (function (_super) {
  40125. __extends(TorusGeometry, _super);
  40126. /**
  40127. * Creates a new torus geometry
  40128. * @param id defines the unique ID of the geometry
  40129. * @param scene defines the hosting scene
  40130. * @param diameter defines the diameter of the torus
  40131. * @param thickness defines the thickness of the torus (ie. internal diameter)
  40132. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  40133. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40134. * @param mesh defines the hosting mesh (can be null)
  40135. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40136. */
  40137. function TorusGeometry(id, scene,
  40138. /**
  40139. * Defines the diameter of the torus
  40140. */
  40141. diameter,
  40142. /**
  40143. * Defines the thickness of the torus (ie. internal diameter)
  40144. */
  40145. thickness,
  40146. /**
  40147. * Defines the tesselation factor to apply to the torus
  40148. */
  40149. tessellation, canBeRegenerated, mesh,
  40150. /**
  40151. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40152. */
  40153. side) {
  40154. if (mesh === void 0) { mesh = null; }
  40155. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40156. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40157. _this.diameter = diameter;
  40158. _this.thickness = thickness;
  40159. _this.tessellation = tessellation;
  40160. _this.side = side;
  40161. return _this;
  40162. }
  40163. /** @hidden */
  40164. TorusGeometry.prototype._regenerateVertexData = function () {
  40165. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  40166. };
  40167. TorusGeometry.prototype.copy = function (id) {
  40168. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  40169. };
  40170. TorusGeometry.prototype.serialize = function () {
  40171. var serializationObject = _super.prototype.serialize.call(this);
  40172. serializationObject.diameter = this.diameter;
  40173. serializationObject.thickness = this.thickness;
  40174. serializationObject.tessellation = this.tessellation;
  40175. return serializationObject;
  40176. };
  40177. TorusGeometry.Parse = function (parsedTorus, scene) {
  40178. if (scene.getGeometryByID(parsedTorus.id)) {
  40179. return null; // null since geometry could be something else than a torus...
  40180. }
  40181. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40182. if (BABYLON.Tags) {
  40183. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40184. }
  40185. scene.pushGeometry(torus, true);
  40186. return torus;
  40187. };
  40188. return TorusGeometry;
  40189. }(_PrimitiveGeometry));
  40190. BABYLON.TorusGeometry = TorusGeometry;
  40191. /**
  40192. * Creates a new ground geometry
  40193. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  40194. */
  40195. var GroundGeometry = /** @class */ (function (_super) {
  40196. __extends(GroundGeometry, _super);
  40197. /**
  40198. * Creates a new ground geometry
  40199. * @param id defines the unique ID of the geometry
  40200. * @param scene defines the hosting scene
  40201. * @param width defines the width of the ground
  40202. * @param height defines the height of the ground
  40203. * @param subdivisions defines the subdivisions to apply to the ground
  40204. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40205. * @param mesh defines the hosting mesh (can be null)
  40206. */
  40207. function GroundGeometry(id, scene,
  40208. /**
  40209. * Defines the width of the ground
  40210. */
  40211. width,
  40212. /**
  40213. * Defines the height of the ground
  40214. */
  40215. height,
  40216. /**
  40217. * Defines the subdivisions to apply to the ground
  40218. */
  40219. subdivisions, canBeRegenerated, mesh) {
  40220. if (mesh === void 0) { mesh = null; }
  40221. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40222. _this.width = width;
  40223. _this.height = height;
  40224. _this.subdivisions = subdivisions;
  40225. return _this;
  40226. }
  40227. /** @hidden */
  40228. GroundGeometry.prototype._regenerateVertexData = function () {
  40229. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40230. };
  40231. GroundGeometry.prototype.copy = function (id) {
  40232. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40233. };
  40234. GroundGeometry.prototype.serialize = function () {
  40235. var serializationObject = _super.prototype.serialize.call(this);
  40236. serializationObject.width = this.width;
  40237. serializationObject.height = this.height;
  40238. serializationObject.subdivisions = this.subdivisions;
  40239. return serializationObject;
  40240. };
  40241. GroundGeometry.Parse = function (parsedGround, scene) {
  40242. if (scene.getGeometryByID(parsedGround.id)) {
  40243. return null; // null since geometry could be something else than a ground...
  40244. }
  40245. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40246. if (BABYLON.Tags) {
  40247. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40248. }
  40249. scene.pushGeometry(ground, true);
  40250. return ground;
  40251. };
  40252. return GroundGeometry;
  40253. }(_PrimitiveGeometry));
  40254. BABYLON.GroundGeometry = GroundGeometry;
  40255. /**
  40256. * Creates a tiled ground geometry
  40257. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40258. */
  40259. var TiledGroundGeometry = /** @class */ (function (_super) {
  40260. __extends(TiledGroundGeometry, _super);
  40261. /**
  40262. * Creates a tiled ground geometry
  40263. * @param id defines the unique ID of the geometry
  40264. * @param scene defines the hosting scene
  40265. * @param xmin defines the minimum value on X axis
  40266. * @param zmin defines the minimum value on Z axis
  40267. * @param xmax defines the maximum value on X axis
  40268. * @param zmax defines the maximum value on Z axis
  40269. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40270. * @param precision defines the precision to use when computing the tiles
  40271. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40272. * @param mesh defines the hosting mesh (can be null)
  40273. */
  40274. function TiledGroundGeometry(id, scene,
  40275. /**
  40276. * Defines the minimum value on X axis
  40277. */
  40278. xmin,
  40279. /**
  40280. * Defines the minimum value on Z axis
  40281. */
  40282. zmin,
  40283. /**
  40284. * Defines the maximum value on X axis
  40285. */
  40286. xmax,
  40287. /**
  40288. * Defines the maximum value on Z axis
  40289. */
  40290. zmax,
  40291. /**
  40292. * Defines the subdivisions to apply to the ground
  40293. */
  40294. subdivisions,
  40295. /**
  40296. * Defines the precision to use when computing the tiles
  40297. */
  40298. precision, canBeRegenerated, mesh) {
  40299. if (mesh === void 0) { mesh = null; }
  40300. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40301. _this.xmin = xmin;
  40302. _this.zmin = zmin;
  40303. _this.xmax = xmax;
  40304. _this.zmax = zmax;
  40305. _this.subdivisions = subdivisions;
  40306. _this.precision = precision;
  40307. return _this;
  40308. }
  40309. /** @hidden */
  40310. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40311. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40312. };
  40313. TiledGroundGeometry.prototype.copy = function (id) {
  40314. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40315. };
  40316. return TiledGroundGeometry;
  40317. }(_PrimitiveGeometry));
  40318. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40319. /**
  40320. * Creates a plane geometry
  40321. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40322. */
  40323. var PlaneGeometry = /** @class */ (function (_super) {
  40324. __extends(PlaneGeometry, _super);
  40325. /**
  40326. * Creates a plane geometry
  40327. * @param id defines the unique ID of the geometry
  40328. * @param scene defines the hosting scene
  40329. * @param size defines the size of the plane (width === height)
  40330. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40331. * @param mesh defines the hosting mesh (can be null)
  40332. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40333. */
  40334. function PlaneGeometry(id, scene,
  40335. /**
  40336. * Defines the size of the plane (width === height)
  40337. */
  40338. size, canBeRegenerated, mesh,
  40339. /**
  40340. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40341. */
  40342. side) {
  40343. if (mesh === void 0) { mesh = null; }
  40344. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40345. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40346. _this.size = size;
  40347. _this.side = side;
  40348. return _this;
  40349. }
  40350. /** @hidden */
  40351. PlaneGeometry.prototype._regenerateVertexData = function () {
  40352. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40353. };
  40354. PlaneGeometry.prototype.copy = function (id) {
  40355. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40356. };
  40357. PlaneGeometry.prototype.serialize = function () {
  40358. var serializationObject = _super.prototype.serialize.call(this);
  40359. serializationObject.size = this.size;
  40360. return serializationObject;
  40361. };
  40362. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40363. if (scene.getGeometryByID(parsedPlane.id)) {
  40364. return null; // null since geometry could be something else than a ground...
  40365. }
  40366. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40367. if (BABYLON.Tags) {
  40368. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40369. }
  40370. scene.pushGeometry(plane, true);
  40371. return plane;
  40372. };
  40373. return PlaneGeometry;
  40374. }(_PrimitiveGeometry));
  40375. BABYLON.PlaneGeometry = PlaneGeometry;
  40376. /**
  40377. * Creates a torus knot geometry
  40378. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40379. */
  40380. var TorusKnotGeometry = /** @class */ (function (_super) {
  40381. __extends(TorusKnotGeometry, _super);
  40382. /**
  40383. * Creates a torus knot geometry
  40384. * @param id defines the unique ID of the geometry
  40385. * @param scene defines the hosting scene
  40386. * @param radius defines the radius of the torus knot
  40387. * @param tube defines the thickness of the torus knot tube
  40388. * @param radialSegments defines the number of radial segments
  40389. * @param tubularSegments defines the number of tubular segments
  40390. * @param p defines the first number of windings
  40391. * @param q defines the second number of windings
  40392. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40393. * @param mesh defines the hosting mesh (can be null)
  40394. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40395. */
  40396. function TorusKnotGeometry(id, scene,
  40397. /**
  40398. * Defines the radius of the torus knot
  40399. */
  40400. radius,
  40401. /**
  40402. * Defines the thickness of the torus knot tube
  40403. */
  40404. tube,
  40405. /**
  40406. * Defines the number of radial segments
  40407. */
  40408. radialSegments,
  40409. /**
  40410. * Defines the number of tubular segments
  40411. */
  40412. tubularSegments,
  40413. /**
  40414. * Defines the first number of windings
  40415. */
  40416. p,
  40417. /**
  40418. * Defines the second number of windings
  40419. */
  40420. q, canBeRegenerated, mesh,
  40421. /**
  40422. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40423. */
  40424. side) {
  40425. if (mesh === void 0) { mesh = null; }
  40426. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40427. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40428. _this.radius = radius;
  40429. _this.tube = tube;
  40430. _this.radialSegments = radialSegments;
  40431. _this.tubularSegments = tubularSegments;
  40432. _this.p = p;
  40433. _this.q = q;
  40434. _this.side = side;
  40435. return _this;
  40436. }
  40437. /** @hidden */
  40438. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40439. 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 });
  40440. };
  40441. TorusKnotGeometry.prototype.copy = function (id) {
  40442. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40443. };
  40444. TorusKnotGeometry.prototype.serialize = function () {
  40445. var serializationObject = _super.prototype.serialize.call(this);
  40446. serializationObject.radius = this.radius;
  40447. serializationObject.tube = this.tube;
  40448. serializationObject.radialSegments = this.radialSegments;
  40449. serializationObject.tubularSegments = this.tubularSegments;
  40450. serializationObject.p = this.p;
  40451. serializationObject.q = this.q;
  40452. return serializationObject;
  40453. };
  40454. ;
  40455. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40456. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40457. return null; // null since geometry could be something else than a ground...
  40458. }
  40459. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40460. if (BABYLON.Tags) {
  40461. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40462. }
  40463. scene.pushGeometry(torusKnot, true);
  40464. return torusKnot;
  40465. };
  40466. return TorusKnotGeometry;
  40467. }(_PrimitiveGeometry));
  40468. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40469. //}
  40470. })(BABYLON || (BABYLON = {}));
  40471. //# sourceMappingURL=babylon.geometry.js.map
  40472. var BABYLON;
  40473. (function (BABYLON) {
  40474. /**
  40475. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  40476. */
  40477. var PerformanceMonitor = /** @class */ (function () {
  40478. /**
  40479. * constructor
  40480. * @param frameSampleSize The number of samples required to saturate the sliding window
  40481. */
  40482. function PerformanceMonitor(frameSampleSize) {
  40483. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  40484. this._enabled = true;
  40485. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  40486. }
  40487. /**
  40488. * Samples current frame
  40489. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  40490. */
  40491. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  40492. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  40493. if (!this._enabled)
  40494. return;
  40495. if (this._lastFrameTimeMs != null) {
  40496. var dt = timeMs - this._lastFrameTimeMs;
  40497. this._rollingFrameTime.add(dt);
  40498. }
  40499. this._lastFrameTimeMs = timeMs;
  40500. };
  40501. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  40502. /**
  40503. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40504. * @return Average frame time in milliseconds
  40505. */
  40506. get: function () {
  40507. return this._rollingFrameTime.average;
  40508. },
  40509. enumerable: true,
  40510. configurable: true
  40511. });
  40512. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  40513. /**
  40514. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40515. * @return Frame time variance in milliseconds squared
  40516. */
  40517. get: function () {
  40518. return this._rollingFrameTime.variance;
  40519. },
  40520. enumerable: true,
  40521. configurable: true
  40522. });
  40523. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  40524. /**
  40525. * Returns the frame time of the most recent frame
  40526. * @return Frame time in milliseconds
  40527. */
  40528. get: function () {
  40529. return this._rollingFrameTime.history(0);
  40530. },
  40531. enumerable: true,
  40532. configurable: true
  40533. });
  40534. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  40535. /**
  40536. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  40537. * @return Framerate in frames per second
  40538. */
  40539. get: function () {
  40540. return 1000.0 / this._rollingFrameTime.average;
  40541. },
  40542. enumerable: true,
  40543. configurable: true
  40544. });
  40545. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  40546. /**
  40547. * Returns the average framerate in frames per second using the most recent frame time
  40548. * @return Framerate in frames per second
  40549. */
  40550. get: function () {
  40551. var history = this._rollingFrameTime.history(0);
  40552. if (history === 0) {
  40553. return 0;
  40554. }
  40555. return 1000.0 / history;
  40556. },
  40557. enumerable: true,
  40558. configurable: true
  40559. });
  40560. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  40561. /**
  40562. * Returns true if enough samples have been taken to completely fill the sliding window
  40563. * @return true if saturated
  40564. */
  40565. get: function () {
  40566. return this._rollingFrameTime.isSaturated();
  40567. },
  40568. enumerable: true,
  40569. configurable: true
  40570. });
  40571. /**
  40572. * Enables contributions to the sliding window sample set
  40573. */
  40574. PerformanceMonitor.prototype.enable = function () {
  40575. this._enabled = true;
  40576. };
  40577. /**
  40578. * Disables contributions to the sliding window sample set
  40579. * Samples will not be interpolated over the disabled period
  40580. */
  40581. PerformanceMonitor.prototype.disable = function () {
  40582. this._enabled = false;
  40583. //clear last sample to avoid interpolating over the disabled period when next enabled
  40584. this._lastFrameTimeMs = null;
  40585. };
  40586. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  40587. /**
  40588. * Returns true if sampling is enabled
  40589. * @return true if enabled
  40590. */
  40591. get: function () {
  40592. return this._enabled;
  40593. },
  40594. enumerable: true,
  40595. configurable: true
  40596. });
  40597. /**
  40598. * Resets performance monitor
  40599. */
  40600. PerformanceMonitor.prototype.reset = function () {
  40601. //clear last sample to avoid interpolating over the disabled period when next enabled
  40602. this._lastFrameTimeMs = null;
  40603. //wipe record
  40604. this._rollingFrameTime.reset();
  40605. };
  40606. return PerformanceMonitor;
  40607. }());
  40608. BABYLON.PerformanceMonitor = PerformanceMonitor;
  40609. /**
  40610. * RollingAverage
  40611. *
  40612. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  40613. */
  40614. var RollingAverage = /** @class */ (function () {
  40615. /**
  40616. * constructor
  40617. * @param length The number of samples required to saturate the sliding window
  40618. */
  40619. function RollingAverage(length) {
  40620. this._samples = new Array(length);
  40621. this.reset();
  40622. }
  40623. /**
  40624. * Adds a sample to the sample set
  40625. * @param v The sample value
  40626. */
  40627. RollingAverage.prototype.add = function (v) {
  40628. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  40629. var delta;
  40630. //we need to check if we've already wrapped round
  40631. if (this.isSaturated()) {
  40632. //remove bottom of stack from mean
  40633. var bottomValue = this._samples[this._pos];
  40634. delta = bottomValue - this.average;
  40635. this.average -= delta / (this._sampleCount - 1);
  40636. this._m2 -= delta * (bottomValue - this.average);
  40637. }
  40638. else {
  40639. this._sampleCount++;
  40640. }
  40641. //add new value to mean
  40642. delta = v - this.average;
  40643. this.average += delta / (this._sampleCount);
  40644. this._m2 += delta * (v - this.average);
  40645. //set the new variance
  40646. this.variance = this._m2 / (this._sampleCount - 1);
  40647. this._samples[this._pos] = v;
  40648. this._pos++;
  40649. this._pos %= this._samples.length; //positive wrap around
  40650. };
  40651. /**
  40652. * Returns previously added values or null if outside of history or outside the sliding window domain
  40653. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  40654. * @return Value previously recorded with add() or null if outside of range
  40655. */
  40656. RollingAverage.prototype.history = function (i) {
  40657. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  40658. return 0;
  40659. }
  40660. var i0 = this._wrapPosition(this._pos - 1.0);
  40661. return this._samples[this._wrapPosition(i0 - i)];
  40662. };
  40663. /**
  40664. * Returns true if enough samples have been taken to completely fill the sliding window
  40665. * @return true if sample-set saturated
  40666. */
  40667. RollingAverage.prototype.isSaturated = function () {
  40668. return this._sampleCount >= this._samples.length;
  40669. };
  40670. /**
  40671. * Resets the rolling average (equivalent to 0 samples taken so far)
  40672. */
  40673. RollingAverage.prototype.reset = function () {
  40674. this.average = 0;
  40675. this.variance = 0;
  40676. this._sampleCount = 0;
  40677. this._pos = 0;
  40678. this._m2 = 0;
  40679. };
  40680. /**
  40681. * Wraps a value around the sample range boundaries
  40682. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  40683. * @return Wrapped position in sample range
  40684. */
  40685. RollingAverage.prototype._wrapPosition = function (i) {
  40686. var max = this._samples.length;
  40687. return ((i % max) + max) % max;
  40688. };
  40689. return RollingAverage;
  40690. }());
  40691. BABYLON.RollingAverage = RollingAverage;
  40692. })(BABYLON || (BABYLON = {}));
  40693. //# sourceMappingURL=babylon.performanceMonitor.js.map
  40694. var BABYLON;
  40695. (function (BABYLON) {
  40696. /**
  40697. * "Static Class" containing the most commonly used helper while dealing with material for
  40698. * rendering purpose.
  40699. *
  40700. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  40701. *
  40702. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  40703. */
  40704. var MaterialHelper = /** @class */ (function () {
  40705. function MaterialHelper() {
  40706. }
  40707. /**
  40708. * Bind the current view position to an effect.
  40709. * @param effect The effect to be bound
  40710. * @param scene The scene the eyes position is used from
  40711. */
  40712. MaterialHelper.BindEyePosition = function (effect, scene) {
  40713. if (scene._forcedViewPosition) {
  40714. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  40715. return;
  40716. }
  40717. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  40718. };
  40719. /**
  40720. * Helps preparing the defines values about the UVs in used in the effect.
  40721. * UVs are shared as much as we can accross chanels in the shaders.
  40722. * @param texture The texture we are preparing the UVs for
  40723. * @param defines The defines to update
  40724. * @param key The chanel key "diffuse", "specular"... used in the shader
  40725. */
  40726. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  40727. defines._needUVs = true;
  40728. defines[key] = true;
  40729. if (texture.getTextureMatrix().isIdentity(true)) {
  40730. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  40731. if (texture.coordinatesIndex === 0) {
  40732. defines["MAINUV1"] = true;
  40733. }
  40734. else {
  40735. defines["MAINUV2"] = true;
  40736. }
  40737. }
  40738. else {
  40739. defines[key + "DIRECTUV"] = 0;
  40740. }
  40741. };
  40742. /**
  40743. * Binds a texture matrix value to its corrsponding uniform
  40744. * @param texture The texture to bind the matrix for
  40745. * @param uniformBuffer The uniform buffer receivin the data
  40746. * @param key The chanel key "diffuse", "specular"... used in the shader
  40747. */
  40748. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  40749. var matrix = texture.getTextureMatrix();
  40750. if (!matrix.isIdentity(true)) {
  40751. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  40752. }
  40753. };
  40754. /**
  40755. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  40756. * @param mesh defines the current mesh
  40757. * @param scene defines the current scene
  40758. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  40759. * @param pointsCloud defines if point cloud rendering has to be turned on
  40760. * @param fogEnabled defines if fog has to be turned on
  40761. * @param alphaTest defines if alpha testing has to be turned on
  40762. * @param defines defines the current list of defines
  40763. */
  40764. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  40765. if (defines._areMiscDirty) {
  40766. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  40767. defines["POINTSIZE"] = pointsCloud;
  40768. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  40769. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  40770. defines["ALPHATEST"] = alphaTest;
  40771. }
  40772. };
  40773. /**
  40774. * Helper used to prepare the list of defines associated with frame values for shader compilation
  40775. * @param scene defines the current scene
  40776. * @param engine defines the current engine
  40777. * @param defines specifies the list of active defines
  40778. * @param useInstances defines if instances have to be turned on
  40779. * @param useClipPlane defines if clip plane have to be turned on
  40780. */
  40781. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  40782. if (useClipPlane === void 0) { useClipPlane = null; }
  40783. var changed = false;
  40784. var useClipPlane1 = false;
  40785. var useClipPlane2 = false;
  40786. var useClipPlane3 = false;
  40787. var useClipPlane4 = false;
  40788. useClipPlane1 = useClipPlane == null ? (scene.clipPlane !== undefined && scene.clipPlane !== null) : useClipPlane;
  40789. useClipPlane2 = useClipPlane == null ? (scene.clipPlane2 !== undefined && scene.clipPlane2 !== null) : useClipPlane;
  40790. useClipPlane3 = useClipPlane == null ? (scene.clipPlane3 !== undefined && scene.clipPlane3 !== null) : useClipPlane;
  40791. useClipPlane4 = useClipPlane == null ? (scene.clipPlane4 !== undefined && scene.clipPlane4 !== null) : useClipPlane;
  40792. if (defines["CLIPPLANE"] !== useClipPlane1) {
  40793. defines["CLIPPLANE"] = useClipPlane1;
  40794. changed = true;
  40795. }
  40796. if (defines["CLIPPLANE2"] !== useClipPlane2) {
  40797. defines["CLIPPLANE2"] = useClipPlane2;
  40798. changed = true;
  40799. }
  40800. if (defines["CLIPPLANE3"] !== useClipPlane3) {
  40801. defines["CLIPPLANE3"] = useClipPlane3;
  40802. changed = true;
  40803. }
  40804. if (defines["CLIPPLANE4"] !== useClipPlane4) {
  40805. defines["CLIPPLANE4"] = useClipPlane4;
  40806. changed = true;
  40807. }
  40808. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  40809. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  40810. changed = true;
  40811. }
  40812. if (defines["INSTANCES"] !== useInstances) {
  40813. defines["INSTANCES"] = useInstances;
  40814. changed = true;
  40815. }
  40816. if (changed) {
  40817. defines.markAsUnprocessed();
  40818. }
  40819. };
  40820. /**
  40821. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  40822. * @param mesh The mesh containing the geometry data we will draw
  40823. * @param defines The defines to update
  40824. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  40825. * @param useBones Precise whether bones should be used or not (override mesh info)
  40826. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  40827. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  40828. * @returns false if defines are considered not dirty and have not been checked
  40829. */
  40830. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  40831. if (useMorphTargets === void 0) { useMorphTargets = false; }
  40832. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  40833. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  40834. return false;
  40835. }
  40836. defines._normals = defines._needNormals;
  40837. defines._uvs = defines._needUVs;
  40838. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  40839. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  40840. defines["TANGENT"] = true;
  40841. }
  40842. if (defines._needUVs) {
  40843. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  40844. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  40845. }
  40846. else {
  40847. defines["UV1"] = false;
  40848. defines["UV2"] = false;
  40849. }
  40850. if (useVertexColor) {
  40851. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  40852. defines["VERTEXCOLOR"] = hasVertexColors;
  40853. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  40854. }
  40855. if (useBones) {
  40856. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  40857. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  40858. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  40859. }
  40860. else {
  40861. defines["NUM_BONE_INFLUENCERS"] = 0;
  40862. defines["BonesPerMesh"] = 0;
  40863. }
  40864. }
  40865. if (useMorphTargets) {
  40866. var manager = mesh.morphTargetManager;
  40867. if (manager) {
  40868. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  40869. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  40870. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  40871. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  40872. }
  40873. else {
  40874. defines["MORPHTARGETS_TANGENT"] = false;
  40875. defines["MORPHTARGETS_NORMAL"] = false;
  40876. defines["MORPHTARGETS"] = false;
  40877. defines["NUM_MORPH_INFLUENCERS"] = 0;
  40878. }
  40879. }
  40880. return true;
  40881. };
  40882. /**
  40883. * Prepares the defines related to the light information passed in parameter
  40884. * @param scene The scene we are intending to draw
  40885. * @param mesh The mesh the effect is compiling for
  40886. * @param defines The defines to update
  40887. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  40888. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  40889. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  40890. * @returns true if normals will be required for the rest of the effect
  40891. */
  40892. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  40893. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  40894. if (disableLighting === void 0) { disableLighting = false; }
  40895. if (!defines._areLightsDirty) {
  40896. return defines._needNormals;
  40897. }
  40898. var lightIndex = 0;
  40899. var needNormals = false;
  40900. var needRebuild = false;
  40901. var lightmapMode = false;
  40902. var shadowEnabled = false;
  40903. var specularEnabled = false;
  40904. if (scene.lightsEnabled && !disableLighting) {
  40905. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  40906. var light = _a[_i];
  40907. needNormals = true;
  40908. if (defines["LIGHT" + lightIndex] === undefined) {
  40909. needRebuild = true;
  40910. }
  40911. defines["LIGHT" + lightIndex] = true;
  40912. defines["SPOTLIGHT" + lightIndex] = false;
  40913. defines["HEMILIGHT" + lightIndex] = false;
  40914. defines["POINTLIGHT" + lightIndex] = false;
  40915. defines["DIRLIGHT" + lightIndex] = false;
  40916. light.prepareLightSpecificDefines(defines, lightIndex);
  40917. // FallOff.
  40918. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = false;
  40919. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = false;
  40920. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = false;
  40921. switch (light.falloffType) {
  40922. case BABYLON.Light.FALLOFF_GLTF:
  40923. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = true;
  40924. break;
  40925. case BABYLON.Light.FALLOFF_PHYSICAL:
  40926. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = true;
  40927. break;
  40928. case BABYLON.Light.FALLOFF_STANDARD:
  40929. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = true;
  40930. break;
  40931. }
  40932. // Specular
  40933. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  40934. specularEnabled = true;
  40935. }
  40936. // Shadows
  40937. defines["SHADOW" + lightIndex] = false;
  40938. defines["SHADOWPCF" + lightIndex] = false;
  40939. defines["SHADOWPCSS" + lightIndex] = false;
  40940. defines["SHADOWPOISSON" + lightIndex] = false;
  40941. defines["SHADOWESM" + lightIndex] = false;
  40942. defines["SHADOWCUBE" + lightIndex] = false;
  40943. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  40944. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  40945. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  40946. var shadowGenerator = light.getShadowGenerator();
  40947. if (shadowGenerator) {
  40948. var shadowMap = shadowGenerator.getShadowMap();
  40949. if (shadowMap) {
  40950. if (shadowMap.renderList && shadowMap.renderList.length > 0) {
  40951. shadowEnabled = true;
  40952. shadowGenerator.prepareDefines(defines, lightIndex);
  40953. }
  40954. }
  40955. }
  40956. }
  40957. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  40958. lightmapMode = true;
  40959. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  40960. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  40961. }
  40962. else {
  40963. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  40964. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  40965. }
  40966. lightIndex++;
  40967. if (lightIndex === maxSimultaneousLights)
  40968. break;
  40969. }
  40970. }
  40971. defines["SPECULARTERM"] = specularEnabled;
  40972. defines["SHADOWS"] = shadowEnabled;
  40973. // Resetting all other lights if any
  40974. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  40975. if (defines["LIGHT" + index] !== undefined) {
  40976. defines["LIGHT" + index] = false;
  40977. defines["HEMILIGHT" + lightIndex] = false;
  40978. defines["POINTLIGHT" + lightIndex] = false;
  40979. defines["DIRLIGHT" + lightIndex] = false;
  40980. defines["SPOTLIGHT" + lightIndex] = false;
  40981. defines["SHADOW" + lightIndex] = false;
  40982. }
  40983. }
  40984. var caps = scene.getEngine().getCaps();
  40985. if (defines["SHADOWFLOAT"] === undefined) {
  40986. needRebuild = true;
  40987. }
  40988. defines["SHADOWFLOAT"] = shadowEnabled &&
  40989. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  40990. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  40991. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  40992. if (needRebuild) {
  40993. defines.rebuild();
  40994. }
  40995. return needNormals;
  40996. };
  40997. /**
  40998. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  40999. * that won t be acctive due to defines being turned off.
  41000. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  41001. * @param samplersList The samplers list
  41002. * @param defines The defines helping in the list generation
  41003. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  41004. */
  41005. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  41006. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41007. var uniformsList;
  41008. var uniformBuffersList = null;
  41009. if (uniformsListOrOptions.uniformsNames) {
  41010. var options = uniformsListOrOptions;
  41011. uniformsList = options.uniformsNames;
  41012. uniformBuffersList = options.uniformBuffersNames;
  41013. samplersList = options.samplers;
  41014. defines = options.defines;
  41015. maxSimultaneousLights = options.maxSimultaneousLights;
  41016. }
  41017. else {
  41018. uniformsList = uniformsListOrOptions;
  41019. if (!samplersList) {
  41020. samplersList = [];
  41021. }
  41022. }
  41023. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41024. if (!defines["LIGHT" + lightIndex]) {
  41025. break;
  41026. }
  41027. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightFalloff" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  41028. if (uniformBuffersList) {
  41029. uniformBuffersList.push("Light" + lightIndex);
  41030. }
  41031. samplersList.push("shadowSampler" + lightIndex);
  41032. samplersList.push("depthSampler" + lightIndex);
  41033. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  41034. samplersList.push("projectionLightSampler" + lightIndex);
  41035. uniformsList.push("textureProjectionMatrix" + lightIndex);
  41036. }
  41037. }
  41038. if (defines["NUM_MORPH_INFLUENCERS"]) {
  41039. uniformsList.push("morphTargetInfluences");
  41040. }
  41041. };
  41042. /**
  41043. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  41044. * @param defines The defines to update while falling back
  41045. * @param fallbacks The authorized effect fallbacks
  41046. * @param maxSimultaneousLights The maximum number of lights allowed
  41047. * @param rank the current rank of the Effect
  41048. * @returns The newly affected rank
  41049. */
  41050. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  41051. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41052. if (rank === void 0) { rank = 0; }
  41053. var lightFallbackRank = 0;
  41054. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41055. if (!defines["LIGHT" + lightIndex]) {
  41056. break;
  41057. }
  41058. if (lightIndex > 0) {
  41059. lightFallbackRank = rank + lightIndex;
  41060. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  41061. }
  41062. if (!defines["SHADOWS"]) {
  41063. if (defines["SHADOW" + lightIndex]) {
  41064. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  41065. }
  41066. if (defines["SHADOWPCF" + lightIndex]) {
  41067. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  41068. }
  41069. if (defines["SHADOWPCSS" + lightIndex]) {
  41070. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  41071. }
  41072. if (defines["SHADOWPOISSON" + lightIndex]) {
  41073. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  41074. }
  41075. if (defines["SHADOWESM" + lightIndex]) {
  41076. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  41077. }
  41078. }
  41079. }
  41080. return lightFallbackRank++;
  41081. };
  41082. /**
  41083. * Prepares the list of attributes required for morph targets according to the effect defines.
  41084. * @param attribs The current list of supported attribs
  41085. * @param mesh The mesh to prepare the morph targets attributes for
  41086. * @param defines The current Defines of the effect
  41087. */
  41088. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  41089. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  41090. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  41091. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  41092. var manager = mesh.morphTargetManager;
  41093. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  41094. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  41095. for (var index = 0; index < influencers; index++) {
  41096. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  41097. if (normal) {
  41098. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  41099. }
  41100. if (tangent) {
  41101. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  41102. }
  41103. if (attribs.length > maxAttributesCount) {
  41104. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  41105. }
  41106. }
  41107. }
  41108. };
  41109. /**
  41110. * Prepares the list of attributes required for bones according to the effect defines.
  41111. * @param attribs The current list of supported attribs
  41112. * @param mesh The mesh to prepare the bones attributes for
  41113. * @param defines The current Defines of the effect
  41114. * @param fallbacks The current efffect fallback strategy
  41115. */
  41116. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  41117. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  41118. fallbacks.addCPUSkinningFallback(0, mesh);
  41119. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  41120. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  41121. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  41122. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  41123. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  41124. }
  41125. }
  41126. };
  41127. /**
  41128. * Prepares the list of attributes required for instances according to the effect defines.
  41129. * @param attribs The current list of supported attribs
  41130. * @param defines The current Defines of the effect
  41131. */
  41132. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  41133. if (defines["INSTANCES"]) {
  41134. attribs.push("world0");
  41135. attribs.push("world1");
  41136. attribs.push("world2");
  41137. attribs.push("world3");
  41138. }
  41139. };
  41140. /**
  41141. * Binds the light shadow information to the effect for the given mesh.
  41142. * @param light The light containing the generator
  41143. * @param scene The scene the lights belongs to
  41144. * @param mesh The mesh we are binding the information to render
  41145. * @param lightIndex The light index in the effect used to render the mesh
  41146. * @param effect The effect we are binding the data to
  41147. */
  41148. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  41149. if (light.shadowEnabled && mesh.receiveShadows) {
  41150. var shadowGenerator = light.getShadowGenerator();
  41151. if (shadowGenerator) {
  41152. shadowGenerator.bindShadowLight(lightIndex, effect);
  41153. }
  41154. }
  41155. };
  41156. /**
  41157. * Binds the light information to the effect.
  41158. * @param light The light containing the generator
  41159. * @param effect The effect we are binding the data to
  41160. * @param lightIndex The light index in the effect used to render
  41161. */
  41162. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  41163. light.transferToEffect(effect, lightIndex + "");
  41164. };
  41165. /**
  41166. * Binds the lights information from the scene to the effect for the given mesh.
  41167. * @param scene The scene the lights belongs to
  41168. * @param mesh The mesh we are binding the information to render
  41169. * @param effect The effect we are binding the data to
  41170. * @param defines The generated defines for the effect
  41171. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  41172. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  41173. */
  41174. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  41175. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41176. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  41177. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  41178. for (var i = 0; i < len; i++) {
  41179. var light = mesh._lightSources[i];
  41180. var iAsString = i.toString();
  41181. var scaledIntensity = light.getScaledIntensity();
  41182. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  41183. MaterialHelper.BindLightProperties(light, effect, i);
  41184. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  41185. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  41186. if (defines["SPECULARTERM"]) {
  41187. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  41188. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  41189. }
  41190. // Shadows
  41191. if (scene.shadowsEnabled) {
  41192. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  41193. }
  41194. light._uniformBuffer.update();
  41195. }
  41196. };
  41197. /**
  41198. * Binds the fog information from the scene to the effect for the given mesh.
  41199. * @param scene The scene the lights belongs to
  41200. * @param mesh The mesh we are binding the information to render
  41201. * @param effect The effect we are binding the data to
  41202. */
  41203. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  41204. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  41205. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  41206. effect.setColor3("vFogColor", scene.fogColor);
  41207. }
  41208. };
  41209. /**
  41210. * Binds the bones information from the mesh to the effect.
  41211. * @param mesh The mesh we are binding the information to render
  41212. * @param effect The effect we are binding the data to
  41213. */
  41214. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  41215. if (!effect || !mesh) {
  41216. return;
  41217. }
  41218. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  41219. mesh.computeBonesUsingShaders = false;
  41220. }
  41221. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41222. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  41223. if (matrices) {
  41224. effect.setMatrices("mBones", matrices);
  41225. }
  41226. }
  41227. };
  41228. /**
  41229. * Binds the morph targets information from the mesh to the effect.
  41230. * @param abstractMesh The mesh we are binding the information to render
  41231. * @param effect The effect we are binding the data to
  41232. */
  41233. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  41234. var manager = abstractMesh.morphTargetManager;
  41235. if (!abstractMesh || !manager) {
  41236. return;
  41237. }
  41238. effect.setFloatArray("morphTargetInfluences", manager.influences);
  41239. };
  41240. /**
  41241. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  41242. * @param defines The generated defines used in the effect
  41243. * @param effect The effect we are binding the data to
  41244. * @param scene The scene we are willing to render with logarithmic scale for
  41245. */
  41246. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  41247. if (defines["LOGARITHMICDEPTH"]) {
  41248. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  41249. }
  41250. };
  41251. /**
  41252. * Binds the clip plane information from the scene to the effect.
  41253. * @param scene The scene the clip plane information are extracted from
  41254. * @param effect The effect we are binding the data to
  41255. */
  41256. MaterialHelper.BindClipPlane = function (effect, scene) {
  41257. if (scene.clipPlane) {
  41258. var clipPlane = scene.clipPlane;
  41259. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41260. }
  41261. if (scene.clipPlane2) {
  41262. var clipPlane = scene.clipPlane2;
  41263. effect.setFloat4("vClipPlane2", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41264. }
  41265. if (scene.clipPlane3) {
  41266. var clipPlane = scene.clipPlane3;
  41267. effect.setFloat4("vClipPlane3", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41268. }
  41269. if (scene.clipPlane4) {
  41270. var clipPlane = scene.clipPlane4;
  41271. effect.setFloat4("vClipPlane4", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41272. }
  41273. };
  41274. return MaterialHelper;
  41275. }());
  41276. BABYLON.MaterialHelper = MaterialHelper;
  41277. })(BABYLON || (BABYLON = {}));
  41278. //# sourceMappingURL=babylon.materialHelper.js.map
  41279. var BABYLON;
  41280. (function (BABYLON) {
  41281. var PushMaterial = /** @class */ (function (_super) {
  41282. __extends(PushMaterial, _super);
  41283. function PushMaterial(name, scene) {
  41284. var _this = _super.call(this, name, scene) || this;
  41285. _this._normalMatrix = new BABYLON.Matrix();
  41286. _this.storeEffectOnSubMeshes = true;
  41287. return _this;
  41288. }
  41289. PushMaterial.prototype.getEffect = function () {
  41290. return this._activeEffect;
  41291. };
  41292. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  41293. if (!mesh) {
  41294. return false;
  41295. }
  41296. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  41297. return true;
  41298. }
  41299. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  41300. };
  41301. /**
  41302. * Binds the given world matrix to the active effect
  41303. *
  41304. * @param world the matrix to bind
  41305. */
  41306. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  41307. this._activeEffect.setMatrix("world", world);
  41308. };
  41309. /**
  41310. * Binds the given normal matrix to the active effect
  41311. *
  41312. * @param normalMatrix the matrix to bind
  41313. */
  41314. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  41315. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  41316. };
  41317. PushMaterial.prototype.bind = function (world, mesh) {
  41318. if (!mesh) {
  41319. return;
  41320. }
  41321. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  41322. };
  41323. PushMaterial.prototype._afterBind = function (mesh, effect) {
  41324. if (effect === void 0) { effect = null; }
  41325. _super.prototype._afterBind.call(this, mesh);
  41326. this.getScene()._cachedEffect = effect;
  41327. };
  41328. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  41329. if (visibility === void 0) { visibility = 1; }
  41330. return scene.isCachedMaterialInvalid(this, effect, visibility);
  41331. };
  41332. return PushMaterial;
  41333. }(BABYLON.Material));
  41334. BABYLON.PushMaterial = PushMaterial;
  41335. })(BABYLON || (BABYLON = {}));
  41336. //# sourceMappingURL=babylon.pushMaterial.js.map
  41337. var BABYLON;
  41338. (function (BABYLON) {
  41339. /** @hidden */
  41340. var StandardMaterialDefines = /** @class */ (function (_super) {
  41341. __extends(StandardMaterialDefines, _super);
  41342. function StandardMaterialDefines() {
  41343. var _this = _super.call(this) || this;
  41344. _this.MAINUV1 = false;
  41345. _this.MAINUV2 = false;
  41346. _this.DIFFUSE = false;
  41347. _this.DIFFUSEDIRECTUV = 0;
  41348. _this.AMBIENT = false;
  41349. _this.AMBIENTDIRECTUV = 0;
  41350. _this.OPACITY = false;
  41351. _this.OPACITYDIRECTUV = 0;
  41352. _this.OPACITYRGB = false;
  41353. _this.REFLECTION = false;
  41354. _this.EMISSIVE = false;
  41355. _this.EMISSIVEDIRECTUV = 0;
  41356. _this.SPECULAR = false;
  41357. _this.SPECULARDIRECTUV = 0;
  41358. _this.BUMP = false;
  41359. _this.BUMPDIRECTUV = 0;
  41360. _this.PARALLAX = false;
  41361. _this.PARALLAXOCCLUSION = false;
  41362. _this.SPECULAROVERALPHA = false;
  41363. _this.CLIPPLANE = false;
  41364. _this.CLIPPLANE2 = false;
  41365. _this.CLIPPLANE3 = false;
  41366. _this.CLIPPLANE4 = false;
  41367. _this.ALPHATEST = false;
  41368. _this.DEPTHPREPASS = false;
  41369. _this.ALPHAFROMDIFFUSE = false;
  41370. _this.POINTSIZE = false;
  41371. _this.FOG = false;
  41372. _this.SPECULARTERM = false;
  41373. _this.DIFFUSEFRESNEL = false;
  41374. _this.OPACITYFRESNEL = false;
  41375. _this.REFLECTIONFRESNEL = false;
  41376. _this.REFRACTIONFRESNEL = false;
  41377. _this.EMISSIVEFRESNEL = false;
  41378. _this.FRESNEL = false;
  41379. _this.NORMAL = false;
  41380. _this.UV1 = false;
  41381. _this.UV2 = false;
  41382. _this.VERTEXCOLOR = false;
  41383. _this.VERTEXALPHA = false;
  41384. _this.NUM_BONE_INFLUENCERS = 0;
  41385. _this.BonesPerMesh = 0;
  41386. _this.INSTANCES = false;
  41387. _this.GLOSSINESS = false;
  41388. _this.ROUGHNESS = false;
  41389. _this.EMISSIVEASILLUMINATION = false;
  41390. _this.LINKEMISSIVEWITHDIFFUSE = false;
  41391. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  41392. _this.LIGHTMAP = false;
  41393. _this.LIGHTMAPDIRECTUV = 0;
  41394. _this.OBJECTSPACE_NORMALMAP = false;
  41395. _this.USELIGHTMAPASSHADOWMAP = false;
  41396. _this.REFLECTIONMAP_3D = false;
  41397. _this.REFLECTIONMAP_SPHERICAL = false;
  41398. _this.REFLECTIONMAP_PLANAR = false;
  41399. _this.REFLECTIONMAP_CUBIC = false;
  41400. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41401. _this.REFLECTIONMAP_PROJECTION = false;
  41402. _this.REFLECTIONMAP_SKYBOX = false;
  41403. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  41404. _this.REFLECTIONMAP_EXPLICIT = false;
  41405. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41406. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41407. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41408. _this.INVERTCUBICMAP = false;
  41409. _this.LOGARITHMICDEPTH = false;
  41410. _this.REFRACTION = false;
  41411. _this.REFRACTIONMAP_3D = false;
  41412. _this.REFLECTIONOVERALPHA = false;
  41413. _this.TWOSIDEDLIGHTING = false;
  41414. _this.SHADOWFLOAT = false;
  41415. _this.MORPHTARGETS = false;
  41416. _this.MORPHTARGETS_NORMAL = false;
  41417. _this.MORPHTARGETS_TANGENT = false;
  41418. _this.NUM_MORPH_INFLUENCERS = 0;
  41419. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  41420. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  41421. _this.IMAGEPROCESSING = false;
  41422. _this.VIGNETTE = false;
  41423. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  41424. _this.VIGNETTEBLENDMODEOPAQUE = false;
  41425. _this.TONEMAPPING = false;
  41426. _this.TONEMAPPING_ACES = false;
  41427. _this.CONTRAST = false;
  41428. _this.COLORCURVES = false;
  41429. _this.COLORGRADING = false;
  41430. _this.COLORGRADING3D = false;
  41431. _this.SAMPLER3DGREENDEPTH = false;
  41432. _this.SAMPLER3DBGRMAP = false;
  41433. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  41434. /**
  41435. * If the reflection texture on this material is in linear color space
  41436. * @hidden
  41437. */
  41438. _this.IS_REFLECTION_LINEAR = false;
  41439. /**
  41440. * If the refraction texture on this material is in linear color space
  41441. * @hidden
  41442. */
  41443. _this.IS_REFRACTION_LINEAR = false;
  41444. _this.EXPOSURE = false;
  41445. _this.rebuild();
  41446. return _this;
  41447. }
  41448. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  41449. var modes = [
  41450. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  41451. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  41452. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  41453. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  41454. ];
  41455. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  41456. var mode = modes_1[_i];
  41457. this[mode] = (mode === modeToEnable);
  41458. }
  41459. };
  41460. return StandardMaterialDefines;
  41461. }(BABYLON.MaterialDefines));
  41462. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  41463. var StandardMaterial = /** @class */ (function (_super) {
  41464. __extends(StandardMaterial, _super);
  41465. function StandardMaterial(name, scene) {
  41466. var _this = _super.call(this, name, scene) || this;
  41467. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41468. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  41469. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  41470. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41471. _this.specularPower = 64;
  41472. _this._useAlphaFromDiffuseTexture = false;
  41473. _this._useEmissiveAsIllumination = false;
  41474. _this._linkEmissiveWithDiffuse = false;
  41475. _this._useSpecularOverAlpha = false;
  41476. _this._useReflectionOverAlpha = false;
  41477. _this._disableLighting = false;
  41478. _this._useObjectSpaceNormalMap = false;
  41479. _this._useParallax = false;
  41480. _this._useParallaxOcclusion = false;
  41481. _this.parallaxScaleBias = 0.05;
  41482. _this._roughness = 0;
  41483. _this.indexOfRefraction = 0.98;
  41484. _this.invertRefractionY = true;
  41485. /**
  41486. * Defines the alpha limits in alpha test mode
  41487. */
  41488. _this.alphaCutOff = 0.4;
  41489. _this._useLightmapAsShadowmap = false;
  41490. _this._useReflectionFresnelFromSpecular = false;
  41491. _this._useGlossinessFromSpecularMapAlpha = false;
  41492. _this._maxSimultaneousLights = 4;
  41493. /**
  41494. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41495. */
  41496. _this._invertNormalMapX = false;
  41497. /**
  41498. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41499. */
  41500. _this._invertNormalMapY = false;
  41501. /**
  41502. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41503. */
  41504. _this._twoSidedLighting = false;
  41505. _this._renderTargets = new BABYLON.SmartArray(16);
  41506. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  41507. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  41508. // Setup the default processing configuration to the scene.
  41509. _this._attachImageProcessingConfiguration(null);
  41510. _this.getRenderTargetTextures = function () {
  41511. _this._renderTargets.reset();
  41512. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  41513. _this._renderTargets.push(_this._reflectionTexture);
  41514. }
  41515. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  41516. _this._renderTargets.push(_this._refractionTexture);
  41517. }
  41518. return _this._renderTargets;
  41519. };
  41520. return _this;
  41521. }
  41522. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  41523. /**
  41524. * Gets the image processing configuration used either in this material.
  41525. */
  41526. get: function () {
  41527. return this._imageProcessingConfiguration;
  41528. },
  41529. /**
  41530. * Sets the Default image processing configuration used either in the this material.
  41531. *
  41532. * If sets to null, the scene one is in use.
  41533. */
  41534. set: function (value) {
  41535. this._attachImageProcessingConfiguration(value);
  41536. // Ensure the effect will be rebuilt.
  41537. this._markAllSubMeshesAsTexturesDirty();
  41538. },
  41539. enumerable: true,
  41540. configurable: true
  41541. });
  41542. /**
  41543. * Attaches a new image processing configuration to the Standard Material.
  41544. * @param configuration
  41545. */
  41546. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  41547. var _this = this;
  41548. if (configuration === this._imageProcessingConfiguration) {
  41549. return;
  41550. }
  41551. // Detaches observer.
  41552. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41553. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41554. }
  41555. // Pick the scene configuration if needed.
  41556. if (!configuration) {
  41557. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  41558. }
  41559. else {
  41560. this._imageProcessingConfiguration = configuration;
  41561. }
  41562. // Attaches observer.
  41563. if (this._imageProcessingConfiguration) {
  41564. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  41565. _this._markAllSubMeshesAsImageProcessingDirty();
  41566. });
  41567. }
  41568. };
  41569. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  41570. /**
  41571. * Gets wether the color curves effect is enabled.
  41572. */
  41573. get: function () {
  41574. return this.imageProcessingConfiguration.colorCurvesEnabled;
  41575. },
  41576. /**
  41577. * Sets wether the color curves effect is enabled.
  41578. */
  41579. set: function (value) {
  41580. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  41581. },
  41582. enumerable: true,
  41583. configurable: true
  41584. });
  41585. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  41586. /**
  41587. * Gets wether the color grading effect is enabled.
  41588. */
  41589. get: function () {
  41590. return this.imageProcessingConfiguration.colorGradingEnabled;
  41591. },
  41592. /**
  41593. * Gets wether the color grading effect is enabled.
  41594. */
  41595. set: function (value) {
  41596. this.imageProcessingConfiguration.colorGradingEnabled = value;
  41597. },
  41598. enumerable: true,
  41599. configurable: true
  41600. });
  41601. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  41602. /**
  41603. * Gets wether tonemapping is enabled or not.
  41604. */
  41605. get: function () {
  41606. return this._imageProcessingConfiguration.toneMappingEnabled;
  41607. },
  41608. /**
  41609. * Sets wether tonemapping is enabled or not
  41610. */
  41611. set: function (value) {
  41612. this._imageProcessingConfiguration.toneMappingEnabled = value;
  41613. },
  41614. enumerable: true,
  41615. configurable: true
  41616. });
  41617. ;
  41618. ;
  41619. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  41620. /**
  41621. * The camera exposure used on this material.
  41622. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41623. * This corresponds to a photographic exposure.
  41624. */
  41625. get: function () {
  41626. return this._imageProcessingConfiguration.exposure;
  41627. },
  41628. /**
  41629. * The camera exposure used on this material.
  41630. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41631. * This corresponds to a photographic exposure.
  41632. */
  41633. set: function (value) {
  41634. this._imageProcessingConfiguration.exposure = value;
  41635. },
  41636. enumerable: true,
  41637. configurable: true
  41638. });
  41639. ;
  41640. ;
  41641. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  41642. /**
  41643. * Gets The camera contrast used on this material.
  41644. */
  41645. get: function () {
  41646. return this._imageProcessingConfiguration.contrast;
  41647. },
  41648. /**
  41649. * Sets The camera contrast used on this material.
  41650. */
  41651. set: function (value) {
  41652. this._imageProcessingConfiguration.contrast = value;
  41653. },
  41654. enumerable: true,
  41655. configurable: true
  41656. });
  41657. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  41658. /**
  41659. * Gets the Color Grading 2D Lookup Texture.
  41660. */
  41661. get: function () {
  41662. return this._imageProcessingConfiguration.colorGradingTexture;
  41663. },
  41664. /**
  41665. * Sets the Color Grading 2D Lookup Texture.
  41666. */
  41667. set: function (value) {
  41668. this._imageProcessingConfiguration.colorGradingTexture = value;
  41669. },
  41670. enumerable: true,
  41671. configurable: true
  41672. });
  41673. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  41674. /**
  41675. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41676. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41677. * 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;
  41678. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41679. */
  41680. get: function () {
  41681. return this._imageProcessingConfiguration.colorCurves;
  41682. },
  41683. /**
  41684. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41685. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41686. * 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;
  41687. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41688. */
  41689. set: function (value) {
  41690. this._imageProcessingConfiguration.colorCurves = value;
  41691. },
  41692. enumerable: true,
  41693. configurable: true
  41694. });
  41695. Object.defineProperty(StandardMaterial.prototype, "hasRenderTargetTextures", {
  41696. /**
  41697. * Gets a boolean indicating that current material needs to register RTT
  41698. */
  41699. get: function () {
  41700. if (StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  41701. return true;
  41702. }
  41703. if (StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
  41704. return true;
  41705. }
  41706. return false;
  41707. },
  41708. enumerable: true,
  41709. configurable: true
  41710. });
  41711. StandardMaterial.prototype.getClassName = function () {
  41712. return "StandardMaterial";
  41713. };
  41714. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  41715. get: function () {
  41716. return this._useLogarithmicDepth;
  41717. },
  41718. set: function (value) {
  41719. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  41720. this._markAllSubMeshesAsMiscDirty();
  41721. },
  41722. enumerable: true,
  41723. configurable: true
  41724. });
  41725. StandardMaterial.prototype.needAlphaBlending = function () {
  41726. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  41727. };
  41728. StandardMaterial.prototype.needAlphaTesting = function () {
  41729. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  41730. };
  41731. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  41732. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  41733. };
  41734. StandardMaterial.prototype.getAlphaTestTexture = function () {
  41735. return this._diffuseTexture;
  41736. };
  41737. /**
  41738. * Child classes can use it to update shaders
  41739. */
  41740. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  41741. if (useInstances === void 0) { useInstances = false; }
  41742. if (subMesh.effect && this.isFrozen) {
  41743. if (this._wasPreviouslyReady) {
  41744. return true;
  41745. }
  41746. }
  41747. if (!subMesh._materialDefines) {
  41748. subMesh._materialDefines = new StandardMaterialDefines();
  41749. }
  41750. var scene = this.getScene();
  41751. var defines = subMesh._materialDefines;
  41752. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  41753. if (defines._renderId === scene.getRenderId()) {
  41754. return true;
  41755. }
  41756. }
  41757. var engine = scene.getEngine();
  41758. // Lights
  41759. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  41760. // Textures
  41761. if (defines._areTexturesDirty) {
  41762. defines._needUVs = false;
  41763. defines.MAINUV1 = false;
  41764. defines.MAINUV2 = false;
  41765. if (scene.texturesEnabled) {
  41766. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  41767. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  41768. return false;
  41769. }
  41770. else {
  41771. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  41772. }
  41773. }
  41774. else {
  41775. defines.DIFFUSE = false;
  41776. }
  41777. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  41778. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  41779. return false;
  41780. }
  41781. else {
  41782. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  41783. }
  41784. }
  41785. else {
  41786. defines.AMBIENT = false;
  41787. }
  41788. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  41789. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  41790. return false;
  41791. }
  41792. else {
  41793. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  41794. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  41795. }
  41796. }
  41797. else {
  41798. defines.OPACITY = false;
  41799. }
  41800. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  41801. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  41802. return false;
  41803. }
  41804. else {
  41805. defines._needNormals = true;
  41806. defines.REFLECTION = true;
  41807. defines.ROUGHNESS = (this._roughness > 0);
  41808. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  41809. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  41810. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  41811. switch (this._reflectionTexture.coordinatesMode) {
  41812. case BABYLON.Texture.EXPLICIT_MODE:
  41813. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  41814. break;
  41815. case BABYLON.Texture.PLANAR_MODE:
  41816. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  41817. break;
  41818. case BABYLON.Texture.PROJECTION_MODE:
  41819. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  41820. break;
  41821. case BABYLON.Texture.SKYBOX_MODE:
  41822. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  41823. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !this._reflectionTexture.getReflectionTextureMatrix().isIdentity();
  41824. break;
  41825. case BABYLON.Texture.SPHERICAL_MODE:
  41826. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  41827. break;
  41828. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  41829. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  41830. break;
  41831. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  41832. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  41833. break;
  41834. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  41835. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  41836. break;
  41837. case BABYLON.Texture.CUBIC_MODE:
  41838. case BABYLON.Texture.INVCUBIC_MODE:
  41839. default:
  41840. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  41841. break;
  41842. }
  41843. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  41844. }
  41845. }
  41846. else {
  41847. defines.REFLECTION = false;
  41848. }
  41849. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  41850. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  41851. return false;
  41852. }
  41853. else {
  41854. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  41855. }
  41856. }
  41857. else {
  41858. defines.EMISSIVE = false;
  41859. }
  41860. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  41861. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  41862. return false;
  41863. }
  41864. else {
  41865. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  41866. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  41867. }
  41868. }
  41869. else {
  41870. defines.LIGHTMAP = false;
  41871. }
  41872. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  41873. if (!this._specularTexture.isReadyOrNotBlocking()) {
  41874. return false;
  41875. }
  41876. else {
  41877. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  41878. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  41879. }
  41880. }
  41881. else {
  41882. defines.SPECULAR = false;
  41883. }
  41884. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  41885. // Bump texure can not be not blocking.
  41886. if (!this._bumpTexture.isReady()) {
  41887. return false;
  41888. }
  41889. else {
  41890. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  41891. defines.PARALLAX = this._useParallax;
  41892. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  41893. }
  41894. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  41895. }
  41896. else {
  41897. defines.BUMP = false;
  41898. }
  41899. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  41900. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  41901. return false;
  41902. }
  41903. else {
  41904. defines._needUVs = true;
  41905. defines.REFRACTION = true;
  41906. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  41907. }
  41908. }
  41909. else {
  41910. defines.REFRACTION = false;
  41911. }
  41912. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  41913. }
  41914. else {
  41915. defines.DIFFUSE = false;
  41916. defines.AMBIENT = false;
  41917. defines.OPACITY = false;
  41918. defines.REFLECTION = false;
  41919. defines.EMISSIVE = false;
  41920. defines.LIGHTMAP = false;
  41921. defines.BUMP = false;
  41922. defines.REFRACTION = false;
  41923. }
  41924. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  41925. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  41926. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  41927. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  41928. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  41929. }
  41930. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  41931. if (!this._imageProcessingConfiguration.isReady()) {
  41932. return false;
  41933. }
  41934. this._imageProcessingConfiguration.prepareDefines(defines);
  41935. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  41936. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  41937. }
  41938. if (defines._areFresnelDirty) {
  41939. if (StandardMaterial.FresnelEnabled) {
  41940. // Fresnel
  41941. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  41942. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  41943. this._reflectionFresnelParameters) {
  41944. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  41945. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  41946. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  41947. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  41948. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  41949. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  41950. defines._needNormals = true;
  41951. defines.FRESNEL = true;
  41952. }
  41953. }
  41954. else {
  41955. defines.FRESNEL = false;
  41956. }
  41957. }
  41958. // Misc.
  41959. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  41960. // Attribs
  41961. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  41962. // Values that need to be evaluated on every frame
  41963. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  41964. // Get correct effect
  41965. if (defines.isDirty) {
  41966. defines.markAsProcessed();
  41967. scene.resetCachedMaterial();
  41968. // Fallbacks
  41969. var fallbacks = new BABYLON.EffectFallbacks();
  41970. if (defines.REFLECTION) {
  41971. fallbacks.addFallback(0, "REFLECTION");
  41972. }
  41973. if (defines.SPECULAR) {
  41974. fallbacks.addFallback(0, "SPECULAR");
  41975. }
  41976. if (defines.BUMP) {
  41977. fallbacks.addFallback(0, "BUMP");
  41978. }
  41979. if (defines.PARALLAX) {
  41980. fallbacks.addFallback(1, "PARALLAX");
  41981. }
  41982. if (defines.PARALLAXOCCLUSION) {
  41983. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  41984. }
  41985. if (defines.SPECULAROVERALPHA) {
  41986. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  41987. }
  41988. if (defines.FOG) {
  41989. fallbacks.addFallback(1, "FOG");
  41990. }
  41991. if (defines.POINTSIZE) {
  41992. fallbacks.addFallback(0, "POINTSIZE");
  41993. }
  41994. if (defines.LOGARITHMICDEPTH) {
  41995. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  41996. }
  41997. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  41998. if (defines.SPECULARTERM) {
  41999. fallbacks.addFallback(0, "SPECULARTERM");
  42000. }
  42001. if (defines.DIFFUSEFRESNEL) {
  42002. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  42003. }
  42004. if (defines.OPACITYFRESNEL) {
  42005. fallbacks.addFallback(2, "OPACITYFRESNEL");
  42006. }
  42007. if (defines.REFLECTIONFRESNEL) {
  42008. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  42009. }
  42010. if (defines.EMISSIVEFRESNEL) {
  42011. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  42012. }
  42013. if (defines.FRESNEL) {
  42014. fallbacks.addFallback(4, "FRESNEL");
  42015. }
  42016. //Attributes
  42017. var attribs = [BABYLON.VertexBuffer.PositionKind];
  42018. if (defines.NORMAL) {
  42019. attribs.push(BABYLON.VertexBuffer.NormalKind);
  42020. }
  42021. if (defines.UV1) {
  42022. attribs.push(BABYLON.VertexBuffer.UVKind);
  42023. }
  42024. if (defines.UV2) {
  42025. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  42026. }
  42027. if (defines.VERTEXCOLOR) {
  42028. attribs.push(BABYLON.VertexBuffer.ColorKind);
  42029. }
  42030. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  42031. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  42032. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  42033. var shaderName = "default";
  42034. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  42035. "vFogInfos", "vFogColor", "pointSize",
  42036. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  42037. "mBones",
  42038. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  42039. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  42040. "vReflectionPosition", "vReflectionSize",
  42041. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  42042. ];
  42043. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  42044. var uniformBuffers = ["Material", "Scene"];
  42045. if (BABYLON.ImageProcessingConfiguration) {
  42046. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  42047. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  42048. }
  42049. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  42050. uniformsNames: uniforms,
  42051. uniformBuffersNames: uniformBuffers,
  42052. samplers: samplers,
  42053. defines: defines,
  42054. maxSimultaneousLights: this._maxSimultaneousLights
  42055. });
  42056. if (this.customShaderNameResolve) {
  42057. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  42058. }
  42059. var join = defines.toString();
  42060. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  42061. attributes: attribs,
  42062. uniformsNames: uniforms,
  42063. uniformBuffersNames: uniformBuffers,
  42064. samplers: samplers,
  42065. defines: join,
  42066. fallbacks: fallbacks,
  42067. onCompiled: this.onCompiled,
  42068. onError: this.onError,
  42069. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  42070. }, engine), defines);
  42071. this.buildUniformLayout();
  42072. }
  42073. if (!subMesh.effect || !subMesh.effect.isReady()) {
  42074. return false;
  42075. }
  42076. defines._renderId = scene.getRenderId();
  42077. this._wasPreviouslyReady = true;
  42078. return true;
  42079. };
  42080. StandardMaterial.prototype.buildUniformLayout = function () {
  42081. // Order is important !
  42082. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  42083. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  42084. this._uniformBuffer.addUniform("opacityParts", 4);
  42085. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  42086. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  42087. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  42088. this._uniformBuffer.addUniform("refractionRightColor", 4);
  42089. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  42090. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  42091. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  42092. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  42093. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  42094. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  42095. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  42096. this._uniformBuffer.addUniform("vReflectionSize", 3);
  42097. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  42098. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  42099. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  42100. this._uniformBuffer.addUniform("vBumpInfos", 3);
  42101. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  42102. this._uniformBuffer.addUniform("ambientMatrix", 16);
  42103. this._uniformBuffer.addUniform("opacityMatrix", 16);
  42104. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  42105. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  42106. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  42107. this._uniformBuffer.addUniform("specularMatrix", 16);
  42108. this._uniformBuffer.addUniform("bumpMatrix", 16);
  42109. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  42110. this._uniformBuffer.addUniform("refractionMatrix", 16);
  42111. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  42112. this._uniformBuffer.addUniform("vSpecularColor", 4);
  42113. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  42114. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  42115. this._uniformBuffer.addUniform("pointSize", 1);
  42116. this._uniformBuffer.create();
  42117. };
  42118. StandardMaterial.prototype.unbind = function () {
  42119. if (this._activeEffect) {
  42120. var needFlag = false;
  42121. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  42122. this._activeEffect.setTexture("reflection2DSampler", null);
  42123. needFlag = true;
  42124. }
  42125. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  42126. this._activeEffect.setTexture("refraction2DSampler", null);
  42127. needFlag = true;
  42128. }
  42129. if (needFlag) {
  42130. this._markAllSubMeshesAsTexturesDirty();
  42131. }
  42132. }
  42133. _super.prototype.unbind.call(this);
  42134. };
  42135. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  42136. var scene = this.getScene();
  42137. var defines = subMesh._materialDefines;
  42138. if (!defines) {
  42139. return;
  42140. }
  42141. var effect = subMesh.effect;
  42142. if (!effect) {
  42143. return;
  42144. }
  42145. this._activeEffect = effect;
  42146. // Matrices
  42147. this.bindOnlyWorldMatrix(world);
  42148. // Normal Matrix
  42149. if (defines.OBJECTSPACE_NORMALMAP) {
  42150. world.toNormalMatrix(this._normalMatrix);
  42151. this.bindOnlyNormalMatrix(this._normalMatrix);
  42152. }
  42153. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  42154. // Bones
  42155. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  42156. if (mustRebind) {
  42157. this._uniformBuffer.bindToEffect(effect, "Material");
  42158. this.bindViewProjection(effect);
  42159. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  42160. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  42161. // Fresnel
  42162. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  42163. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  42164. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  42165. }
  42166. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  42167. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  42168. }
  42169. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  42170. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  42171. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  42172. }
  42173. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  42174. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  42175. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  42176. }
  42177. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  42178. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  42179. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  42180. }
  42181. }
  42182. // Textures
  42183. if (scene.texturesEnabled) {
  42184. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42185. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  42186. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  42187. if (this._diffuseTexture.hasAlpha) {
  42188. effect.setFloat("alphaCutOff", this.alphaCutOff);
  42189. }
  42190. }
  42191. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42192. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  42193. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  42194. }
  42195. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42196. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  42197. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  42198. }
  42199. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42200. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  42201. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  42202. if (this._reflectionTexture.boundingBoxSize) {
  42203. var cubeTexture = this._reflectionTexture;
  42204. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  42205. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  42206. }
  42207. }
  42208. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42209. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  42210. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  42211. }
  42212. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42213. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  42214. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  42215. }
  42216. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42217. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  42218. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  42219. }
  42220. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42221. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  42222. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  42223. if (scene._mirroredCameraPosition) {
  42224. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  42225. }
  42226. else {
  42227. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  42228. }
  42229. }
  42230. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42231. var depth = 1.0;
  42232. if (!this._refractionTexture.isCube) {
  42233. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  42234. if (this._refractionTexture.depth) {
  42235. depth = this._refractionTexture.depth;
  42236. }
  42237. }
  42238. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  42239. }
  42240. }
  42241. // Point size
  42242. if (this.pointsCloud) {
  42243. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  42244. }
  42245. if (defines.SPECULARTERM) {
  42246. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  42247. }
  42248. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  42249. // Diffuse
  42250. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  42251. }
  42252. // Textures
  42253. if (scene.texturesEnabled) {
  42254. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42255. effect.setTexture("diffuseSampler", this._diffuseTexture);
  42256. }
  42257. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42258. effect.setTexture("ambientSampler", this._ambientTexture);
  42259. }
  42260. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42261. effect.setTexture("opacitySampler", this._opacityTexture);
  42262. }
  42263. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42264. if (this._reflectionTexture.isCube) {
  42265. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  42266. }
  42267. else {
  42268. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  42269. }
  42270. }
  42271. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42272. effect.setTexture("emissiveSampler", this._emissiveTexture);
  42273. }
  42274. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42275. effect.setTexture("lightmapSampler", this._lightmapTexture);
  42276. }
  42277. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42278. effect.setTexture("specularSampler", this._specularTexture);
  42279. }
  42280. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42281. effect.setTexture("bumpSampler", this._bumpTexture);
  42282. }
  42283. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42284. var depth = 1.0;
  42285. if (this._refractionTexture.isCube) {
  42286. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  42287. }
  42288. else {
  42289. effect.setTexture("refraction2DSampler", this._refractionTexture);
  42290. }
  42291. }
  42292. }
  42293. // Clip plane
  42294. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  42295. // Colors
  42296. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  42297. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  42298. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  42299. }
  42300. if (mustRebind || !this.isFrozen) {
  42301. // Lights
  42302. if (scene.lightsEnabled && !this._disableLighting) {
  42303. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  42304. }
  42305. // View
  42306. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  42307. this.bindView(effect);
  42308. }
  42309. // Fog
  42310. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  42311. // Morph targets
  42312. if (defines.NUM_MORPH_INFLUENCERS) {
  42313. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  42314. }
  42315. // Log. depth
  42316. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  42317. // image processing
  42318. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  42319. this._imageProcessingConfiguration.bind(this._activeEffect);
  42320. }
  42321. }
  42322. this._uniformBuffer.update();
  42323. this._afterBind(mesh, this._activeEffect);
  42324. };
  42325. StandardMaterial.prototype.getAnimatables = function () {
  42326. var results = [];
  42327. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  42328. results.push(this._diffuseTexture);
  42329. }
  42330. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  42331. results.push(this._ambientTexture);
  42332. }
  42333. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  42334. results.push(this._opacityTexture);
  42335. }
  42336. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  42337. results.push(this._reflectionTexture);
  42338. }
  42339. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  42340. results.push(this._emissiveTexture);
  42341. }
  42342. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  42343. results.push(this._specularTexture);
  42344. }
  42345. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  42346. results.push(this._bumpTexture);
  42347. }
  42348. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  42349. results.push(this._lightmapTexture);
  42350. }
  42351. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  42352. results.push(this._refractionTexture);
  42353. }
  42354. return results;
  42355. };
  42356. StandardMaterial.prototype.getActiveTextures = function () {
  42357. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42358. if (this._diffuseTexture) {
  42359. activeTextures.push(this._diffuseTexture);
  42360. }
  42361. if (this._ambientTexture) {
  42362. activeTextures.push(this._ambientTexture);
  42363. }
  42364. if (this._opacityTexture) {
  42365. activeTextures.push(this._opacityTexture);
  42366. }
  42367. if (this._reflectionTexture) {
  42368. activeTextures.push(this._reflectionTexture);
  42369. }
  42370. if (this._emissiveTexture) {
  42371. activeTextures.push(this._emissiveTexture);
  42372. }
  42373. if (this._specularTexture) {
  42374. activeTextures.push(this._specularTexture);
  42375. }
  42376. if (this._bumpTexture) {
  42377. activeTextures.push(this._bumpTexture);
  42378. }
  42379. if (this._lightmapTexture) {
  42380. activeTextures.push(this._lightmapTexture);
  42381. }
  42382. if (this._refractionTexture) {
  42383. activeTextures.push(this._refractionTexture);
  42384. }
  42385. return activeTextures;
  42386. };
  42387. StandardMaterial.prototype.hasTexture = function (texture) {
  42388. if (_super.prototype.hasTexture.call(this, texture)) {
  42389. return true;
  42390. }
  42391. if (this._diffuseTexture === texture) {
  42392. return true;
  42393. }
  42394. if (this._ambientTexture === texture) {
  42395. return true;
  42396. }
  42397. if (this._opacityTexture === texture) {
  42398. return true;
  42399. }
  42400. if (this._reflectionTexture === texture) {
  42401. return true;
  42402. }
  42403. if (this._emissiveTexture === texture) {
  42404. return true;
  42405. }
  42406. if (this._specularTexture === texture) {
  42407. return true;
  42408. }
  42409. if (this._bumpTexture === texture) {
  42410. return true;
  42411. }
  42412. if (this._lightmapTexture === texture) {
  42413. return true;
  42414. }
  42415. if (this._refractionTexture === texture) {
  42416. return true;
  42417. }
  42418. return false;
  42419. };
  42420. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42421. if (forceDisposeTextures) {
  42422. if (this._diffuseTexture) {
  42423. this._diffuseTexture.dispose();
  42424. }
  42425. if (this._ambientTexture) {
  42426. this._ambientTexture.dispose();
  42427. }
  42428. if (this._opacityTexture) {
  42429. this._opacityTexture.dispose();
  42430. }
  42431. if (this._reflectionTexture) {
  42432. this._reflectionTexture.dispose();
  42433. }
  42434. if (this._emissiveTexture) {
  42435. this._emissiveTexture.dispose();
  42436. }
  42437. if (this._specularTexture) {
  42438. this._specularTexture.dispose();
  42439. }
  42440. if (this._bumpTexture) {
  42441. this._bumpTexture.dispose();
  42442. }
  42443. if (this._lightmapTexture) {
  42444. this._lightmapTexture.dispose();
  42445. }
  42446. if (this._refractionTexture) {
  42447. this._refractionTexture.dispose();
  42448. }
  42449. }
  42450. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42451. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42452. }
  42453. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  42454. };
  42455. StandardMaterial.prototype.clone = function (name) {
  42456. var _this = this;
  42457. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  42458. result.name = name;
  42459. result.id = name;
  42460. return result;
  42461. };
  42462. StandardMaterial.prototype.serialize = function () {
  42463. return BABYLON.SerializationHelper.Serialize(this);
  42464. };
  42465. // Statics
  42466. StandardMaterial.Parse = function (source, scene, rootUrl) {
  42467. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  42468. };
  42469. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  42470. get: function () {
  42471. return StandardMaterial._DiffuseTextureEnabled;
  42472. },
  42473. set: function (value) {
  42474. if (StandardMaterial._DiffuseTextureEnabled === value) {
  42475. return;
  42476. }
  42477. StandardMaterial._DiffuseTextureEnabled = value;
  42478. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42479. },
  42480. enumerable: true,
  42481. configurable: true
  42482. });
  42483. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  42484. get: function () {
  42485. return StandardMaterial._AmbientTextureEnabled;
  42486. },
  42487. set: function (value) {
  42488. if (StandardMaterial._AmbientTextureEnabled === value) {
  42489. return;
  42490. }
  42491. StandardMaterial._AmbientTextureEnabled = value;
  42492. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42493. },
  42494. enumerable: true,
  42495. configurable: true
  42496. });
  42497. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  42498. get: function () {
  42499. return StandardMaterial._OpacityTextureEnabled;
  42500. },
  42501. set: function (value) {
  42502. if (StandardMaterial._OpacityTextureEnabled === value) {
  42503. return;
  42504. }
  42505. StandardMaterial._OpacityTextureEnabled = value;
  42506. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42507. },
  42508. enumerable: true,
  42509. configurable: true
  42510. });
  42511. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  42512. get: function () {
  42513. return StandardMaterial._ReflectionTextureEnabled;
  42514. },
  42515. set: function (value) {
  42516. if (StandardMaterial._ReflectionTextureEnabled === value) {
  42517. return;
  42518. }
  42519. StandardMaterial._ReflectionTextureEnabled = value;
  42520. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42521. },
  42522. enumerable: true,
  42523. configurable: true
  42524. });
  42525. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  42526. get: function () {
  42527. return StandardMaterial._EmissiveTextureEnabled;
  42528. },
  42529. set: function (value) {
  42530. if (StandardMaterial._EmissiveTextureEnabled === value) {
  42531. return;
  42532. }
  42533. StandardMaterial._EmissiveTextureEnabled = value;
  42534. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42535. },
  42536. enumerable: true,
  42537. configurable: true
  42538. });
  42539. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  42540. get: function () {
  42541. return StandardMaterial._SpecularTextureEnabled;
  42542. },
  42543. set: function (value) {
  42544. if (StandardMaterial._SpecularTextureEnabled === value) {
  42545. return;
  42546. }
  42547. StandardMaterial._SpecularTextureEnabled = value;
  42548. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42549. },
  42550. enumerable: true,
  42551. configurable: true
  42552. });
  42553. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  42554. get: function () {
  42555. return StandardMaterial._BumpTextureEnabled;
  42556. },
  42557. set: function (value) {
  42558. if (StandardMaterial._BumpTextureEnabled === value) {
  42559. return;
  42560. }
  42561. StandardMaterial._BumpTextureEnabled = value;
  42562. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42563. },
  42564. enumerable: true,
  42565. configurable: true
  42566. });
  42567. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  42568. get: function () {
  42569. return StandardMaterial._LightmapTextureEnabled;
  42570. },
  42571. set: function (value) {
  42572. if (StandardMaterial._LightmapTextureEnabled === value) {
  42573. return;
  42574. }
  42575. StandardMaterial._LightmapTextureEnabled = value;
  42576. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42577. },
  42578. enumerable: true,
  42579. configurable: true
  42580. });
  42581. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  42582. get: function () {
  42583. return StandardMaterial._RefractionTextureEnabled;
  42584. },
  42585. set: function (value) {
  42586. if (StandardMaterial._RefractionTextureEnabled === value) {
  42587. return;
  42588. }
  42589. StandardMaterial._RefractionTextureEnabled = value;
  42590. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42591. },
  42592. enumerable: true,
  42593. configurable: true
  42594. });
  42595. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  42596. get: function () {
  42597. return StandardMaterial._ColorGradingTextureEnabled;
  42598. },
  42599. set: function (value) {
  42600. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  42601. return;
  42602. }
  42603. StandardMaterial._ColorGradingTextureEnabled = value;
  42604. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42605. },
  42606. enumerable: true,
  42607. configurable: true
  42608. });
  42609. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  42610. get: function () {
  42611. return StandardMaterial._FresnelEnabled;
  42612. },
  42613. set: function (value) {
  42614. if (StandardMaterial._FresnelEnabled === value) {
  42615. return;
  42616. }
  42617. StandardMaterial._FresnelEnabled = value;
  42618. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  42619. },
  42620. enumerable: true,
  42621. configurable: true
  42622. });
  42623. // Flags used to enable or disable a type of texture for all Standard Materials
  42624. StandardMaterial._DiffuseTextureEnabled = true;
  42625. StandardMaterial._AmbientTextureEnabled = true;
  42626. StandardMaterial._OpacityTextureEnabled = true;
  42627. StandardMaterial._ReflectionTextureEnabled = true;
  42628. StandardMaterial._EmissiveTextureEnabled = true;
  42629. StandardMaterial._SpecularTextureEnabled = true;
  42630. StandardMaterial._BumpTextureEnabled = true;
  42631. StandardMaterial._LightmapTextureEnabled = true;
  42632. StandardMaterial._RefractionTextureEnabled = true;
  42633. StandardMaterial._ColorGradingTextureEnabled = true;
  42634. StandardMaterial._FresnelEnabled = true;
  42635. __decorate([
  42636. BABYLON.serializeAsTexture("diffuseTexture")
  42637. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  42638. __decorate([
  42639. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42640. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  42641. __decorate([
  42642. BABYLON.serializeAsTexture("ambientTexture")
  42643. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  42644. __decorate([
  42645. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42646. ], StandardMaterial.prototype, "ambientTexture", void 0);
  42647. __decorate([
  42648. BABYLON.serializeAsTexture("opacityTexture")
  42649. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  42650. __decorate([
  42651. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42652. ], StandardMaterial.prototype, "opacityTexture", void 0);
  42653. __decorate([
  42654. BABYLON.serializeAsTexture("reflectionTexture")
  42655. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  42656. __decorate([
  42657. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42658. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  42659. __decorate([
  42660. BABYLON.serializeAsTexture("emissiveTexture")
  42661. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  42662. __decorate([
  42663. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42664. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  42665. __decorate([
  42666. BABYLON.serializeAsTexture("specularTexture")
  42667. ], StandardMaterial.prototype, "_specularTexture", void 0);
  42668. __decorate([
  42669. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42670. ], StandardMaterial.prototype, "specularTexture", void 0);
  42671. __decorate([
  42672. BABYLON.serializeAsTexture("bumpTexture")
  42673. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  42674. __decorate([
  42675. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42676. ], StandardMaterial.prototype, "bumpTexture", void 0);
  42677. __decorate([
  42678. BABYLON.serializeAsTexture("lightmapTexture")
  42679. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  42680. __decorate([
  42681. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42682. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  42683. __decorate([
  42684. BABYLON.serializeAsTexture("refractionTexture")
  42685. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  42686. __decorate([
  42687. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42688. ], StandardMaterial.prototype, "refractionTexture", void 0);
  42689. __decorate([
  42690. BABYLON.serializeAsColor3("ambient")
  42691. ], StandardMaterial.prototype, "ambientColor", void 0);
  42692. __decorate([
  42693. BABYLON.serializeAsColor3("diffuse")
  42694. ], StandardMaterial.prototype, "diffuseColor", void 0);
  42695. __decorate([
  42696. BABYLON.serializeAsColor3("specular")
  42697. ], StandardMaterial.prototype, "specularColor", void 0);
  42698. __decorate([
  42699. BABYLON.serializeAsColor3("emissive")
  42700. ], StandardMaterial.prototype, "emissiveColor", void 0);
  42701. __decorate([
  42702. BABYLON.serialize()
  42703. ], StandardMaterial.prototype, "specularPower", void 0);
  42704. __decorate([
  42705. BABYLON.serialize("useAlphaFromDiffuseTexture")
  42706. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  42707. __decorate([
  42708. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42709. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  42710. __decorate([
  42711. BABYLON.serialize("useEmissiveAsIllumination")
  42712. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  42713. __decorate([
  42714. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42715. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  42716. __decorate([
  42717. BABYLON.serialize("linkEmissiveWithDiffuse")
  42718. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  42719. __decorate([
  42720. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42721. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  42722. __decorate([
  42723. BABYLON.serialize("useSpecularOverAlpha")
  42724. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  42725. __decorate([
  42726. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42727. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  42728. __decorate([
  42729. BABYLON.serialize("useReflectionOverAlpha")
  42730. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  42731. __decorate([
  42732. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42733. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  42734. __decorate([
  42735. BABYLON.serialize("disableLighting")
  42736. ], StandardMaterial.prototype, "_disableLighting", void 0);
  42737. __decorate([
  42738. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42739. ], StandardMaterial.prototype, "disableLighting", void 0);
  42740. __decorate([
  42741. BABYLON.serialize("useObjectSpaceNormalMap")
  42742. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  42743. __decorate([
  42744. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42745. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  42746. __decorate([
  42747. BABYLON.serialize("useParallax")
  42748. ], StandardMaterial.prototype, "_useParallax", void 0);
  42749. __decorate([
  42750. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42751. ], StandardMaterial.prototype, "useParallax", void 0);
  42752. __decorate([
  42753. BABYLON.serialize("useParallaxOcclusion")
  42754. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  42755. __decorate([
  42756. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42757. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  42758. __decorate([
  42759. BABYLON.serialize()
  42760. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  42761. __decorate([
  42762. BABYLON.serialize("roughness")
  42763. ], StandardMaterial.prototype, "_roughness", void 0);
  42764. __decorate([
  42765. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42766. ], StandardMaterial.prototype, "roughness", void 0);
  42767. __decorate([
  42768. BABYLON.serialize()
  42769. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  42770. __decorate([
  42771. BABYLON.serialize()
  42772. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  42773. __decorate([
  42774. BABYLON.serialize()
  42775. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  42776. __decorate([
  42777. BABYLON.serialize("useLightmapAsShadowmap")
  42778. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  42779. __decorate([
  42780. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42781. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  42782. __decorate([
  42783. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  42784. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  42785. __decorate([
  42786. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42787. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  42788. __decorate([
  42789. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  42790. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  42791. __decorate([
  42792. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  42793. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  42794. __decorate([
  42795. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  42796. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  42797. __decorate([
  42798. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42799. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  42800. __decorate([
  42801. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  42802. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  42803. __decorate([
  42804. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42805. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  42806. __decorate([
  42807. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  42808. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  42809. __decorate([
  42810. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42811. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  42812. __decorate([
  42813. BABYLON.serialize("useReflectionFresnelFromSpecular")
  42814. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  42815. __decorate([
  42816. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42817. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  42818. __decorate([
  42819. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  42820. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  42821. __decorate([
  42822. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42823. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  42824. __decorate([
  42825. BABYLON.serialize("maxSimultaneousLights")
  42826. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  42827. __decorate([
  42828. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42829. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  42830. __decorate([
  42831. BABYLON.serialize("invertNormalMapX")
  42832. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  42833. __decorate([
  42834. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42835. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  42836. __decorate([
  42837. BABYLON.serialize("invertNormalMapY")
  42838. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  42839. __decorate([
  42840. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42841. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  42842. __decorate([
  42843. BABYLON.serialize("twoSidedLighting")
  42844. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  42845. __decorate([
  42846. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42847. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  42848. __decorate([
  42849. BABYLON.serialize()
  42850. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  42851. return StandardMaterial;
  42852. }(BABYLON.PushMaterial));
  42853. BABYLON.StandardMaterial = StandardMaterial;
  42854. })(BABYLON || (BABYLON = {}));
  42855. //# sourceMappingURL=babylon.standardMaterial.js.map
  42856. var BABYLON;
  42857. (function (BABYLON) {
  42858. /**
  42859. * Class representing spherical polynomial coefficients to the 3rd degree
  42860. */
  42861. var SphericalPolynomial = /** @class */ (function () {
  42862. function SphericalPolynomial() {
  42863. /**
  42864. * The x coefficients of the spherical polynomial
  42865. */
  42866. this.x = BABYLON.Vector3.Zero();
  42867. /**
  42868. * The y coefficients of the spherical polynomial
  42869. */
  42870. this.y = BABYLON.Vector3.Zero();
  42871. /**
  42872. * The z coefficients of the spherical polynomial
  42873. */
  42874. this.z = BABYLON.Vector3.Zero();
  42875. /**
  42876. * The xx coefficients of the spherical polynomial
  42877. */
  42878. this.xx = BABYLON.Vector3.Zero();
  42879. /**
  42880. * The yy coefficients of the spherical polynomial
  42881. */
  42882. this.yy = BABYLON.Vector3.Zero();
  42883. /**
  42884. * The zz coefficients of the spherical polynomial
  42885. */
  42886. this.zz = BABYLON.Vector3.Zero();
  42887. /**
  42888. * The xy coefficients of the spherical polynomial
  42889. */
  42890. this.xy = BABYLON.Vector3.Zero();
  42891. /**
  42892. * The yz coefficients of the spherical polynomial
  42893. */
  42894. this.yz = BABYLON.Vector3.Zero();
  42895. /**
  42896. * The zx coefficients of the spherical polynomial
  42897. */
  42898. this.zx = BABYLON.Vector3.Zero();
  42899. }
  42900. /**
  42901. * Adds an ambient color to the spherical polynomial
  42902. * @param color the color to add
  42903. */
  42904. SphericalPolynomial.prototype.addAmbient = function (color) {
  42905. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  42906. this.xx = this.xx.add(colorVector);
  42907. this.yy = this.yy.add(colorVector);
  42908. this.zz = this.zz.add(colorVector);
  42909. };
  42910. /**
  42911. * Scales the spherical polynomial by the given amount
  42912. * @param scale the amount to scale
  42913. */
  42914. SphericalPolynomial.prototype.scale = function (scale) {
  42915. this.x = this.x.scale(scale);
  42916. this.y = this.y.scale(scale);
  42917. this.z = this.z.scale(scale);
  42918. this.xx = this.xx.scale(scale);
  42919. this.yy = this.yy.scale(scale);
  42920. this.zz = this.zz.scale(scale);
  42921. this.yz = this.yz.scale(scale);
  42922. this.zx = this.zx.scale(scale);
  42923. this.xy = this.xy.scale(scale);
  42924. };
  42925. /**
  42926. * Gets the spherical polynomial from harmonics
  42927. * @param harmonics the spherical harmonics
  42928. * @returns the spherical polynomial
  42929. */
  42930. SphericalPolynomial.FromHarmonics = function (harmonics) {
  42931. var result = new SphericalPolynomial();
  42932. result.x = harmonics.l11.scale(1.02333);
  42933. result.y = harmonics.l1_1.scale(1.02333);
  42934. result.z = harmonics.l10.scale(1.02333);
  42935. result.xx = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).add(harmonics.lL22.scale(0.429043));
  42936. result.yy = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).subtract(harmonics.lL22.scale(0.429043));
  42937. result.zz = harmonics.l00.scale(0.886277).add(harmonics.l20.scale(0.495417));
  42938. result.yz = harmonics.l2_1.scale(0.858086);
  42939. result.zx = harmonics.l21.scale(0.858086);
  42940. result.xy = harmonics.l2_2.scale(0.858086);
  42941. result.scale(1.0 / Math.PI);
  42942. return result;
  42943. };
  42944. /**
  42945. * Constructs a spherical polynomial from an array.
  42946. * @param data defines the 9x3 coefficients (x, y, z, xx, yy, zz, yz, zx, xy)
  42947. * @returns the spherical polynomial
  42948. */
  42949. SphericalPolynomial.FromArray = function (data) {
  42950. var sp = new SphericalPolynomial();
  42951. BABYLON.Vector3.FromArrayToRef(data[0], 0, sp.x);
  42952. BABYLON.Vector3.FromArrayToRef(data[1], 0, sp.y);
  42953. BABYLON.Vector3.FromArrayToRef(data[2], 0, sp.z);
  42954. BABYLON.Vector3.FromArrayToRef(data[3], 0, sp.xx);
  42955. BABYLON.Vector3.FromArrayToRef(data[4], 0, sp.yy);
  42956. BABYLON.Vector3.FromArrayToRef(data[5], 0, sp.zz);
  42957. BABYLON.Vector3.FromArrayToRef(data[6], 0, sp.yz);
  42958. BABYLON.Vector3.FromArrayToRef(data[7], 0, sp.zx);
  42959. BABYLON.Vector3.FromArrayToRef(data[8], 0, sp.xy);
  42960. return sp;
  42961. };
  42962. return SphericalPolynomial;
  42963. }());
  42964. BABYLON.SphericalPolynomial = SphericalPolynomial;
  42965. /**
  42966. * Class representing spherical harmonics coefficients to the 3rd degree
  42967. */
  42968. var SphericalHarmonics = /** @class */ (function () {
  42969. function SphericalHarmonics() {
  42970. /**
  42971. * The l0,0 coefficients of the spherical harmonics
  42972. */
  42973. this.l00 = BABYLON.Vector3.Zero();
  42974. /**
  42975. * The l1,-1 coefficients of the spherical harmonics
  42976. */
  42977. this.l1_1 = BABYLON.Vector3.Zero();
  42978. /**
  42979. * The l1,0 coefficients of the spherical harmonics
  42980. */
  42981. this.l10 = BABYLON.Vector3.Zero();
  42982. /**
  42983. * The l1,1 coefficients of the spherical harmonics
  42984. */
  42985. this.l11 = BABYLON.Vector3.Zero();
  42986. /**
  42987. * The l2,-2 coefficients of the spherical harmonics
  42988. */
  42989. this.l2_2 = BABYLON.Vector3.Zero();
  42990. /**
  42991. * The l2,-1 coefficients of the spherical harmonics
  42992. */
  42993. this.l2_1 = BABYLON.Vector3.Zero();
  42994. /**
  42995. * The l2,0 coefficients of the spherical harmonics
  42996. */
  42997. this.l20 = BABYLON.Vector3.Zero();
  42998. /**
  42999. * The l2,1 coefficients of the spherical harmonics
  43000. */
  43001. this.l21 = BABYLON.Vector3.Zero();
  43002. /**
  43003. * The l2,2 coefficients of the spherical harmonics
  43004. */
  43005. this.lL22 = BABYLON.Vector3.Zero();
  43006. }
  43007. /**
  43008. * Adds a light to the spherical harmonics
  43009. * @param direction the direction of the light
  43010. * @param color the color of the light
  43011. * @param deltaSolidAngle the delta solid angle of the light
  43012. */
  43013. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  43014. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  43015. var c = colorVector.scale(deltaSolidAngle);
  43016. this.l00 = this.l00.add(c.scale(0.282095));
  43017. this.l1_1 = this.l1_1.add(c.scale(0.488603 * direction.y));
  43018. this.l10 = this.l10.add(c.scale(0.488603 * direction.z));
  43019. this.l11 = this.l11.add(c.scale(0.488603 * direction.x));
  43020. this.l2_2 = this.l2_2.add(c.scale(1.092548 * direction.x * direction.y));
  43021. this.l2_1 = this.l2_1.add(c.scale(1.092548 * direction.y * direction.z));
  43022. this.l21 = this.l21.add(c.scale(1.092548 * direction.x * direction.z));
  43023. this.l20 = this.l20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  43024. this.lL22 = this.lL22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  43025. };
  43026. /**
  43027. * Scales the spherical harmonics by the given amount
  43028. * @param scale the amount to scale
  43029. */
  43030. SphericalHarmonics.prototype.scale = function (scale) {
  43031. this.l00 = this.l00.scale(scale);
  43032. this.l1_1 = this.l1_1.scale(scale);
  43033. this.l10 = this.l10.scale(scale);
  43034. this.l11 = this.l11.scale(scale);
  43035. this.l2_2 = this.l2_2.scale(scale);
  43036. this.l2_1 = this.l2_1.scale(scale);
  43037. this.l20 = this.l20.scale(scale);
  43038. this.l21 = this.l21.scale(scale);
  43039. this.lL22 = this.lL22.scale(scale);
  43040. };
  43041. /**
  43042. * Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  43043. *
  43044. * ```
  43045. * E_lm = A_l * L_lm
  43046. * ```
  43047. *
  43048. * In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  43049. * This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  43050. * the scaling factors are given in equation 9.
  43051. */
  43052. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  43053. // Constant (Band 0)
  43054. this.l00 = this.l00.scale(3.141593);
  43055. // Linear (Band 1)
  43056. this.l1_1 = this.l1_1.scale(2.094395);
  43057. this.l10 = this.l10.scale(2.094395);
  43058. this.l11 = this.l11.scale(2.094395);
  43059. // Quadratic (Band 2)
  43060. this.l2_2 = this.l2_2.scale(0.785398);
  43061. this.l2_1 = this.l2_1.scale(0.785398);
  43062. this.l20 = this.l20.scale(0.785398);
  43063. this.l21 = this.l21.scale(0.785398);
  43064. this.lL22 = this.lL22.scale(0.785398);
  43065. };
  43066. /**
  43067. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  43068. *
  43069. * ```
  43070. * L = (1/pi) * E * rho
  43071. * ```
  43072. *
  43073. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  43074. */
  43075. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  43076. this.scale(1.0 / Math.PI);
  43077. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  43078. // (The pixel shader must apply albedo after texture fetches, etc).
  43079. };
  43080. /**
  43081. * Gets the spherical harmonics from polynomial
  43082. * @param polynomial the spherical polynomial
  43083. * @returns the spherical harmonics
  43084. */
  43085. SphericalHarmonics.FromPolynomial = function (polynomial) {
  43086. var result = new SphericalHarmonics();
  43087. result.l00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  43088. result.l1_1 = polynomial.y.scale(0.977204);
  43089. result.l10 = polynomial.z.scale(0.977204);
  43090. result.l11 = polynomial.x.scale(0.977204);
  43091. result.l2_2 = polynomial.xy.scale(1.16538);
  43092. result.l2_1 = polynomial.yz.scale(1.16538);
  43093. result.l20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  43094. result.l21 = polynomial.zx.scale(1.16538);
  43095. result.lL22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  43096. result.scale(Math.PI);
  43097. return result;
  43098. };
  43099. /**
  43100. * Constructs a spherical harmonics from an array.
  43101. * @param data defines the 9x3 coefficients (l00, l1-1, l10, l11, l2-2, l2-1, l20, l21, l22)
  43102. * @returns the spherical harmonics
  43103. */
  43104. SphericalHarmonics.FromArray = function (data) {
  43105. var sh = new SphericalHarmonics();
  43106. BABYLON.Vector3.FromArrayToRef(data[0], 0, sh.l00);
  43107. BABYLON.Vector3.FromArrayToRef(data[1], 0, sh.l1_1);
  43108. BABYLON.Vector3.FromArrayToRef(data[2], 0, sh.l10);
  43109. BABYLON.Vector3.FromArrayToRef(data[3], 0, sh.l11);
  43110. BABYLON.Vector3.FromArrayToRef(data[4], 0, sh.l2_2);
  43111. BABYLON.Vector3.FromArrayToRef(data[5], 0, sh.l2_1);
  43112. BABYLON.Vector3.FromArrayToRef(data[6], 0, sh.l20);
  43113. BABYLON.Vector3.FromArrayToRef(data[7], 0, sh.l21);
  43114. BABYLON.Vector3.FromArrayToRef(data[8], 0, sh.lL22);
  43115. return sh;
  43116. };
  43117. return SphericalHarmonics;
  43118. }());
  43119. BABYLON.SphericalHarmonics = SphericalHarmonics;
  43120. })(BABYLON || (BABYLON = {}));
  43121. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  43122. var BABYLON;
  43123. (function (BABYLON) {
  43124. var FileFaceOrientation = /** @class */ (function () {
  43125. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  43126. this.name = name;
  43127. this.worldAxisForNormal = worldAxisForNormal;
  43128. this.worldAxisForFileX = worldAxisForFileX;
  43129. this.worldAxisForFileY = worldAxisForFileY;
  43130. }
  43131. return FileFaceOrientation;
  43132. }());
  43133. ;
  43134. /**
  43135. * Helper class dealing with the extraction of spherical polynomial dataArray
  43136. * from a cube map.
  43137. */
  43138. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  43139. function CubeMapToSphericalPolynomialTools() {
  43140. }
  43141. /**
  43142. * Converts a texture to the according Spherical Polynomial data.
  43143. * This extracts the first 3 orders only as they are the only one used in the lighting.
  43144. *
  43145. * @param texture The texture to extract the information from.
  43146. * @return The Spherical Polynomial data.
  43147. */
  43148. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  43149. if (!texture.isCube) {
  43150. // Only supports cube Textures currently.
  43151. return null;
  43152. }
  43153. var size = texture.getSize().width;
  43154. var right = texture.readPixels(0);
  43155. var left = texture.readPixels(1);
  43156. var up;
  43157. var down;
  43158. if (texture.isRenderTarget) {
  43159. up = texture.readPixels(3);
  43160. down = texture.readPixels(2);
  43161. }
  43162. else {
  43163. up = texture.readPixels(2);
  43164. down = texture.readPixels(3);
  43165. }
  43166. var front = texture.readPixels(4);
  43167. var back = texture.readPixels(5);
  43168. var gammaSpace = texture.gammaSpace;
  43169. // Always read as RGBA.
  43170. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  43171. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  43172. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  43173. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  43174. }
  43175. var cubeInfo = {
  43176. size: size,
  43177. right: right,
  43178. left: left,
  43179. up: up,
  43180. down: down,
  43181. front: front,
  43182. back: back,
  43183. format: format,
  43184. type: type,
  43185. gammaSpace: gammaSpace,
  43186. };
  43187. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  43188. };
  43189. /**
  43190. * Converts a cubemap to the according Spherical Polynomial data.
  43191. * This extracts the first 3 orders only as they are the only one used in the lighting.
  43192. *
  43193. * @param cubeInfo The Cube map to extract the information from.
  43194. * @return The Spherical Polynomial data.
  43195. */
  43196. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  43197. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  43198. var totalSolidAngle = 0.0;
  43199. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  43200. var du = 2.0 / cubeInfo.size;
  43201. var dv = du;
  43202. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  43203. var minUV = du * 0.5 - 1.0;
  43204. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  43205. var fileFace = this.FileFaces[faceIndex];
  43206. var dataArray = cubeInfo[fileFace.name];
  43207. var v = minUV;
  43208. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  43209. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  43210. // Because SP is still linear, so summation is fine in that basis.
  43211. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  43212. for (var y = 0; y < cubeInfo.size; y++) {
  43213. var u = minUV;
  43214. for (var x = 0; x < cubeInfo.size; x++) {
  43215. // World direction (not normalised)
  43216. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  43217. worldDirection.normalize();
  43218. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  43219. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  43220. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  43221. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  43222. // Handle Integer types.
  43223. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  43224. r /= 255;
  43225. g /= 255;
  43226. b /= 255;
  43227. }
  43228. // Handle Gamma space textures.
  43229. if (cubeInfo.gammaSpace) {
  43230. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  43231. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  43232. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  43233. }
  43234. var color = new BABYLON.Color3(r, g, b);
  43235. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  43236. totalSolidAngle += deltaSolidAngle;
  43237. u += du;
  43238. }
  43239. v += dv;
  43240. }
  43241. }
  43242. // Solid angle for entire sphere is 4*pi
  43243. var sphereSolidAngle = 4.0 * Math.PI;
  43244. // Adjust the solid angle to allow for how many faces we processed.
  43245. var facesProcessed = 6.0;
  43246. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  43247. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  43248. // This is needed because the numerical integration over the cube uses a
  43249. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  43250. // and also to compensate for accumulative error due to float precision in the summation.
  43251. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  43252. sphericalHarmonics.scale(correctionFactor);
  43253. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  43254. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  43255. return BABYLON.SphericalPolynomial.FromHarmonics(sphericalHarmonics);
  43256. };
  43257. CubeMapToSphericalPolynomialTools.FileFaces = [
  43258. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  43259. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  43260. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  43261. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  43262. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  43263. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  43264. ];
  43265. return CubeMapToSphericalPolynomialTools;
  43266. }());
  43267. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  43268. })(BABYLON || (BABYLON = {}));
  43269. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  43270. var BABYLON;
  43271. (function (BABYLON) {
  43272. /**
  43273. * Manages the defines for the PBR Material.
  43274. * @hiddenChildren
  43275. */
  43276. var PBRMaterialDefines = /** @class */ (function (_super) {
  43277. __extends(PBRMaterialDefines, _super);
  43278. /**
  43279. * Initializes the PBR Material defines.
  43280. */
  43281. function PBRMaterialDefines() {
  43282. var _this = _super.call(this) || this;
  43283. _this.PBR = true;
  43284. _this.MAINUV1 = false;
  43285. _this.MAINUV2 = false;
  43286. _this.UV1 = false;
  43287. _this.UV2 = false;
  43288. _this.ALBEDO = false;
  43289. _this.ALBEDODIRECTUV = 0;
  43290. _this.VERTEXCOLOR = false;
  43291. _this.AMBIENT = false;
  43292. _this.AMBIENTDIRECTUV = 0;
  43293. _this.AMBIENTINGRAYSCALE = false;
  43294. _this.OPACITY = false;
  43295. _this.VERTEXALPHA = false;
  43296. _this.OPACITYDIRECTUV = 0;
  43297. _this.OPACITYRGB = false;
  43298. _this.ALPHATEST = false;
  43299. _this.DEPTHPREPASS = false;
  43300. _this.ALPHABLEND = false;
  43301. _this.ALPHAFROMALBEDO = false;
  43302. _this.ALPHATESTVALUE = "0.5";
  43303. _this.SPECULAROVERALPHA = false;
  43304. _this.RADIANCEOVERALPHA = false;
  43305. _this.ALPHAFRESNEL = false;
  43306. _this.LINEARALPHAFRESNEL = false;
  43307. _this.PREMULTIPLYALPHA = false;
  43308. _this.EMISSIVE = false;
  43309. _this.EMISSIVEDIRECTUV = 0;
  43310. _this.REFLECTIVITY = false;
  43311. _this.REFLECTIVITYDIRECTUV = 0;
  43312. _this.SPECULARTERM = false;
  43313. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  43314. _this.MICROSURFACEAUTOMATIC = false;
  43315. _this.LODBASEDMICROSFURACE = false;
  43316. _this.MICROSURFACEMAP = false;
  43317. _this.MICROSURFACEMAPDIRECTUV = 0;
  43318. _this.METALLICWORKFLOW = false;
  43319. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  43320. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  43321. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  43322. _this.AOSTOREINMETALMAPRED = false;
  43323. _this.ENVIRONMENTBRDF = false;
  43324. _this.NORMAL = false;
  43325. _this.TANGENT = false;
  43326. _this.BUMP = false;
  43327. _this.BUMPDIRECTUV = 0;
  43328. _this.OBJECTSPACE_NORMALMAP = false;
  43329. _this.PARALLAX = false;
  43330. _this.PARALLAXOCCLUSION = false;
  43331. _this.NORMALXYSCALE = true;
  43332. _this.LIGHTMAP = false;
  43333. _this.LIGHTMAPDIRECTUV = 0;
  43334. _this.USELIGHTMAPASSHADOWMAP = false;
  43335. _this.GAMMALIGHTMAP = false;
  43336. _this.REFLECTION = false;
  43337. _this.REFLECTIONMAP_3D = false;
  43338. _this.REFLECTIONMAP_SPHERICAL = false;
  43339. _this.REFLECTIONMAP_PLANAR = false;
  43340. _this.REFLECTIONMAP_CUBIC = false;
  43341. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43342. _this.REFLECTIONMAP_PROJECTION = false;
  43343. _this.REFLECTIONMAP_SKYBOX = false;
  43344. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  43345. _this.REFLECTIONMAP_EXPLICIT = false;
  43346. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43347. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43348. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43349. _this.INVERTCUBICMAP = false;
  43350. _this.USESPHERICALFROMREFLECTIONMAP = false;
  43351. _this.USESPHERICALINVERTEX = false;
  43352. _this.REFLECTIONMAP_OPPOSITEZ = false;
  43353. _this.LODINREFLECTIONALPHA = false;
  43354. _this.GAMMAREFLECTION = false;
  43355. _this.RGBDREFLECTION = false;
  43356. _this.RADIANCEOCCLUSION = false;
  43357. _this.HORIZONOCCLUSION = false;
  43358. _this.REFRACTION = false;
  43359. _this.REFRACTIONMAP_3D = false;
  43360. _this.REFRACTIONMAP_OPPOSITEZ = false;
  43361. _this.LODINREFRACTIONALPHA = false;
  43362. _this.GAMMAREFRACTION = false;
  43363. _this.RGBDREFRACTION = false;
  43364. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  43365. _this.INSTANCES = false;
  43366. _this.NUM_BONE_INFLUENCERS = 0;
  43367. _this.BonesPerMesh = 0;
  43368. _this.NONUNIFORMSCALING = false;
  43369. _this.MORPHTARGETS = false;
  43370. _this.MORPHTARGETS_NORMAL = false;
  43371. _this.MORPHTARGETS_TANGENT = false;
  43372. _this.NUM_MORPH_INFLUENCERS = 0;
  43373. _this.IMAGEPROCESSING = false;
  43374. _this.VIGNETTE = false;
  43375. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43376. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43377. _this.TONEMAPPING = false;
  43378. _this.TONEMAPPING_ACES = false;
  43379. _this.CONTRAST = false;
  43380. _this.COLORCURVES = false;
  43381. _this.COLORGRADING = false;
  43382. _this.COLORGRADING3D = false;
  43383. _this.SAMPLER3DGREENDEPTH = false;
  43384. _this.SAMPLER3DBGRMAP = false;
  43385. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43386. _this.EXPOSURE = false;
  43387. _this.USEPHYSICALLIGHTFALLOFF = false;
  43388. _this.USEGLTFLIGHTFALLOFF = false;
  43389. _this.TWOSIDEDLIGHTING = false;
  43390. _this.SHADOWFLOAT = false;
  43391. _this.CLIPPLANE = false;
  43392. _this.CLIPPLANE2 = false;
  43393. _this.CLIPPLANE3 = false;
  43394. _this.CLIPPLANE4 = false;
  43395. _this.POINTSIZE = false;
  43396. _this.FOG = false;
  43397. _this.LOGARITHMICDEPTH = false;
  43398. _this.FORCENORMALFORWARD = false;
  43399. _this.SPECULARAA = false;
  43400. _this.UNLIT = false;
  43401. _this.rebuild();
  43402. return _this;
  43403. }
  43404. /**
  43405. * Resets the PBR Material defines.
  43406. */
  43407. PBRMaterialDefines.prototype.reset = function () {
  43408. _super.prototype.reset.call(this);
  43409. this.ALPHATESTVALUE = "0.5";
  43410. this.PBR = true;
  43411. };
  43412. return PBRMaterialDefines;
  43413. }(BABYLON.MaterialDefines));
  43414. /**
  43415. * The Physically based material base class of BJS.
  43416. *
  43417. * This offers the main features of a standard PBR material.
  43418. * For more information, please refer to the documentation :
  43419. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  43420. */
  43421. var PBRBaseMaterial = /** @class */ (function (_super) {
  43422. __extends(PBRBaseMaterial, _super);
  43423. /**
  43424. * Instantiates a new PBRMaterial instance.
  43425. *
  43426. * @param name The material name
  43427. * @param scene The scene the material will be use in.
  43428. */
  43429. function PBRBaseMaterial(name, scene) {
  43430. var _this = _super.call(this, name, scene) || this;
  43431. /**
  43432. * Intensity of the direct lights e.g. the four lights available in your scene.
  43433. * This impacts both the direct diffuse and specular highlights.
  43434. */
  43435. _this._directIntensity = 1.0;
  43436. /**
  43437. * Intensity of the emissive part of the material.
  43438. * This helps controlling the emissive effect without modifying the emissive color.
  43439. */
  43440. _this._emissiveIntensity = 1.0;
  43441. /**
  43442. * Intensity of the environment e.g. how much the environment will light the object
  43443. * either through harmonics for rough material or through the refelction for shiny ones.
  43444. */
  43445. _this._environmentIntensity = 1.0;
  43446. /**
  43447. * This is a special control allowing the reduction of the specular highlights coming from the
  43448. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  43449. */
  43450. _this._specularIntensity = 1.0;
  43451. /**
  43452. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  43453. */
  43454. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  43455. /**
  43456. * Debug Control allowing disabling the bump map on this material.
  43457. */
  43458. _this._disableBumpMap = false;
  43459. /**
  43460. * AKA Occlusion Texture Intensity in other nomenclature.
  43461. */
  43462. _this._ambientTextureStrength = 1.0;
  43463. /**
  43464. * Defines how much the AO map is occluding the analytical lights (point spot...).
  43465. * 1 means it completely occludes it
  43466. * 0 mean it has no impact
  43467. */
  43468. _this._ambientTextureImpactOnAnalyticalLights = BABYLON.PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
  43469. /**
  43470. * The color of a material in ambient lighting.
  43471. */
  43472. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  43473. /**
  43474. * AKA Diffuse Color in other nomenclature.
  43475. */
  43476. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  43477. /**
  43478. * AKA Specular Color in other nomenclature.
  43479. */
  43480. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  43481. /**
  43482. * The color applied when light is reflected from a material.
  43483. */
  43484. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  43485. /**
  43486. * The color applied when light is emitted from a material.
  43487. */
  43488. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  43489. /**
  43490. * AKA Glossiness in other nomenclature.
  43491. */
  43492. _this._microSurface = 0.9;
  43493. /**
  43494. * source material index of refraction (IOR)' / 'destination material IOR.
  43495. */
  43496. _this._indexOfRefraction = 0.66;
  43497. /**
  43498. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  43499. */
  43500. _this._invertRefractionY = false;
  43501. /**
  43502. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  43503. * Materials half opaque for instance using refraction could benefit from this control.
  43504. */
  43505. _this._linkRefractionWithTransparency = false;
  43506. /**
  43507. * Specifies that the material will use the light map as a show map.
  43508. */
  43509. _this._useLightmapAsShadowmap = false;
  43510. /**
  43511. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  43512. * makes the reflect vector face the model (under horizon).
  43513. */
  43514. _this._useHorizonOcclusion = true;
  43515. /**
  43516. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  43517. * too much the area relying on ambient texture to define their ambient occlusion.
  43518. */
  43519. _this._useRadianceOcclusion = true;
  43520. /**
  43521. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  43522. */
  43523. _this._useAlphaFromAlbedoTexture = false;
  43524. /**
  43525. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  43526. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  43527. */
  43528. _this._useSpecularOverAlpha = true;
  43529. /**
  43530. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  43531. */
  43532. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  43533. /**
  43534. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  43535. */
  43536. _this._useRoughnessFromMetallicTextureAlpha = true;
  43537. /**
  43538. * Specifies if the metallic texture contains the roughness information in its green channel.
  43539. */
  43540. _this._useRoughnessFromMetallicTextureGreen = false;
  43541. /**
  43542. * Specifies if the metallic texture contains the metallness information in its blue channel.
  43543. */
  43544. _this._useMetallnessFromMetallicTextureBlue = false;
  43545. /**
  43546. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  43547. */
  43548. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  43549. /**
  43550. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  43551. */
  43552. _this._useAmbientInGrayScale = false;
  43553. /**
  43554. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  43555. * The material will try to infer what glossiness each pixel should be.
  43556. */
  43557. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  43558. /**
  43559. * Defines the falloff type used in this material.
  43560. * It by default is Physical.
  43561. */
  43562. _this._lightFalloff = PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  43563. /**
  43564. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  43565. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  43566. */
  43567. _this._useRadianceOverAlpha = true;
  43568. /**
  43569. * Allows using an object space normal map (instead of tangent space).
  43570. */
  43571. _this._useObjectSpaceNormalMap = false;
  43572. /**
  43573. * Allows using the bump map in parallax mode.
  43574. */
  43575. _this._useParallax = false;
  43576. /**
  43577. * Allows using the bump map in parallax occlusion mode.
  43578. */
  43579. _this._useParallaxOcclusion = false;
  43580. /**
  43581. * Controls the scale bias of the parallax mode.
  43582. */
  43583. _this._parallaxScaleBias = 0.05;
  43584. /**
  43585. * If sets to true, disables all the lights affecting the material.
  43586. */
  43587. _this._disableLighting = false;
  43588. /**
  43589. * Number of Simultaneous lights allowed on the material.
  43590. */
  43591. _this._maxSimultaneousLights = 4;
  43592. /**
  43593. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  43594. */
  43595. _this._invertNormalMapX = false;
  43596. /**
  43597. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  43598. */
  43599. _this._invertNormalMapY = false;
  43600. /**
  43601. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  43602. */
  43603. _this._twoSidedLighting = false;
  43604. /**
  43605. * Defines the alpha limits in alpha test mode.
  43606. */
  43607. _this._alphaCutOff = 0.4;
  43608. /**
  43609. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  43610. */
  43611. _this._forceAlphaTest = false;
  43612. /**
  43613. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43614. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  43615. */
  43616. _this._useAlphaFresnel = false;
  43617. /**
  43618. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43619. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  43620. */
  43621. _this._useLinearAlphaFresnel = false;
  43622. /**
  43623. * The transparency mode of the material.
  43624. */
  43625. _this._transparencyMode = null;
  43626. /**
  43627. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  43628. * from cos thetav and roughness:
  43629. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  43630. */
  43631. _this._environmentBRDFTexture = null;
  43632. /**
  43633. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  43634. */
  43635. _this._forceIrradianceInFragment = false;
  43636. /**
  43637. * Force normal to face away from face.
  43638. */
  43639. _this._forceNormalForward = false;
  43640. /**
  43641. * Enables specular anti aliasing in the PBR shader.
  43642. * It will both interacts on the Geometry for analytical and IBL lighting.
  43643. * It also prefilter the roughness map based on the bump values.
  43644. */
  43645. _this._enableSpecularAntiAliasing = false;
  43646. /**
  43647. * Stores the available render targets.
  43648. */
  43649. _this._renderTargets = new BABYLON.SmartArray(16);
  43650. /**
  43651. * Sets the global ambient color for the material used in lighting calculations.
  43652. */
  43653. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43654. /**
  43655. * If set to true, no lighting calculations will be applied.
  43656. */
  43657. _this._unlit = false;
  43658. // Setup the default processing configuration to the scene.
  43659. _this._attachImageProcessingConfiguration(null);
  43660. _this.getRenderTargetTextures = function () {
  43661. _this._renderTargets.reset();
  43662. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43663. _this._renderTargets.push(_this._reflectionTexture);
  43664. }
  43665. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43666. _this._renderTargets.push(_this._refractionTexture);
  43667. }
  43668. return _this._renderTargets;
  43669. };
  43670. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  43671. return _this;
  43672. }
  43673. /**
  43674. * Attaches a new image processing configuration to the PBR Material.
  43675. * @param configuration
  43676. */
  43677. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43678. var _this = this;
  43679. if (configuration === this._imageProcessingConfiguration) {
  43680. return;
  43681. }
  43682. // Detaches observer.
  43683. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43684. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43685. }
  43686. // Pick the scene configuration if needed.
  43687. if (!configuration) {
  43688. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43689. }
  43690. else {
  43691. this._imageProcessingConfiguration = configuration;
  43692. }
  43693. // Attaches observer.
  43694. if (this._imageProcessingConfiguration) {
  43695. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43696. _this._markAllSubMeshesAsImageProcessingDirty();
  43697. });
  43698. }
  43699. };
  43700. Object.defineProperty(PBRBaseMaterial.prototype, "hasRenderTargetTextures", {
  43701. /**
  43702. * Gets a boolean indicating that current material needs to register RTT
  43703. */
  43704. get: function () {
  43705. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  43706. return true;
  43707. }
  43708. if (BABYLON.StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
  43709. return true;
  43710. }
  43711. return false;
  43712. },
  43713. enumerable: true,
  43714. configurable: true
  43715. });
  43716. /**
  43717. * Gets the name of the material class.
  43718. */
  43719. PBRBaseMaterial.prototype.getClassName = function () {
  43720. return "PBRBaseMaterial";
  43721. };
  43722. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  43723. /**
  43724. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43725. */
  43726. get: function () {
  43727. return this._useLogarithmicDepth;
  43728. },
  43729. /**
  43730. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43731. */
  43732. set: function (value) {
  43733. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43734. },
  43735. enumerable: true,
  43736. configurable: true
  43737. });
  43738. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  43739. /**
  43740. * Gets the current transparency mode.
  43741. */
  43742. get: function () {
  43743. return this._transparencyMode;
  43744. },
  43745. /**
  43746. * Sets the transparency mode of the material.
  43747. *
  43748. * | Value | Type | Description |
  43749. * | ----- | ----------------------------------- | ----------- |
  43750. * | 0 | OPAQUE | |
  43751. * | 1 | ALPHATEST | |
  43752. * | 2 | ALPHABLEND | |
  43753. * | 3 | ALPHATESTANDBLEND | |
  43754. *
  43755. */
  43756. set: function (value) {
  43757. if (this._transparencyMode === value) {
  43758. return;
  43759. }
  43760. this._transparencyMode = value;
  43761. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  43762. this._markAllSubMeshesAsTexturesAndMiscDirty();
  43763. },
  43764. enumerable: true,
  43765. configurable: true
  43766. });
  43767. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  43768. /**
  43769. * Returns true if alpha blending should be disabled.
  43770. */
  43771. get: function () {
  43772. return (this._linkRefractionWithTransparency ||
  43773. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  43774. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43775. },
  43776. enumerable: true,
  43777. configurable: true
  43778. });
  43779. /**
  43780. * Specifies whether or not this material should be rendered in alpha blend mode.
  43781. */
  43782. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  43783. if (this._disableAlphaBlending) {
  43784. return false;
  43785. }
  43786. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  43787. };
  43788. /**
  43789. * Specifies if the mesh will require alpha blending.
  43790. * @param mesh - BJS mesh.
  43791. */
  43792. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  43793. if (this._disableAlphaBlending) {
  43794. return false;
  43795. }
  43796. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  43797. };
  43798. /**
  43799. * Specifies whether or not this material should be rendered in alpha test mode.
  43800. */
  43801. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  43802. if (this._forceAlphaTest) {
  43803. return true;
  43804. }
  43805. if (this._linkRefractionWithTransparency) {
  43806. return false;
  43807. }
  43808. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43809. };
  43810. /**
  43811. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  43812. */
  43813. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  43814. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  43815. };
  43816. /**
  43817. * Gets the texture used for the alpha test.
  43818. */
  43819. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  43820. return this._albedoTexture;
  43821. };
  43822. /**
  43823. * Specifies that the submesh is ready to be used.
  43824. * @param mesh - BJS mesh.
  43825. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  43826. * @param useInstances - Specifies that instances should be used.
  43827. * @returns - boolean indicating that the submesh is ready or not.
  43828. */
  43829. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43830. if (subMesh.effect && this.isFrozen) {
  43831. if (this._wasPreviouslyReady) {
  43832. return true;
  43833. }
  43834. }
  43835. if (!subMesh._materialDefines) {
  43836. subMesh._materialDefines = new PBRMaterialDefines();
  43837. }
  43838. var defines = subMesh._materialDefines;
  43839. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43840. if (defines._renderId === this.getScene().getRenderId()) {
  43841. return true;
  43842. }
  43843. }
  43844. var scene = this.getScene();
  43845. var engine = scene.getEngine();
  43846. if (defines._areTexturesDirty) {
  43847. if (scene.texturesEnabled) {
  43848. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  43849. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  43850. return false;
  43851. }
  43852. }
  43853. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  43854. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43855. return false;
  43856. }
  43857. }
  43858. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  43859. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43860. return false;
  43861. }
  43862. }
  43863. var reflectionTexture = this._getReflectionTexture();
  43864. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43865. if (!reflectionTexture.isReadyOrNotBlocking()) {
  43866. return false;
  43867. }
  43868. }
  43869. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  43870. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43871. return false;
  43872. }
  43873. }
  43874. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  43875. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43876. return false;
  43877. }
  43878. }
  43879. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  43880. if (this._metallicTexture) {
  43881. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  43882. return false;
  43883. }
  43884. }
  43885. else if (this._reflectivityTexture) {
  43886. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  43887. return false;
  43888. }
  43889. }
  43890. if (this._microSurfaceTexture) {
  43891. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  43892. return false;
  43893. }
  43894. }
  43895. }
  43896. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  43897. // Bump texture cannot be not blocking.
  43898. if (!this._bumpTexture.isReady()) {
  43899. return false;
  43900. }
  43901. }
  43902. var refractionTexture = this._getRefractionTexture();
  43903. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  43904. if (!refractionTexture.isReadyOrNotBlocking()) {
  43905. return false;
  43906. }
  43907. }
  43908. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43909. // This is blocking.
  43910. if (!this._environmentBRDFTexture.isReady()) {
  43911. return false;
  43912. }
  43913. }
  43914. }
  43915. }
  43916. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  43917. if (!this._imageProcessingConfiguration.isReady()) {
  43918. return false;
  43919. }
  43920. }
  43921. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  43922. mesh.createNormals(true);
  43923. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  43924. }
  43925. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  43926. if (effect) {
  43927. scene.resetCachedMaterial();
  43928. subMesh.setEffect(effect, defines);
  43929. this.buildUniformLayout();
  43930. }
  43931. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43932. return false;
  43933. }
  43934. defines._renderId = scene.getRenderId();
  43935. this._wasPreviouslyReady = true;
  43936. return true;
  43937. };
  43938. /**
  43939. * Specifies if the material uses metallic roughness workflow.
  43940. * @returns boolean specifiying if the material uses metallic roughness workflow.
  43941. */
  43942. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  43943. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  43944. return true;
  43945. }
  43946. return false;
  43947. };
  43948. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  43949. if (onCompiled === void 0) { onCompiled = null; }
  43950. if (onError === void 0) { onError = null; }
  43951. if (useInstances === void 0) { useInstances = null; }
  43952. if (useClipPlane === void 0) { useClipPlane = null; }
  43953. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  43954. if (!defines.isDirty) {
  43955. return null;
  43956. }
  43957. defines.markAsProcessed();
  43958. var scene = this.getScene();
  43959. var engine = scene.getEngine();
  43960. // Fallbacks
  43961. var fallbacks = new BABYLON.EffectFallbacks();
  43962. var fallbackRank = 0;
  43963. if (defines.USESPHERICALINVERTEX) {
  43964. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  43965. }
  43966. if (defines.FOG) {
  43967. fallbacks.addFallback(fallbackRank, "FOG");
  43968. }
  43969. if (defines.SPECULARAA) {
  43970. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  43971. }
  43972. if (defines.POINTSIZE) {
  43973. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  43974. }
  43975. if (defines.LOGARITHMICDEPTH) {
  43976. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  43977. }
  43978. if (defines.PARALLAX) {
  43979. fallbacks.addFallback(fallbackRank, "PARALLAX");
  43980. }
  43981. if (defines.PARALLAXOCCLUSION) {
  43982. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  43983. }
  43984. if (defines.ENVIRONMENTBRDF) {
  43985. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  43986. }
  43987. if (defines.TANGENT) {
  43988. fallbacks.addFallback(fallbackRank++, "TANGENT");
  43989. }
  43990. if (defines.BUMP) {
  43991. fallbacks.addFallback(fallbackRank++, "BUMP");
  43992. }
  43993. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  43994. if (defines.SPECULARTERM) {
  43995. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  43996. }
  43997. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  43998. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  43999. }
  44000. if (defines.LIGHTMAP) {
  44001. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  44002. }
  44003. if (defines.NORMAL) {
  44004. fallbacks.addFallback(fallbackRank++, "NORMAL");
  44005. }
  44006. if (defines.AMBIENT) {
  44007. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  44008. }
  44009. if (defines.EMISSIVE) {
  44010. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  44011. }
  44012. if (defines.VERTEXCOLOR) {
  44013. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  44014. }
  44015. if (defines.NUM_BONE_INFLUENCERS > 0) {
  44016. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  44017. }
  44018. if (defines.MORPHTARGETS) {
  44019. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  44020. }
  44021. //Attributes
  44022. var attribs = [BABYLON.VertexBuffer.PositionKind];
  44023. if (defines.NORMAL) {
  44024. attribs.push(BABYLON.VertexBuffer.NormalKind);
  44025. }
  44026. if (defines.TANGENT) {
  44027. attribs.push(BABYLON.VertexBuffer.TangentKind);
  44028. }
  44029. if (defines.UV1) {
  44030. attribs.push(BABYLON.VertexBuffer.UVKind);
  44031. }
  44032. if (defines.UV2) {
  44033. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44034. }
  44035. if (defines.VERTEXCOLOR) {
  44036. attribs.push(BABYLON.VertexBuffer.ColorKind);
  44037. }
  44038. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  44039. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  44040. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  44041. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  44042. "vFogInfos", "vFogColor", "pointSize",
  44043. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  44044. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  44045. "mBones",
  44046. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  44047. "vLightingIntensity",
  44048. "logarithmicDepthConstant",
  44049. "vSphericalX", "vSphericalY", "vSphericalZ",
  44050. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  44051. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  44052. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  44053. "vTangentSpaceParams"
  44054. ];
  44055. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  44056. "bumpSampler", "lightmapSampler", "opacitySampler",
  44057. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  44058. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  44059. "microSurfaceSampler", "environmentBrdfSampler"];
  44060. var uniformBuffers = ["Material", "Scene"];
  44061. if (BABYLON.ImageProcessingConfiguration) {
  44062. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  44063. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  44064. }
  44065. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  44066. uniformsNames: uniforms,
  44067. uniformBuffersNames: uniformBuffers,
  44068. samplers: samplers,
  44069. defines: defines,
  44070. maxSimultaneousLights: this._maxSimultaneousLights
  44071. });
  44072. var join = defines.toString();
  44073. return engine.createEffect("pbr", {
  44074. attributes: attribs,
  44075. uniformsNames: uniforms,
  44076. uniformBuffersNames: uniformBuffers,
  44077. samplers: samplers,
  44078. defines: join,
  44079. fallbacks: fallbacks,
  44080. onCompiled: onCompiled,
  44081. onError: onError,
  44082. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  44083. }, engine);
  44084. };
  44085. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  44086. if (useInstances === void 0) { useInstances = null; }
  44087. if (useClipPlane === void 0) { useClipPlane = null; }
  44088. var scene = this.getScene();
  44089. var engine = scene.getEngine();
  44090. // Lights
  44091. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  44092. defines._needNormals = true;
  44093. // Textures
  44094. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  44095. if (defines._areTexturesDirty) {
  44096. defines._needUVs = false;
  44097. if (scene.texturesEnabled) {
  44098. if (scene.getEngine().getCaps().textureLOD) {
  44099. defines.LODBASEDMICROSFURACE = true;
  44100. }
  44101. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44102. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  44103. }
  44104. else {
  44105. defines.ALBEDO = false;
  44106. }
  44107. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44108. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  44109. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  44110. }
  44111. else {
  44112. defines.AMBIENT = false;
  44113. }
  44114. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44115. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  44116. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  44117. }
  44118. else {
  44119. defines.OPACITY = false;
  44120. }
  44121. var reflectionTexture = this._getReflectionTexture();
  44122. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44123. defines.REFLECTION = true;
  44124. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  44125. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  44126. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  44127. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  44128. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  44129. defines.INVERTCUBICMAP = true;
  44130. }
  44131. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  44132. switch (reflectionTexture.coordinatesMode) {
  44133. case BABYLON.Texture.EXPLICIT_MODE:
  44134. defines.REFLECTIONMAP_EXPLICIT = true;
  44135. break;
  44136. case BABYLON.Texture.PLANAR_MODE:
  44137. defines.REFLECTIONMAP_PLANAR = true;
  44138. break;
  44139. case BABYLON.Texture.PROJECTION_MODE:
  44140. defines.REFLECTIONMAP_PROJECTION = true;
  44141. break;
  44142. case BABYLON.Texture.SKYBOX_MODE:
  44143. defines.REFLECTIONMAP_SKYBOX = true;
  44144. break;
  44145. case BABYLON.Texture.SPHERICAL_MODE:
  44146. defines.REFLECTIONMAP_SPHERICAL = true;
  44147. break;
  44148. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  44149. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  44150. break;
  44151. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  44152. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  44153. break;
  44154. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  44155. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  44156. break;
  44157. case BABYLON.Texture.CUBIC_MODE:
  44158. case BABYLON.Texture.INVCUBIC_MODE:
  44159. default:
  44160. defines.REFLECTIONMAP_CUBIC = true;
  44161. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  44162. break;
  44163. }
  44164. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  44165. if (reflectionTexture.sphericalPolynomial) {
  44166. defines.USESPHERICALFROMREFLECTIONMAP = true;
  44167. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  44168. defines.USESPHERICALINVERTEX = false;
  44169. }
  44170. else {
  44171. defines.USESPHERICALINVERTEX = true;
  44172. }
  44173. }
  44174. }
  44175. else {
  44176. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
  44177. }
  44178. }
  44179. else {
  44180. defines.REFLECTION = false;
  44181. defines.REFLECTIONMAP_3D = false;
  44182. defines.REFLECTIONMAP_SPHERICAL = false;
  44183. defines.REFLECTIONMAP_PLANAR = false;
  44184. defines.REFLECTIONMAP_CUBIC = false;
  44185. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44186. defines.REFLECTIONMAP_PROJECTION = false;
  44187. defines.REFLECTIONMAP_SKYBOX = false;
  44188. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  44189. defines.REFLECTIONMAP_EXPLICIT = false;
  44190. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44191. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44192. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44193. defines.INVERTCUBICMAP = false;
  44194. defines.USESPHERICALFROMREFLECTIONMAP = false;
  44195. defines.USESPHERICALINVERTEX = false;
  44196. defines.REFLECTIONMAP_OPPOSITEZ = false;
  44197. defines.LODINREFLECTIONALPHA = false;
  44198. defines.GAMMAREFLECTION = false;
  44199. defines.RGBDREFLECTION = false;
  44200. }
  44201. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44202. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  44203. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  44204. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  44205. }
  44206. else {
  44207. defines.LIGHTMAP = false;
  44208. }
  44209. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44210. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  44211. }
  44212. else {
  44213. defines.EMISSIVE = false;
  44214. }
  44215. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44216. if (this._metallicTexture) {
  44217. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  44218. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  44219. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  44220. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  44221. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  44222. }
  44223. else if (this._reflectivityTexture) {
  44224. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  44225. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  44226. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  44227. }
  44228. else {
  44229. defines.REFLECTIVITY = false;
  44230. }
  44231. if (this._microSurfaceTexture) {
  44232. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  44233. }
  44234. else {
  44235. defines.MICROSURFACEMAP = false;
  44236. }
  44237. }
  44238. else {
  44239. defines.REFLECTIVITY = false;
  44240. defines.MICROSURFACEMAP = false;
  44241. }
  44242. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44243. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  44244. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44245. defines.PARALLAX = true;
  44246. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  44247. }
  44248. else {
  44249. defines.PARALLAX = false;
  44250. }
  44251. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  44252. }
  44253. else {
  44254. defines.BUMP = false;
  44255. }
  44256. var refractionTexture = this._getRefractionTexture();
  44257. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44258. defines.REFRACTION = true;
  44259. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  44260. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  44261. defines.RGBDREFRACTION = refractionTexture.isRGBD;
  44262. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  44263. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  44264. if (this._linkRefractionWithTransparency) {
  44265. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  44266. }
  44267. }
  44268. else {
  44269. defines.REFRACTION = false;
  44270. }
  44271. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44272. defines.ENVIRONMENTBRDF = true;
  44273. }
  44274. else {
  44275. defines.ENVIRONMENTBRDF = false;
  44276. }
  44277. if (this._shouldUseAlphaFromAlbedoTexture()) {
  44278. defines.ALPHAFROMALBEDO = true;
  44279. }
  44280. else {
  44281. defines.ALPHAFROMALBEDO = false;
  44282. }
  44283. }
  44284. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  44285. if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_STANDARD) {
  44286. defines.USEPHYSICALLIGHTFALLOFF = false;
  44287. defines.USEGLTFLIGHTFALLOFF = false;
  44288. }
  44289. else if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_GLTF) {
  44290. defines.USEPHYSICALLIGHTFALLOFF = false;
  44291. defines.USEGLTFLIGHTFALLOFF = true;
  44292. }
  44293. else {
  44294. defines.USEPHYSICALLIGHTFALLOFF = true;
  44295. defines.USEGLTFLIGHTFALLOFF = false;
  44296. }
  44297. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  44298. if (!this.backFaceCulling && this._twoSidedLighting) {
  44299. defines.TWOSIDEDLIGHTING = true;
  44300. }
  44301. else {
  44302. defines.TWOSIDEDLIGHTING = false;
  44303. }
  44304. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  44305. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  44306. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  44307. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  44308. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  44309. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  44310. }
  44311. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  44312. this._imageProcessingConfiguration.prepareDefines(defines);
  44313. }
  44314. defines.FORCENORMALFORWARD = this._forceNormalForward;
  44315. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  44316. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  44317. // Misc.
  44318. if (defines._areMiscDirty) {
  44319. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  44320. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  44321. }
  44322. // Values that need to be evaluated on every frame
  44323. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  44324. // Attribs
  44325. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  44326. };
  44327. /**
  44328. * Force shader compilation
  44329. */
  44330. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  44331. var _this = this;
  44332. var localOptions = __assign({ clipPlane: false }, options);
  44333. var defines = new PBRMaterialDefines();
  44334. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  44335. if (effect.isReady()) {
  44336. if (onCompiled) {
  44337. onCompiled(this);
  44338. }
  44339. }
  44340. else {
  44341. effect.onCompileObservable.add(function () {
  44342. if (onCompiled) {
  44343. onCompiled(_this);
  44344. }
  44345. });
  44346. }
  44347. };
  44348. /**
  44349. * Initializes the uniform buffer layout for the shader.
  44350. */
  44351. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  44352. // Order is important !
  44353. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  44354. this._uniformBuffer.addUniform("vAmbientInfos", 4);
  44355. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  44356. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  44357. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  44358. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  44359. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  44360. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  44361. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  44362. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  44363. this._uniformBuffer.addUniform("vReflectionSize", 3);
  44364. this._uniformBuffer.addUniform("vBumpInfos", 3);
  44365. this._uniformBuffer.addUniform("albedoMatrix", 16);
  44366. this._uniformBuffer.addUniform("ambientMatrix", 16);
  44367. this._uniformBuffer.addUniform("opacityMatrix", 16);
  44368. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  44369. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  44370. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  44371. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  44372. this._uniformBuffer.addUniform("bumpMatrix", 16);
  44373. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  44374. this._uniformBuffer.addUniform("refractionMatrix", 16);
  44375. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  44376. this._uniformBuffer.addUniform("vReflectionColor", 3);
  44377. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  44378. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  44379. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  44380. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  44381. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  44382. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  44383. this._uniformBuffer.addUniform("pointSize", 1);
  44384. this._uniformBuffer.create();
  44385. };
  44386. /**
  44387. * Unbinds the textures.
  44388. */
  44389. PBRBaseMaterial.prototype.unbind = function () {
  44390. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44391. this._uniformBuffer.setTexture("reflectionSampler", null);
  44392. }
  44393. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44394. this._uniformBuffer.setTexture("refractionSampler", null);
  44395. }
  44396. _super.prototype.unbind.call(this);
  44397. };
  44398. /**
  44399. * Binds the submesh data.
  44400. * @param world - The world matrix.
  44401. * @param mesh - The BJS mesh.
  44402. * @param subMesh - A submesh of the BJS mesh.
  44403. */
  44404. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  44405. var scene = this.getScene();
  44406. var defines = subMesh._materialDefines;
  44407. if (!defines) {
  44408. return;
  44409. }
  44410. var effect = subMesh.effect;
  44411. if (!effect) {
  44412. return;
  44413. }
  44414. this._activeEffect = effect;
  44415. // Matrices
  44416. this.bindOnlyWorldMatrix(world);
  44417. // Normal Matrix
  44418. if (defines.OBJECTSPACE_NORMALMAP) {
  44419. world.toNormalMatrix(this._normalMatrix);
  44420. this.bindOnlyNormalMatrix(this._normalMatrix);
  44421. }
  44422. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  44423. // Bones
  44424. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  44425. var reflectionTexture = null;
  44426. if (mustRebind) {
  44427. this._uniformBuffer.bindToEffect(effect, "Material");
  44428. this.bindViewProjection(effect);
  44429. reflectionTexture = this._getReflectionTexture();
  44430. var refractionTexture = this._getRefractionTexture();
  44431. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  44432. // Texture uniforms
  44433. if (scene.texturesEnabled) {
  44434. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44435. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  44436. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  44437. }
  44438. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44439. this._uniformBuffer.updateFloat4("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength, this._ambientTextureImpactOnAnalyticalLights);
  44440. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  44441. }
  44442. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44443. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  44444. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  44445. }
  44446. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44447. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  44448. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  44449. if (reflectionTexture.boundingBoxSize) {
  44450. var cubeTexture = reflectionTexture;
  44451. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  44452. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  44453. }
  44454. var polynomials = reflectionTexture.sphericalPolynomial;
  44455. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  44456. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  44457. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  44458. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  44459. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  44460. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  44461. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  44462. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  44463. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  44464. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  44465. }
  44466. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  44467. }
  44468. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44469. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  44470. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  44471. }
  44472. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44473. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  44474. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  44475. }
  44476. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44477. if (this._metallicTexture) {
  44478. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  44479. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  44480. }
  44481. else if (this._reflectivityTexture) {
  44482. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  44483. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  44484. }
  44485. if (this._microSurfaceTexture) {
  44486. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  44487. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  44488. }
  44489. }
  44490. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44491. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  44492. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  44493. if (scene._mirroredCameraPosition) {
  44494. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  44495. }
  44496. else {
  44497. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  44498. }
  44499. }
  44500. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44501. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  44502. var depth = 1.0;
  44503. if (!refractionTexture.isCube) {
  44504. if (refractionTexture.depth) {
  44505. depth = refractionTexture.depth;
  44506. }
  44507. }
  44508. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  44509. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  44510. }
  44511. }
  44512. // Point size
  44513. if (this.pointsCloud) {
  44514. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  44515. }
  44516. // Colors
  44517. if (defines.METALLICWORKFLOW) {
  44518. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  44519. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  44520. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  44521. }
  44522. else {
  44523. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  44524. }
  44525. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  44526. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  44527. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  44528. // Misc
  44529. this._lightingInfos.x = this._directIntensity;
  44530. this._lightingInfos.y = this._emissiveIntensity;
  44531. this._lightingInfos.z = this._environmentIntensity;
  44532. this._lightingInfos.w = this._specularIntensity;
  44533. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  44534. }
  44535. // Textures
  44536. if (scene.texturesEnabled) {
  44537. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44538. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  44539. }
  44540. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44541. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  44542. }
  44543. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44544. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  44545. }
  44546. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44547. if (defines.LODBASEDMICROSFURACE) {
  44548. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  44549. }
  44550. else {
  44551. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  44552. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  44553. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  44554. }
  44555. }
  44556. if (defines.ENVIRONMENTBRDF) {
  44557. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  44558. }
  44559. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44560. if (defines.LODBASEDMICROSFURACE) {
  44561. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  44562. }
  44563. else {
  44564. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  44565. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  44566. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  44567. }
  44568. }
  44569. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44570. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  44571. }
  44572. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44573. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  44574. }
  44575. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44576. if (this._metallicTexture) {
  44577. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  44578. }
  44579. else if (this._reflectivityTexture) {
  44580. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  44581. }
  44582. if (this._microSurfaceTexture) {
  44583. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  44584. }
  44585. }
  44586. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44587. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  44588. }
  44589. }
  44590. // Clip plane
  44591. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  44592. // Colors
  44593. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  44594. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  44595. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  44596. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  44597. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44598. }
  44599. if (mustRebind || !this.isFrozen) {
  44600. // Lights
  44601. if (scene.lightsEnabled && !this._disableLighting) {
  44602. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._lightFalloff !== PBRBaseMaterial.LIGHTFALLOFF_STANDARD);
  44603. }
  44604. // View
  44605. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  44606. this.bindView(effect);
  44607. }
  44608. // Fog
  44609. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  44610. // Morph targets
  44611. if (defines.NUM_MORPH_INFLUENCERS) {
  44612. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  44613. }
  44614. // image processing
  44615. this._imageProcessingConfiguration.bind(this._activeEffect);
  44616. // Log. depth
  44617. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  44618. }
  44619. this._uniformBuffer.update();
  44620. this._afterBind(mesh, this._activeEffect);
  44621. };
  44622. /**
  44623. * Returns the animatable textures.
  44624. * @returns - Array of animatable textures.
  44625. */
  44626. PBRBaseMaterial.prototype.getAnimatables = function () {
  44627. var results = [];
  44628. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  44629. results.push(this._albedoTexture);
  44630. }
  44631. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  44632. results.push(this._ambientTexture);
  44633. }
  44634. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  44635. results.push(this._opacityTexture);
  44636. }
  44637. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  44638. results.push(this._reflectionTexture);
  44639. }
  44640. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  44641. results.push(this._emissiveTexture);
  44642. }
  44643. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  44644. results.push(this._metallicTexture);
  44645. }
  44646. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  44647. results.push(this._reflectivityTexture);
  44648. }
  44649. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  44650. results.push(this._bumpTexture);
  44651. }
  44652. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  44653. results.push(this._lightmapTexture);
  44654. }
  44655. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  44656. results.push(this._refractionTexture);
  44657. }
  44658. return results;
  44659. };
  44660. /**
  44661. * Returns the texture used for reflections.
  44662. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  44663. */
  44664. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  44665. if (this._reflectionTexture) {
  44666. return this._reflectionTexture;
  44667. }
  44668. return this.getScene().environmentTexture;
  44669. };
  44670. /**
  44671. * Returns the texture used for refraction or null if none is used.
  44672. * @returns - Refection texture if present. If no refraction texture and refraction
  44673. * is linked with transparency, returns environment texture. Otherwise, returns null.
  44674. */
  44675. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  44676. if (this._refractionTexture) {
  44677. return this._refractionTexture;
  44678. }
  44679. if (this._linkRefractionWithTransparency) {
  44680. return this.getScene().environmentTexture;
  44681. }
  44682. return null;
  44683. };
  44684. /**
  44685. * Disposes the resources of the material.
  44686. * @param forceDisposeEffect - Forces the disposal of effects.
  44687. * @param forceDisposeTextures - Forces the disposal of all textures.
  44688. */
  44689. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44690. if (forceDisposeTextures) {
  44691. if (this._albedoTexture) {
  44692. this._albedoTexture.dispose();
  44693. }
  44694. if (this._ambientTexture) {
  44695. this._ambientTexture.dispose();
  44696. }
  44697. if (this._opacityTexture) {
  44698. this._opacityTexture.dispose();
  44699. }
  44700. if (this._reflectionTexture) {
  44701. this._reflectionTexture.dispose();
  44702. }
  44703. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  44704. this._environmentBRDFTexture.dispose();
  44705. }
  44706. if (this._emissiveTexture) {
  44707. this._emissiveTexture.dispose();
  44708. }
  44709. if (this._metallicTexture) {
  44710. this._metallicTexture.dispose();
  44711. }
  44712. if (this._reflectivityTexture) {
  44713. this._reflectivityTexture.dispose();
  44714. }
  44715. if (this._bumpTexture) {
  44716. this._bumpTexture.dispose();
  44717. }
  44718. if (this._lightmapTexture) {
  44719. this._lightmapTexture.dispose();
  44720. }
  44721. if (this._refractionTexture) {
  44722. this._refractionTexture.dispose();
  44723. }
  44724. }
  44725. this._renderTargets.dispose();
  44726. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44727. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44728. }
  44729. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  44730. };
  44731. /**
  44732. * PBRMaterialLightFalloff Physical: light is falling off following the inverse squared distance law.
  44733. */
  44734. PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL = 0;
  44735. /**
  44736. * PBRMaterialLightFalloff gltf: light is falling off as described in the gltf moving to PBR document
  44737. * to enhance interoperability with other engines.
  44738. */
  44739. PBRBaseMaterial.LIGHTFALLOFF_GLTF = 1;
  44740. /**
  44741. * PBRMaterialLightFalloff Standard: light is falling off like in the standard material
  44742. * to enhance interoperability with other materials.
  44743. */
  44744. PBRBaseMaterial.LIGHTFALLOFF_STANDARD = 2;
  44745. /**
  44746. * Stores the reflectivity values based on metallic roughness workflow.
  44747. */
  44748. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  44749. __decorate([
  44750. BABYLON.serializeAsImageProcessingConfiguration()
  44751. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  44752. __decorate([
  44753. BABYLON.serialize()
  44754. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  44755. __decorate([
  44756. BABYLON.serialize()
  44757. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  44758. return PBRBaseMaterial;
  44759. }(BABYLON.PushMaterial));
  44760. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  44761. })(BABYLON || (BABYLON = {}));
  44762. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  44763. var BABYLON;
  44764. (function (BABYLON) {
  44765. /**
  44766. * The Physically based simple base material of BJS.
  44767. *
  44768. * This enables better naming and convention enforcements on top of the pbrMaterial.
  44769. * It is used as the base class for both the specGloss and metalRough conventions.
  44770. */
  44771. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  44772. __extends(PBRBaseSimpleMaterial, _super);
  44773. /**
  44774. * Instantiates a new PBRMaterial instance.
  44775. *
  44776. * @param name The material name
  44777. * @param scene The scene the material will be use in.
  44778. */
  44779. function PBRBaseSimpleMaterial(name, scene) {
  44780. var _this = _super.call(this, name, scene) || this;
  44781. /**
  44782. * Number of Simultaneous lights allowed on the material.
  44783. */
  44784. _this.maxSimultaneousLights = 4;
  44785. /**
  44786. * If sets to true, disables all the lights affecting the material.
  44787. */
  44788. _this.disableLighting = false;
  44789. /**
  44790. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  44791. */
  44792. _this.invertNormalMapX = false;
  44793. /**
  44794. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  44795. */
  44796. _this.invertNormalMapY = false;
  44797. /**
  44798. * Emissivie color used to self-illuminate the model.
  44799. */
  44800. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44801. /**
  44802. * Occlusion Channel Strenght.
  44803. */
  44804. _this.occlusionStrength = 1.0;
  44805. _this.useLightmapAsShadowmap = false;
  44806. _this._useAlphaFromAlbedoTexture = true;
  44807. _this._useAmbientInGrayScale = true;
  44808. return _this;
  44809. }
  44810. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  44811. /**
  44812. * Gets the current double sided mode.
  44813. */
  44814. get: function () {
  44815. return this._twoSidedLighting;
  44816. },
  44817. /**
  44818. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44819. */
  44820. set: function (value) {
  44821. if (this._twoSidedLighting === value) {
  44822. return;
  44823. }
  44824. this._twoSidedLighting = value;
  44825. this.backFaceCulling = !value;
  44826. this._markAllSubMeshesAsTexturesDirty();
  44827. },
  44828. enumerable: true,
  44829. configurable: true
  44830. });
  44831. /**
  44832. * Return the active textures of the material.
  44833. */
  44834. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  44835. var activeTextures = _super.prototype.getActiveTextures.call(this);
  44836. if (this.environmentTexture) {
  44837. activeTextures.push(this.environmentTexture);
  44838. }
  44839. if (this.normalTexture) {
  44840. activeTextures.push(this.normalTexture);
  44841. }
  44842. if (this.emissiveTexture) {
  44843. activeTextures.push(this.emissiveTexture);
  44844. }
  44845. if (this.occlusionTexture) {
  44846. activeTextures.push(this.occlusionTexture);
  44847. }
  44848. if (this.lightmapTexture) {
  44849. activeTextures.push(this.lightmapTexture);
  44850. }
  44851. return activeTextures;
  44852. };
  44853. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  44854. if (_super.prototype.hasTexture.call(this, texture)) {
  44855. return true;
  44856. }
  44857. if (this.lightmapTexture === texture) {
  44858. return true;
  44859. }
  44860. return false;
  44861. };
  44862. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  44863. return "PBRBaseSimpleMaterial";
  44864. };
  44865. __decorate([
  44866. BABYLON.serialize(),
  44867. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44868. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  44869. __decorate([
  44870. BABYLON.serialize(),
  44871. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44872. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  44873. __decorate([
  44874. BABYLON.serializeAsTexture(),
  44875. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  44876. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  44877. __decorate([
  44878. BABYLON.serialize(),
  44879. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44880. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  44881. __decorate([
  44882. BABYLON.serialize(),
  44883. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44884. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  44885. __decorate([
  44886. BABYLON.serializeAsTexture(),
  44887. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  44888. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  44889. __decorate([
  44890. BABYLON.serializeAsColor3("emissive"),
  44891. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44892. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  44893. __decorate([
  44894. BABYLON.serializeAsTexture(),
  44895. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44896. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  44897. __decorate([
  44898. BABYLON.serialize(),
  44899. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  44900. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  44901. __decorate([
  44902. BABYLON.serializeAsTexture(),
  44903. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  44904. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  44905. __decorate([
  44906. BABYLON.serialize(),
  44907. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  44908. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  44909. __decorate([
  44910. BABYLON.serialize()
  44911. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  44912. __decorate([
  44913. BABYLON.serializeAsTexture(),
  44914. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  44915. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  44916. __decorate([
  44917. BABYLON.serialize(),
  44918. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44919. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44920. return PBRBaseSimpleMaterial;
  44921. }(BABYLON.PBRBaseMaterial));
  44922. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  44923. })(BABYLON || (BABYLON = {}));
  44924. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  44925. var BABYLON;
  44926. (function (BABYLON) {
  44927. /**
  44928. * The Physically based material of BJS.
  44929. *
  44930. * This offers the main features of a standard PBR material.
  44931. * For more information, please refer to the documentation :
  44932. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44933. */
  44934. var PBRMaterial = /** @class */ (function (_super) {
  44935. __extends(PBRMaterial, _super);
  44936. /**
  44937. * Instantiates a new PBRMaterial instance.
  44938. *
  44939. * @param name The material name
  44940. * @param scene The scene the material will be use in.
  44941. */
  44942. function PBRMaterial(name, scene) {
  44943. var _this = _super.call(this, name, scene) || this;
  44944. /**
  44945. * Intensity of the direct lights e.g. the four lights available in your scene.
  44946. * This impacts both the direct diffuse and specular highlights.
  44947. */
  44948. _this.directIntensity = 1.0;
  44949. /**
  44950. * Intensity of the emissive part of the material.
  44951. * This helps controlling the emissive effect without modifying the emissive color.
  44952. */
  44953. _this.emissiveIntensity = 1.0;
  44954. /**
  44955. * Intensity of the environment e.g. how much the environment will light the object
  44956. * either through harmonics for rough material or through the refelction for shiny ones.
  44957. */
  44958. _this.environmentIntensity = 1.0;
  44959. /**
  44960. * This is a special control allowing the reduction of the specular highlights coming from the
  44961. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44962. */
  44963. _this.specularIntensity = 1.0;
  44964. /**
  44965. * Debug Control allowing disabling the bump map on this material.
  44966. */
  44967. _this.disableBumpMap = false;
  44968. /**
  44969. * AKA Occlusion Texture Intensity in other nomenclature.
  44970. */
  44971. _this.ambientTextureStrength = 1.0;
  44972. /**
  44973. * Defines how much the AO map is occluding the analytical lights (point spot...).
  44974. * 1 means it completely occludes it
  44975. * 0 mean it has no impact
  44976. */
  44977. _this.ambientTextureImpactOnAnalyticalLights = PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
  44978. /**
  44979. * The color of a material in ambient lighting.
  44980. */
  44981. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  44982. /**
  44983. * AKA Diffuse Color in other nomenclature.
  44984. */
  44985. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  44986. /**
  44987. * AKA Specular Color in other nomenclature.
  44988. */
  44989. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  44990. /**
  44991. * The color reflected from the material.
  44992. */
  44993. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  44994. /**
  44995. * The color emitted from the material.
  44996. */
  44997. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44998. /**
  44999. * AKA Glossiness in other nomenclature.
  45000. */
  45001. _this.microSurface = 1.0;
  45002. /**
  45003. * source material index of refraction (IOR)' / 'destination material IOR.
  45004. */
  45005. _this.indexOfRefraction = 0.66;
  45006. /**
  45007. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  45008. */
  45009. _this.invertRefractionY = false;
  45010. /**
  45011. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  45012. * Materials half opaque for instance using refraction could benefit from this control.
  45013. */
  45014. _this.linkRefractionWithTransparency = false;
  45015. _this.useLightmapAsShadowmap = false;
  45016. /**
  45017. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  45018. */
  45019. _this.useAlphaFromAlbedoTexture = false;
  45020. /**
  45021. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  45022. */
  45023. _this.forceAlphaTest = false;
  45024. /**
  45025. * Defines the alpha limits in alpha test mode.
  45026. */
  45027. _this.alphaCutOff = 0.4;
  45028. /**
  45029. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  45030. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  45031. */
  45032. _this.useSpecularOverAlpha = true;
  45033. /**
  45034. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  45035. */
  45036. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  45037. /**
  45038. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  45039. */
  45040. _this.useRoughnessFromMetallicTextureAlpha = true;
  45041. /**
  45042. * Specifies if the metallic texture contains the roughness information in its green channel.
  45043. */
  45044. _this.useRoughnessFromMetallicTextureGreen = false;
  45045. /**
  45046. * Specifies if the metallic texture contains the metallness information in its blue channel.
  45047. */
  45048. _this.useMetallnessFromMetallicTextureBlue = false;
  45049. /**
  45050. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  45051. */
  45052. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  45053. /**
  45054. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  45055. */
  45056. _this.useAmbientInGrayScale = false;
  45057. /**
  45058. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  45059. * The material will try to infer what glossiness each pixel should be.
  45060. */
  45061. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  45062. /**
  45063. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  45064. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  45065. */
  45066. _this.useRadianceOverAlpha = true;
  45067. /**
  45068. * Allows using an object space normal map (instead of tangent space).
  45069. */
  45070. _this.useObjectSpaceNormalMap = false;
  45071. /**
  45072. * Allows using the bump map in parallax mode.
  45073. */
  45074. _this.useParallax = false;
  45075. /**
  45076. * Allows using the bump map in parallax occlusion mode.
  45077. */
  45078. _this.useParallaxOcclusion = false;
  45079. /**
  45080. * Controls the scale bias of the parallax mode.
  45081. */
  45082. _this.parallaxScaleBias = 0.05;
  45083. /**
  45084. * If sets to true, disables all the lights affecting the material.
  45085. */
  45086. _this.disableLighting = false;
  45087. /**
  45088. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  45089. */
  45090. _this.forceIrradianceInFragment = false;
  45091. /**
  45092. * Number of Simultaneous lights allowed on the material.
  45093. */
  45094. _this.maxSimultaneousLights = 4;
  45095. /**
  45096. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45097. */
  45098. _this.invertNormalMapX = false;
  45099. /**
  45100. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45101. */
  45102. _this.invertNormalMapY = false;
  45103. /**
  45104. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45105. */
  45106. _this.twoSidedLighting = false;
  45107. /**
  45108. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45109. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  45110. */
  45111. _this.useAlphaFresnel = false;
  45112. /**
  45113. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45114. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  45115. */
  45116. _this.useLinearAlphaFresnel = false;
  45117. /**
  45118. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45119. * And/Or occlude the blended part.
  45120. */
  45121. _this.environmentBRDFTexture = null;
  45122. /**
  45123. * Force normal to face away from face.
  45124. */
  45125. _this.forceNormalForward = false;
  45126. /**
  45127. * Enables specular anti aliasing in the PBR shader.
  45128. * It will both interacts on the Geometry for analytical and IBL lighting.
  45129. * It also prefilter the roughness map based on the bump values.
  45130. */
  45131. _this.enableSpecularAntiAliasing = false;
  45132. /**
  45133. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  45134. * makes the reflect vector face the model (under horizon).
  45135. */
  45136. _this.useHorizonOcclusion = true;
  45137. /**
  45138. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  45139. * too much the area relying on ambient texture to define their ambient occlusion.
  45140. */
  45141. _this.useRadianceOcclusion = true;
  45142. /**
  45143. * If set to true, no lighting calculations will be applied.
  45144. */
  45145. _this.unlit = false;
  45146. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  45147. return _this;
  45148. }
  45149. Object.defineProperty(PBRMaterial.prototype, "usePhysicalLightFalloff", {
  45150. /**
  45151. * BJS is using an harcoded light falloff based on a manually sets up range.
  45152. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45153. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45154. */
  45155. get: function () {
  45156. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  45157. },
  45158. /**
  45159. * BJS is using an harcoded light falloff based on a manually sets up range.
  45160. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45161. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45162. */
  45163. set: function (value) {
  45164. if (value !== this.usePhysicalLightFalloff) {
  45165. // Ensure the effect will be rebuilt.
  45166. this._markAllSubMeshesAsTexturesDirty();
  45167. if (value) {
  45168. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  45169. }
  45170. else {
  45171. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  45172. }
  45173. }
  45174. },
  45175. enumerable: true,
  45176. configurable: true
  45177. });
  45178. Object.defineProperty(PBRMaterial.prototype, "useGLTFLightFalloff", {
  45179. /**
  45180. * In order to support the falloff compatibility with gltf, a special mode has been added
  45181. * to reproduce the gltf light falloff.
  45182. */
  45183. get: function () {
  45184. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  45185. },
  45186. /**
  45187. * In order to support the falloff compatibility with gltf, a special mode has been added
  45188. * to reproduce the gltf light falloff.
  45189. */
  45190. set: function (value) {
  45191. if (value !== this.useGLTFLightFalloff) {
  45192. // Ensure the effect will be rebuilt.
  45193. this._markAllSubMeshesAsTexturesDirty();
  45194. if (value) {
  45195. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  45196. }
  45197. else {
  45198. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  45199. }
  45200. }
  45201. },
  45202. enumerable: true,
  45203. configurable: true
  45204. });
  45205. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  45206. /**
  45207. * Gets the image processing configuration used either in this material.
  45208. */
  45209. get: function () {
  45210. return this._imageProcessingConfiguration;
  45211. },
  45212. /**
  45213. * Sets the Default image processing configuration used either in the this material.
  45214. *
  45215. * If sets to null, the scene one is in use.
  45216. */
  45217. set: function (value) {
  45218. this._attachImageProcessingConfiguration(value);
  45219. // Ensure the effect will be rebuilt.
  45220. this._markAllSubMeshesAsTexturesDirty();
  45221. },
  45222. enumerable: true,
  45223. configurable: true
  45224. });
  45225. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  45226. /**
  45227. * Gets wether the color curves effect is enabled.
  45228. */
  45229. get: function () {
  45230. return this.imageProcessingConfiguration.colorCurvesEnabled;
  45231. },
  45232. /**
  45233. * Sets wether the color curves effect is enabled.
  45234. */
  45235. set: function (value) {
  45236. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  45237. },
  45238. enumerable: true,
  45239. configurable: true
  45240. });
  45241. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  45242. /**
  45243. * Gets wether the color grading effect is enabled.
  45244. */
  45245. get: function () {
  45246. return this.imageProcessingConfiguration.colorGradingEnabled;
  45247. },
  45248. /**
  45249. * Gets wether the color grading effect is enabled.
  45250. */
  45251. set: function (value) {
  45252. this.imageProcessingConfiguration.colorGradingEnabled = value;
  45253. },
  45254. enumerable: true,
  45255. configurable: true
  45256. });
  45257. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  45258. /**
  45259. * Gets wether tonemapping is enabled or not.
  45260. */
  45261. get: function () {
  45262. return this._imageProcessingConfiguration.toneMappingEnabled;
  45263. },
  45264. /**
  45265. * Sets wether tonemapping is enabled or not
  45266. */
  45267. set: function (value) {
  45268. this._imageProcessingConfiguration.toneMappingEnabled = value;
  45269. },
  45270. enumerable: true,
  45271. configurable: true
  45272. });
  45273. ;
  45274. ;
  45275. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  45276. /**
  45277. * The camera exposure used on this material.
  45278. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45279. * This corresponds to a photographic exposure.
  45280. */
  45281. get: function () {
  45282. return this._imageProcessingConfiguration.exposure;
  45283. },
  45284. /**
  45285. * The camera exposure used on this material.
  45286. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45287. * This corresponds to a photographic exposure.
  45288. */
  45289. set: function (value) {
  45290. this._imageProcessingConfiguration.exposure = value;
  45291. },
  45292. enumerable: true,
  45293. configurable: true
  45294. });
  45295. ;
  45296. ;
  45297. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  45298. /**
  45299. * Gets The camera contrast used on this material.
  45300. */
  45301. get: function () {
  45302. return this._imageProcessingConfiguration.contrast;
  45303. },
  45304. /**
  45305. * Sets The camera contrast used on this material.
  45306. */
  45307. set: function (value) {
  45308. this._imageProcessingConfiguration.contrast = value;
  45309. },
  45310. enumerable: true,
  45311. configurable: true
  45312. });
  45313. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  45314. /**
  45315. * Gets the Color Grading 2D Lookup Texture.
  45316. */
  45317. get: function () {
  45318. return this._imageProcessingConfiguration.colorGradingTexture;
  45319. },
  45320. /**
  45321. * Sets the Color Grading 2D Lookup Texture.
  45322. */
  45323. set: function (value) {
  45324. this._imageProcessingConfiguration.colorGradingTexture = value;
  45325. },
  45326. enumerable: true,
  45327. configurable: true
  45328. });
  45329. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  45330. /**
  45331. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45332. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45333. * 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;
  45334. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45335. */
  45336. get: function () {
  45337. return this._imageProcessingConfiguration.colorCurves;
  45338. },
  45339. /**
  45340. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45341. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45342. * 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;
  45343. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45344. */
  45345. set: function (value) {
  45346. this._imageProcessingConfiguration.colorCurves = value;
  45347. },
  45348. enumerable: true,
  45349. configurable: true
  45350. });
  45351. /**
  45352. * Returns the name of this material class.
  45353. */
  45354. PBRMaterial.prototype.getClassName = function () {
  45355. return "PBRMaterial";
  45356. };
  45357. /**
  45358. * Returns an array of the actively used textures.
  45359. * @returns - Array of BaseTextures
  45360. */
  45361. PBRMaterial.prototype.getActiveTextures = function () {
  45362. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45363. if (this._albedoTexture) {
  45364. activeTextures.push(this._albedoTexture);
  45365. }
  45366. if (this._ambientTexture) {
  45367. activeTextures.push(this._ambientTexture);
  45368. }
  45369. if (this._opacityTexture) {
  45370. activeTextures.push(this._opacityTexture);
  45371. }
  45372. if (this._reflectionTexture) {
  45373. activeTextures.push(this._reflectionTexture);
  45374. }
  45375. if (this._emissiveTexture) {
  45376. activeTextures.push(this._emissiveTexture);
  45377. }
  45378. if (this._reflectivityTexture) {
  45379. activeTextures.push(this._reflectivityTexture);
  45380. }
  45381. if (this._metallicTexture) {
  45382. activeTextures.push(this._metallicTexture);
  45383. }
  45384. if (this._microSurfaceTexture) {
  45385. activeTextures.push(this._microSurfaceTexture);
  45386. }
  45387. if (this._bumpTexture) {
  45388. activeTextures.push(this._bumpTexture);
  45389. }
  45390. if (this._lightmapTexture) {
  45391. activeTextures.push(this._lightmapTexture);
  45392. }
  45393. if (this._refractionTexture) {
  45394. activeTextures.push(this._refractionTexture);
  45395. }
  45396. return activeTextures;
  45397. };
  45398. /**
  45399. * Checks to see if a texture is used in the material.
  45400. * @param texture - Base texture to use.
  45401. * @returns - Boolean specifying if a texture is used in the material.
  45402. */
  45403. PBRMaterial.prototype.hasTexture = function (texture) {
  45404. if (_super.prototype.hasTexture.call(this, texture)) {
  45405. return true;
  45406. }
  45407. if (this._albedoTexture === texture) {
  45408. return true;
  45409. }
  45410. if (this._ambientTexture === texture) {
  45411. return true;
  45412. }
  45413. if (this._opacityTexture === texture) {
  45414. return true;
  45415. }
  45416. if (this._reflectionTexture === texture) {
  45417. return true;
  45418. }
  45419. if (this._reflectivityTexture === texture) {
  45420. return true;
  45421. }
  45422. if (this._metallicTexture === texture) {
  45423. return true;
  45424. }
  45425. if (this._microSurfaceTexture === texture) {
  45426. return true;
  45427. }
  45428. if (this._bumpTexture === texture) {
  45429. return true;
  45430. }
  45431. if (this._lightmapTexture === texture) {
  45432. return true;
  45433. }
  45434. if (this._refractionTexture === texture) {
  45435. return true;
  45436. }
  45437. return false;
  45438. };
  45439. /**
  45440. * Makes a duplicate of the current material.
  45441. * @param name - name to use for the new material.
  45442. */
  45443. PBRMaterial.prototype.clone = function (name) {
  45444. var _this = this;
  45445. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  45446. clone.id = name;
  45447. clone.name = name;
  45448. return clone;
  45449. };
  45450. /**
  45451. * Serializes this PBR Material.
  45452. * @returns - An object with the serialized material.
  45453. */
  45454. PBRMaterial.prototype.serialize = function () {
  45455. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45456. serializationObject.customType = "BABYLON.PBRMaterial";
  45457. return serializationObject;
  45458. };
  45459. // Statics
  45460. /**
  45461. * Parses a PBR Material from a serialized object.
  45462. * @param source - Serialized object.
  45463. * @param scene - BJS scene instance.
  45464. * @param rootUrl - url for the scene object
  45465. * @returns - PBRMaterial
  45466. */
  45467. PBRMaterial.Parse = function (source, scene, rootUrl) {
  45468. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  45469. };
  45470. /**
  45471. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  45472. */
  45473. PBRMaterial.PBRMATERIAL_OPAQUE = 0;
  45474. /**
  45475. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45476. */
  45477. PBRMaterial.PBRMATERIAL_ALPHATEST = 1;
  45478. /**
  45479. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45480. */
  45481. PBRMaterial.PBRMATERIAL_ALPHABLEND = 2;
  45482. /**
  45483. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45484. * They are also discarded below the alpha cutoff threshold to improve performances.
  45485. */
  45486. PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND = 3;
  45487. /**
  45488. * Defines the default value of how much AO map is occluding the analytical lights
  45489. * (point spot...).
  45490. */
  45491. PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS = 1;
  45492. __decorate([
  45493. BABYLON.serialize(),
  45494. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45495. ], PBRMaterial.prototype, "directIntensity", void 0);
  45496. __decorate([
  45497. BABYLON.serialize(),
  45498. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45499. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  45500. __decorate([
  45501. BABYLON.serialize(),
  45502. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45503. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  45504. __decorate([
  45505. BABYLON.serialize(),
  45506. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45507. ], PBRMaterial.prototype, "specularIntensity", void 0);
  45508. __decorate([
  45509. BABYLON.serialize(),
  45510. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45511. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  45512. __decorate([
  45513. BABYLON.serializeAsTexture(),
  45514. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45515. ], PBRMaterial.prototype, "albedoTexture", void 0);
  45516. __decorate([
  45517. BABYLON.serializeAsTexture(),
  45518. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45519. ], PBRMaterial.prototype, "ambientTexture", void 0);
  45520. __decorate([
  45521. BABYLON.serialize(),
  45522. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45523. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  45524. __decorate([
  45525. BABYLON.serialize(),
  45526. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45527. ], PBRMaterial.prototype, "ambientTextureImpactOnAnalyticalLights", void 0);
  45528. __decorate([
  45529. BABYLON.serializeAsTexture(),
  45530. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45531. ], PBRMaterial.prototype, "opacityTexture", void 0);
  45532. __decorate([
  45533. BABYLON.serializeAsTexture(),
  45534. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45535. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  45536. __decorate([
  45537. BABYLON.serializeAsTexture(),
  45538. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45539. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  45540. __decorate([
  45541. BABYLON.serializeAsTexture(),
  45542. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45543. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  45544. __decorate([
  45545. BABYLON.serializeAsTexture(),
  45546. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45547. ], PBRMaterial.prototype, "metallicTexture", void 0);
  45548. __decorate([
  45549. BABYLON.serialize(),
  45550. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45551. ], PBRMaterial.prototype, "metallic", void 0);
  45552. __decorate([
  45553. BABYLON.serialize(),
  45554. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45555. ], PBRMaterial.prototype, "roughness", void 0);
  45556. __decorate([
  45557. BABYLON.serializeAsTexture(),
  45558. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45559. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  45560. __decorate([
  45561. BABYLON.serializeAsTexture(),
  45562. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45563. ], PBRMaterial.prototype, "bumpTexture", void 0);
  45564. __decorate([
  45565. BABYLON.serializeAsTexture(),
  45566. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45567. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  45568. __decorate([
  45569. BABYLON.serializeAsTexture(),
  45570. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45571. ], PBRMaterial.prototype, "refractionTexture", void 0);
  45572. __decorate([
  45573. BABYLON.serializeAsColor3("ambient"),
  45574. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45575. ], PBRMaterial.prototype, "ambientColor", void 0);
  45576. __decorate([
  45577. BABYLON.serializeAsColor3("albedo"),
  45578. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45579. ], PBRMaterial.prototype, "albedoColor", void 0);
  45580. __decorate([
  45581. BABYLON.serializeAsColor3("reflectivity"),
  45582. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45583. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  45584. __decorate([
  45585. BABYLON.serializeAsColor3("reflection"),
  45586. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45587. ], PBRMaterial.prototype, "reflectionColor", void 0);
  45588. __decorate([
  45589. BABYLON.serializeAsColor3("emissive"),
  45590. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45591. ], PBRMaterial.prototype, "emissiveColor", void 0);
  45592. __decorate([
  45593. BABYLON.serialize(),
  45594. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45595. ], PBRMaterial.prototype, "microSurface", void 0);
  45596. __decorate([
  45597. BABYLON.serialize(),
  45598. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45599. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  45600. __decorate([
  45601. BABYLON.serialize(),
  45602. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45603. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  45604. __decorate([
  45605. BABYLON.serialize(),
  45606. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45607. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  45608. __decorate([
  45609. BABYLON.serialize(),
  45610. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45611. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45612. __decorate([
  45613. BABYLON.serialize(),
  45614. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45615. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  45616. __decorate([
  45617. BABYLON.serialize(),
  45618. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45619. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  45620. __decorate([
  45621. BABYLON.serialize(),
  45622. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45623. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  45624. __decorate([
  45625. BABYLON.serialize(),
  45626. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45627. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  45628. __decorate([
  45629. BABYLON.serialize(),
  45630. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45631. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  45632. __decorate([
  45633. BABYLON.serialize(),
  45634. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45635. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  45636. __decorate([
  45637. BABYLON.serialize(),
  45638. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45639. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  45640. __decorate([
  45641. BABYLON.serialize(),
  45642. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45643. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  45644. __decorate([
  45645. BABYLON.serialize(),
  45646. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45647. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  45648. __decorate([
  45649. BABYLON.serialize(),
  45650. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45651. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  45652. __decorate([
  45653. BABYLON.serialize(),
  45654. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45655. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  45656. __decorate([
  45657. BABYLON.serialize()
  45658. ], PBRMaterial.prototype, "usePhysicalLightFalloff", null);
  45659. __decorate([
  45660. BABYLON.serialize()
  45661. ], PBRMaterial.prototype, "useGLTFLightFalloff", null);
  45662. __decorate([
  45663. BABYLON.serialize(),
  45664. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45665. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  45666. __decorate([
  45667. BABYLON.serialize(),
  45668. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45669. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  45670. __decorate([
  45671. BABYLON.serialize(),
  45672. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45673. ], PBRMaterial.prototype, "useParallax", void 0);
  45674. __decorate([
  45675. BABYLON.serialize(),
  45676. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45677. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  45678. __decorate([
  45679. BABYLON.serialize(),
  45680. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45681. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  45682. __decorate([
  45683. BABYLON.serialize(),
  45684. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45685. ], PBRMaterial.prototype, "disableLighting", void 0);
  45686. __decorate([
  45687. BABYLON.serialize(),
  45688. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45689. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  45690. __decorate([
  45691. BABYLON.serialize(),
  45692. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45693. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  45694. __decorate([
  45695. BABYLON.serialize(),
  45696. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45697. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  45698. __decorate([
  45699. BABYLON.serialize(),
  45700. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45701. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  45702. __decorate([
  45703. BABYLON.serialize(),
  45704. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45705. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  45706. __decorate([
  45707. BABYLON.serialize(),
  45708. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45709. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  45710. __decorate([
  45711. BABYLON.serialize(),
  45712. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45713. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  45714. __decorate([
  45715. BABYLON.serializeAsTexture(),
  45716. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45717. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  45718. __decorate([
  45719. BABYLON.serialize(),
  45720. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45721. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  45722. __decorate([
  45723. BABYLON.serialize(),
  45724. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45725. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  45726. __decorate([
  45727. BABYLON.serialize(),
  45728. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45729. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  45730. __decorate([
  45731. BABYLON.serialize(),
  45732. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45733. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  45734. __decorate([
  45735. BABYLON.serialize(),
  45736. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  45737. ], PBRMaterial.prototype, "unlit", void 0);
  45738. return PBRMaterial;
  45739. }(BABYLON.PBRBaseMaterial));
  45740. BABYLON.PBRMaterial = PBRMaterial;
  45741. })(BABYLON || (BABYLON = {}));
  45742. //# sourceMappingURL=babylon.pbrMaterial.js.map
  45743. var BABYLON;
  45744. (function (BABYLON) {
  45745. /**
  45746. * The PBR material of BJS following the metal roughness convention.
  45747. *
  45748. * This fits to the PBR convention in the GLTF definition:
  45749. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  45750. */
  45751. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  45752. __extends(PBRMetallicRoughnessMaterial, _super);
  45753. /**
  45754. * Instantiates a new PBRMetalRoughnessMaterial instance.
  45755. *
  45756. * @param name The material name
  45757. * @param scene The scene the material will be use in.
  45758. */
  45759. function PBRMetallicRoughnessMaterial(name, scene) {
  45760. var _this = _super.call(this, name, scene) || this;
  45761. _this._useRoughnessFromMetallicTextureAlpha = false;
  45762. _this._useRoughnessFromMetallicTextureGreen = true;
  45763. _this._useMetallnessFromMetallicTextureBlue = true;
  45764. _this.metallic = 1.0;
  45765. _this.roughness = 1.0;
  45766. return _this;
  45767. }
  45768. /**
  45769. * Return the currrent class name of the material.
  45770. */
  45771. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  45772. return "PBRMetallicRoughnessMaterial";
  45773. };
  45774. /**
  45775. * Return the active textures of the material.
  45776. */
  45777. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  45778. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45779. if (this.baseTexture) {
  45780. activeTextures.push(this.baseTexture);
  45781. }
  45782. if (this.metallicRoughnessTexture) {
  45783. activeTextures.push(this.metallicRoughnessTexture);
  45784. }
  45785. return activeTextures;
  45786. };
  45787. /**
  45788. * Checks to see if a texture is used in the material.
  45789. * @param texture - Base texture to use.
  45790. * @returns - Boolean specifying if a texture is used in the material.
  45791. */
  45792. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  45793. if (_super.prototype.hasTexture.call(this, texture)) {
  45794. return true;
  45795. }
  45796. if (this.baseTexture === texture) {
  45797. return true;
  45798. }
  45799. if (this.metallicRoughnessTexture === texture) {
  45800. return true;
  45801. }
  45802. return false;
  45803. };
  45804. /**
  45805. * Makes a duplicate of the current material.
  45806. * @param name - name to use for the new material.
  45807. */
  45808. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  45809. var _this = this;
  45810. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  45811. clone.id = name;
  45812. clone.name = name;
  45813. return clone;
  45814. };
  45815. /**
  45816. * Serialize the material to a parsable JSON object.
  45817. */
  45818. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  45819. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45820. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  45821. return serializationObject;
  45822. };
  45823. /**
  45824. * Parses a JSON object correponding to the serialize function.
  45825. */
  45826. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  45827. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  45828. };
  45829. __decorate([
  45830. BABYLON.serializeAsColor3(),
  45831. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45832. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  45833. __decorate([
  45834. BABYLON.serializeAsTexture(),
  45835. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45836. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  45837. __decorate([
  45838. BABYLON.serialize(),
  45839. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45840. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  45841. __decorate([
  45842. BABYLON.serialize(),
  45843. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45844. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  45845. __decorate([
  45846. BABYLON.serializeAsTexture(),
  45847. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  45848. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  45849. return PBRMetallicRoughnessMaterial;
  45850. }(BABYLON.PBRBaseSimpleMaterial));
  45851. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  45852. })(BABYLON || (BABYLON = {}));
  45853. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  45854. var BABYLON;
  45855. (function (BABYLON) {
  45856. /**
  45857. * The PBR material of BJS following the specular glossiness convention.
  45858. *
  45859. * This fits to the PBR convention in the GLTF definition:
  45860. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  45861. */
  45862. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  45863. __extends(PBRSpecularGlossinessMaterial, _super);
  45864. /**
  45865. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  45866. *
  45867. * @param name The material name
  45868. * @param scene The scene the material will be use in.
  45869. */
  45870. function PBRSpecularGlossinessMaterial(name, scene) {
  45871. var _this = _super.call(this, name, scene) || this;
  45872. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  45873. return _this;
  45874. }
  45875. /**
  45876. * Return the currrent class name of the material.
  45877. */
  45878. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  45879. return "PBRSpecularGlossinessMaterial";
  45880. };
  45881. /**
  45882. * Return the active textures of the material.
  45883. */
  45884. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  45885. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45886. if (this.diffuseTexture) {
  45887. activeTextures.push(this.diffuseTexture);
  45888. }
  45889. if (this.specularGlossinessTexture) {
  45890. activeTextures.push(this.specularGlossinessTexture);
  45891. }
  45892. return activeTextures;
  45893. };
  45894. /**
  45895. * Checks to see if a texture is used in the material.
  45896. * @param texture - Base texture to use.
  45897. * @returns - Boolean specifying if a texture is used in the material.
  45898. */
  45899. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  45900. if (_super.prototype.hasTexture.call(this, texture)) {
  45901. return true;
  45902. }
  45903. if (this.diffuseTexture === texture) {
  45904. return true;
  45905. }
  45906. if (this.specularGlossinessTexture === texture) {
  45907. return true;
  45908. }
  45909. return false;
  45910. };
  45911. /**
  45912. * Makes a duplicate of the current material.
  45913. * @param name - name to use for the new material.
  45914. */
  45915. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  45916. var _this = this;
  45917. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  45918. clone.id = name;
  45919. clone.name = name;
  45920. return clone;
  45921. };
  45922. /**
  45923. * Serialize the material to a parsable JSON object.
  45924. */
  45925. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  45926. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45927. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  45928. return serializationObject;
  45929. };
  45930. /**
  45931. * Parses a JSON object correponding to the serialize function.
  45932. */
  45933. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  45934. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  45935. };
  45936. __decorate([
  45937. BABYLON.serializeAsColor3("diffuse"),
  45938. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45939. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  45940. __decorate([
  45941. BABYLON.serializeAsTexture(),
  45942. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45943. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  45944. __decorate([
  45945. BABYLON.serializeAsColor3("specular"),
  45946. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  45947. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  45948. __decorate([
  45949. BABYLON.serialize(),
  45950. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  45951. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  45952. __decorate([
  45953. BABYLON.serializeAsTexture(),
  45954. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  45955. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  45956. return PBRSpecularGlossinessMaterial;
  45957. }(BABYLON.PBRBaseSimpleMaterial));
  45958. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  45959. })(BABYLON || (BABYLON = {}));
  45960. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  45961. var BABYLON;
  45962. (function (BABYLON) {
  45963. BABYLON.CameraInputTypes = {};
  45964. var CameraInputsManager = /** @class */ (function () {
  45965. function CameraInputsManager(camera) {
  45966. this.attached = {};
  45967. this.camera = camera;
  45968. this.checkInputs = function () { };
  45969. }
  45970. /**
  45971. * Add an input method to a camera
  45972. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  45973. * @param input camera input method
  45974. */
  45975. CameraInputsManager.prototype.add = function (input) {
  45976. var type = input.getSimpleName();
  45977. if (this.attached[type]) {
  45978. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  45979. return;
  45980. }
  45981. this.attached[type] = input;
  45982. input.camera = this.camera;
  45983. //for checkInputs, we are dynamically creating a function
  45984. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  45985. if (input.checkInputs) {
  45986. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  45987. }
  45988. if (this.attachedElement) {
  45989. input.attachControl(this.attachedElement);
  45990. }
  45991. };
  45992. /**
  45993. * Remove a specific input method from a camera
  45994. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  45995. * @param inputToRemove camera input method
  45996. */
  45997. CameraInputsManager.prototype.remove = function (inputToRemove) {
  45998. for (var cam in this.attached) {
  45999. var input = this.attached[cam];
  46000. if (input === inputToRemove) {
  46001. input.detachControl(this.attachedElement);
  46002. input.camera = null;
  46003. delete this.attached[cam];
  46004. this.rebuildInputCheck();
  46005. }
  46006. }
  46007. };
  46008. CameraInputsManager.prototype.removeByType = function (inputType) {
  46009. for (var cam in this.attached) {
  46010. var input = this.attached[cam];
  46011. if (input.getClassName() === inputType) {
  46012. input.detachControl(this.attachedElement);
  46013. input.camera = null;
  46014. delete this.attached[cam];
  46015. this.rebuildInputCheck();
  46016. }
  46017. }
  46018. };
  46019. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  46020. var current = this.checkInputs;
  46021. return function () {
  46022. current();
  46023. fn();
  46024. };
  46025. };
  46026. CameraInputsManager.prototype.attachInput = function (input) {
  46027. if (this.attachedElement) {
  46028. input.attachControl(this.attachedElement, this.noPreventDefault);
  46029. }
  46030. };
  46031. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  46032. if (noPreventDefault === void 0) { noPreventDefault = false; }
  46033. if (this.attachedElement) {
  46034. return;
  46035. }
  46036. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  46037. this.attachedElement = element;
  46038. this.noPreventDefault = noPreventDefault;
  46039. for (var cam in this.attached) {
  46040. this.attached[cam].attachControl(element, noPreventDefault);
  46041. }
  46042. };
  46043. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  46044. if (disconnect === void 0) { disconnect = false; }
  46045. if (this.attachedElement !== element) {
  46046. return;
  46047. }
  46048. for (var cam in this.attached) {
  46049. this.attached[cam].detachControl(element);
  46050. if (disconnect) {
  46051. this.attached[cam].camera = null;
  46052. }
  46053. }
  46054. this.attachedElement = null;
  46055. };
  46056. CameraInputsManager.prototype.rebuildInputCheck = function () {
  46057. this.checkInputs = function () { };
  46058. for (var cam in this.attached) {
  46059. var input = this.attached[cam];
  46060. if (input.checkInputs) {
  46061. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46062. }
  46063. }
  46064. };
  46065. /**
  46066. * Remove all attached input methods from a camera
  46067. */
  46068. CameraInputsManager.prototype.clear = function () {
  46069. if (this.attachedElement) {
  46070. this.detachElement(this.attachedElement, true);
  46071. }
  46072. this.attached = {};
  46073. this.attachedElement = null;
  46074. this.checkInputs = function () { };
  46075. };
  46076. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  46077. var inputs = {};
  46078. for (var cam in this.attached) {
  46079. var input = this.attached[cam];
  46080. var res = BABYLON.SerializationHelper.Serialize(input);
  46081. inputs[input.getClassName()] = res;
  46082. }
  46083. serializedCamera.inputsmgr = inputs;
  46084. };
  46085. CameraInputsManager.prototype.parse = function (parsedCamera) {
  46086. var parsedInputs = parsedCamera.inputsmgr;
  46087. if (parsedInputs) {
  46088. this.clear();
  46089. for (var n in parsedInputs) {
  46090. var construct = BABYLON.CameraInputTypes[n];
  46091. if (construct) {
  46092. var parsedinput = parsedInputs[n];
  46093. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  46094. this.add(input);
  46095. }
  46096. }
  46097. }
  46098. else {
  46099. //2016-03-08 this part is for managing backward compatibility
  46100. for (var n in this.attached) {
  46101. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  46102. if (construct) {
  46103. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  46104. this.remove(this.attached[n]);
  46105. this.add(input);
  46106. }
  46107. }
  46108. }
  46109. };
  46110. return CameraInputsManager;
  46111. }());
  46112. BABYLON.CameraInputsManager = CameraInputsManager;
  46113. })(BABYLON || (BABYLON = {}));
  46114. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  46115. var BABYLON;
  46116. (function (BABYLON) {
  46117. var TargetCamera = /** @class */ (function (_super) {
  46118. __extends(TargetCamera, _super);
  46119. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46120. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46121. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46122. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46123. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  46124. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  46125. _this.speed = 2.0;
  46126. _this.noRotationConstraint = false;
  46127. _this.lockedTarget = null;
  46128. /** @hidden */
  46129. _this._currentTarget = BABYLON.Vector3.Zero();
  46130. /** @hidden */
  46131. _this._viewMatrix = BABYLON.Matrix.Zero();
  46132. /** @hidden */
  46133. _this._camMatrix = BABYLON.Matrix.Zero();
  46134. /** @hidden */
  46135. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  46136. /** @hidden */
  46137. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  46138. /** @hidden */
  46139. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  46140. /** @hidden */
  46141. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  46142. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  46143. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  46144. _this._defaultUp = BABYLON.Vector3.Up();
  46145. _this._cachedRotationZ = 0;
  46146. return _this;
  46147. }
  46148. TargetCamera.prototype.getFrontPosition = function (distance) {
  46149. this.getWorldMatrix();
  46150. var direction = this.getTarget().subtract(this.position);
  46151. direction.normalize();
  46152. direction.scaleInPlace(distance);
  46153. return this.globalPosition.add(direction);
  46154. };
  46155. /** @hidden */
  46156. TargetCamera.prototype._getLockedTargetPosition = function () {
  46157. if (!this.lockedTarget) {
  46158. return null;
  46159. }
  46160. if (this.lockedTarget.absolutePosition) {
  46161. this.lockedTarget.computeWorldMatrix();
  46162. }
  46163. return this.lockedTarget.absolutePosition || this.lockedTarget;
  46164. };
  46165. TargetCamera.prototype.storeState = function () {
  46166. this._storedPosition = this.position.clone();
  46167. this._storedRotation = this.rotation.clone();
  46168. if (this.rotationQuaternion) {
  46169. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  46170. }
  46171. return _super.prototype.storeState.call(this);
  46172. };
  46173. /**
  46174. * Restored camera state. You must call storeState() first
  46175. * @returns whether it was successful or not
  46176. * @hidden
  46177. */
  46178. TargetCamera.prototype._restoreStateValues = function () {
  46179. if (!_super.prototype._restoreStateValues.call(this)) {
  46180. return false;
  46181. }
  46182. this.position = this._storedPosition.clone();
  46183. this.rotation = this._storedRotation.clone();
  46184. if (this.rotationQuaternion) {
  46185. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  46186. }
  46187. this.cameraDirection.copyFromFloats(0, 0, 0);
  46188. this.cameraRotation.copyFromFloats(0, 0);
  46189. return true;
  46190. };
  46191. // Cache
  46192. /** @hidden */
  46193. TargetCamera.prototype._initCache = function () {
  46194. _super.prototype._initCache.call(this);
  46195. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46196. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46197. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46198. };
  46199. /** @hidden */
  46200. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  46201. if (!ignoreParentClass) {
  46202. _super.prototype._updateCache.call(this);
  46203. }
  46204. var lockedTargetPosition = this._getLockedTargetPosition();
  46205. if (!lockedTargetPosition) {
  46206. this._cache.lockedTarget = null;
  46207. }
  46208. else {
  46209. if (!this._cache.lockedTarget) {
  46210. this._cache.lockedTarget = lockedTargetPosition.clone();
  46211. }
  46212. else {
  46213. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  46214. }
  46215. }
  46216. this._cache.rotation.copyFrom(this.rotation);
  46217. if (this.rotationQuaternion)
  46218. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46219. };
  46220. // Synchronized
  46221. /** @hidden */
  46222. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  46223. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  46224. return false;
  46225. }
  46226. var lockedTargetPosition = this._getLockedTargetPosition();
  46227. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  46228. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  46229. };
  46230. // Methods
  46231. /** @hidden */
  46232. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  46233. var engine = this.getEngine();
  46234. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  46235. };
  46236. // Target
  46237. /** @hidden */
  46238. TargetCamera.prototype.setTarget = function (target) {
  46239. this.upVector.normalize();
  46240. if (this.position.z === target.z) {
  46241. this.position.z += BABYLON.Epsilon;
  46242. }
  46243. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUp, this._camMatrix);
  46244. this._camMatrix.invert();
  46245. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  46246. var vDir = target.subtract(this.position);
  46247. if (vDir.x >= 0.0) {
  46248. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  46249. }
  46250. else {
  46251. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  46252. }
  46253. this.rotation.z = 0;
  46254. if (isNaN(this.rotation.x)) {
  46255. this.rotation.x = 0;
  46256. }
  46257. if (isNaN(this.rotation.y)) {
  46258. this.rotation.y = 0;
  46259. }
  46260. if (isNaN(this.rotation.z)) {
  46261. this.rotation.z = 0;
  46262. }
  46263. if (this.rotationQuaternion) {
  46264. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46265. }
  46266. };
  46267. /**
  46268. * Return the current target position of the camera. This value is expressed in local space.
  46269. */
  46270. TargetCamera.prototype.getTarget = function () {
  46271. return this._currentTarget;
  46272. };
  46273. /** @hidden */
  46274. TargetCamera.prototype._decideIfNeedsToMove = function () {
  46275. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46276. };
  46277. /** @hidden */
  46278. TargetCamera.prototype._updatePosition = function () {
  46279. if (this.parent) {
  46280. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  46281. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  46282. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  46283. return;
  46284. }
  46285. this.position.addInPlace(this.cameraDirection);
  46286. };
  46287. /** @hidden */
  46288. TargetCamera.prototype._checkInputs = function () {
  46289. var needToMove = this._decideIfNeedsToMove();
  46290. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  46291. // Move
  46292. if (needToMove) {
  46293. this._updatePosition();
  46294. }
  46295. // Rotate
  46296. if (needToRotate) {
  46297. this.rotation.x += this.cameraRotation.x;
  46298. this.rotation.y += this.cameraRotation.y;
  46299. //rotate, if quaternion is set and rotation was used
  46300. if (this.rotationQuaternion) {
  46301. var len = this.rotation.lengthSquared();
  46302. if (len) {
  46303. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46304. }
  46305. }
  46306. if (!this.noRotationConstraint) {
  46307. var limit = (Math.PI / 2) * 0.95;
  46308. if (this.rotation.x > limit)
  46309. this.rotation.x = limit;
  46310. if (this.rotation.x < -limit)
  46311. this.rotation.x = -limit;
  46312. }
  46313. }
  46314. // Inertia
  46315. if (needToMove) {
  46316. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  46317. this.cameraDirection.x = 0;
  46318. }
  46319. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  46320. this.cameraDirection.y = 0;
  46321. }
  46322. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  46323. this.cameraDirection.z = 0;
  46324. }
  46325. this.cameraDirection.scaleInPlace(this.inertia);
  46326. }
  46327. if (needToRotate) {
  46328. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  46329. this.cameraRotation.x = 0;
  46330. }
  46331. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  46332. this.cameraRotation.y = 0;
  46333. }
  46334. this.cameraRotation.scaleInPlace(this.inertia);
  46335. }
  46336. _super.prototype._checkInputs.call(this);
  46337. };
  46338. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  46339. if (this.rotationQuaternion) {
  46340. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  46341. }
  46342. else {
  46343. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  46344. }
  46345. };
  46346. /**
  46347. * 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)
  46348. * @returns the current camera
  46349. */
  46350. TargetCamera.prototype._rotateUpVectorWithCameraRotationMatrix = function () {
  46351. BABYLON.Vector3.TransformNormalToRef(this._defaultUp, this._cameraRotationMatrix, this.upVector);
  46352. return this;
  46353. };
  46354. /** @hidden */
  46355. TargetCamera.prototype._getViewMatrix = function () {
  46356. if (this.lockedTarget) {
  46357. this.setTarget(this._getLockedTargetPosition());
  46358. }
  46359. // Compute
  46360. this._updateCameraRotationMatrix();
  46361. // Apply the changed rotation to the upVector.
  46362. if (this._cachedRotationZ != this.rotation.z) {
  46363. this._rotateUpVectorWithCameraRotationMatrix();
  46364. this._cachedRotationZ = this.rotation.z;
  46365. }
  46366. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  46367. // Computing target and final matrix
  46368. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  46369. this._computeViewMatrix(this.position, this._currentTarget, this.upVector);
  46370. return this._viewMatrix;
  46371. };
  46372. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  46373. if (this.parent) {
  46374. var parentWorldMatrix = this.parent.getWorldMatrix();
  46375. BABYLON.Vector3.TransformCoordinatesToRef(position, parentWorldMatrix, this._globalPosition);
  46376. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  46377. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  46378. this._markSyncedWithParent();
  46379. }
  46380. else {
  46381. this._globalPosition.copyFrom(position);
  46382. this._globalCurrentTarget.copyFrom(target);
  46383. this._globalCurrentUpVector.copyFrom(up);
  46384. }
  46385. if (this.getScene().useRightHandedSystem) {
  46386. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46387. }
  46388. else {
  46389. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46390. }
  46391. };
  46392. /**
  46393. * @override
  46394. * Override Camera.createRigCamera
  46395. */
  46396. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  46397. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  46398. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  46399. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  46400. if (!this.rotationQuaternion) {
  46401. this.rotationQuaternion = new BABYLON.Quaternion();
  46402. }
  46403. rigCamera._cameraRigParams = {};
  46404. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  46405. }
  46406. return rigCamera;
  46407. }
  46408. return null;
  46409. };
  46410. /**
  46411. * @hidden
  46412. * @override
  46413. * Override Camera._updateRigCameras
  46414. */
  46415. TargetCamera.prototype._updateRigCameras = function () {
  46416. var camLeft = this._rigCameras[0];
  46417. var camRight = this._rigCameras[1];
  46418. switch (this.cameraRigMode) {
  46419. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  46420. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  46421. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  46422. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  46423. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  46424. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  46425. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  46426. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  46427. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  46428. camLeft.setTarget(this.getTarget());
  46429. camRight.setTarget(this.getTarget());
  46430. break;
  46431. case BABYLON.Camera.RIG_MODE_VR:
  46432. if (camLeft.rotationQuaternion) {
  46433. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46434. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46435. }
  46436. else {
  46437. camLeft.rotation.copyFrom(this.rotation);
  46438. camRight.rotation.copyFrom(this.rotation);
  46439. }
  46440. camLeft.position.copyFrom(this.position);
  46441. camRight.position.copyFrom(this.position);
  46442. break;
  46443. }
  46444. _super.prototype._updateRigCameras.call(this);
  46445. };
  46446. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  46447. if (!this._rigCamTransformMatrix) {
  46448. this._rigCamTransformMatrix = new BABYLON.Matrix();
  46449. }
  46450. var target = this.getTarget();
  46451. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  46452. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  46453. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  46454. };
  46455. TargetCamera.prototype.getClassName = function () {
  46456. return "TargetCamera";
  46457. };
  46458. __decorate([
  46459. BABYLON.serializeAsVector3()
  46460. ], TargetCamera.prototype, "rotation", void 0);
  46461. __decorate([
  46462. BABYLON.serialize()
  46463. ], TargetCamera.prototype, "speed", void 0);
  46464. __decorate([
  46465. BABYLON.serializeAsMeshReference("lockedTargetId")
  46466. ], TargetCamera.prototype, "lockedTarget", void 0);
  46467. return TargetCamera;
  46468. }(BABYLON.Camera));
  46469. BABYLON.TargetCamera = TargetCamera;
  46470. })(BABYLON || (BABYLON = {}));
  46471. //# sourceMappingURL=babylon.targetCamera.js.map
  46472. var BABYLON;
  46473. (function (BABYLON) {
  46474. var FreeCameraMouseInput = /** @class */ (function () {
  46475. function FreeCameraMouseInput(touchEnabled) {
  46476. if (touchEnabled === void 0) { touchEnabled = true; }
  46477. this.touchEnabled = touchEnabled;
  46478. this.buttons = [0, 1, 2];
  46479. this.angularSensibility = 2000.0;
  46480. this.previousPosition = null;
  46481. }
  46482. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  46483. var _this = this;
  46484. var engine = this.camera.getEngine();
  46485. if (!this._pointerInput) {
  46486. this._pointerInput = function (p, s) {
  46487. var evt = p.event;
  46488. if (engine.isInVRExclusivePointerMode) {
  46489. return;
  46490. }
  46491. if (!_this.touchEnabled && evt.pointerType === "touch") {
  46492. return;
  46493. }
  46494. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  46495. return;
  46496. }
  46497. var srcElement = (evt.srcElement || evt.target);
  46498. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  46499. try {
  46500. srcElement.setPointerCapture(evt.pointerId);
  46501. }
  46502. catch (e) {
  46503. //Nothing to do with the error. Execution will continue.
  46504. }
  46505. _this.previousPosition = {
  46506. x: evt.clientX,
  46507. y: evt.clientY
  46508. };
  46509. if (!noPreventDefault) {
  46510. evt.preventDefault();
  46511. element.focus();
  46512. }
  46513. }
  46514. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  46515. try {
  46516. srcElement.releasePointerCapture(evt.pointerId);
  46517. }
  46518. catch (e) {
  46519. //Nothing to do with the error.
  46520. }
  46521. _this.previousPosition = null;
  46522. if (!noPreventDefault) {
  46523. evt.preventDefault();
  46524. }
  46525. }
  46526. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  46527. if (!_this.previousPosition || engine.isPointerLock) {
  46528. return;
  46529. }
  46530. var offsetX = evt.clientX - _this.previousPosition.x;
  46531. if (_this.camera.getScene().useRightHandedSystem)
  46532. offsetX *= -1;
  46533. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46534. offsetX *= -1;
  46535. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46536. var offsetY = evt.clientY - _this.previousPosition.y;
  46537. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46538. _this.previousPosition = {
  46539. x: evt.clientX,
  46540. y: evt.clientY
  46541. };
  46542. if (!noPreventDefault) {
  46543. evt.preventDefault();
  46544. }
  46545. }
  46546. };
  46547. }
  46548. this._onMouseMove = function (evt) {
  46549. if (!engine.isPointerLock) {
  46550. return;
  46551. }
  46552. if (engine.isInVRExclusivePointerMode) {
  46553. return;
  46554. }
  46555. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  46556. if (_this.camera.getScene().useRightHandedSystem)
  46557. offsetX *= -1;
  46558. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46559. offsetX *= -1;
  46560. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46561. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  46562. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46563. _this.previousPosition = null;
  46564. if (!noPreventDefault) {
  46565. evt.preventDefault();
  46566. }
  46567. };
  46568. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  46569. element.addEventListener("mousemove", this._onMouseMove, false);
  46570. };
  46571. FreeCameraMouseInput.prototype.detachControl = function (element) {
  46572. if (this._observer && element) {
  46573. this.camera.getScene().onPointerObservable.remove(this._observer);
  46574. if (this._onMouseMove) {
  46575. element.removeEventListener("mousemove", this._onMouseMove);
  46576. }
  46577. this._observer = null;
  46578. this._onMouseMove = null;
  46579. this.previousPosition = null;
  46580. }
  46581. };
  46582. FreeCameraMouseInput.prototype.getClassName = function () {
  46583. return "FreeCameraMouseInput";
  46584. };
  46585. FreeCameraMouseInput.prototype.getSimpleName = function () {
  46586. return "mouse";
  46587. };
  46588. __decorate([
  46589. BABYLON.serialize()
  46590. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  46591. __decorate([
  46592. BABYLON.serialize()
  46593. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  46594. return FreeCameraMouseInput;
  46595. }());
  46596. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  46597. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  46598. })(BABYLON || (BABYLON = {}));
  46599. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  46600. var BABYLON;
  46601. (function (BABYLON) {
  46602. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  46603. function FreeCameraKeyboardMoveInput() {
  46604. this._keys = new Array();
  46605. this.keysUp = [38];
  46606. this.keysDown = [40];
  46607. this.keysLeft = [37];
  46608. this.keysRight = [39];
  46609. }
  46610. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46611. var _this = this;
  46612. if (this._onCanvasBlurObserver) {
  46613. return;
  46614. }
  46615. this._scene = this.camera.getScene();
  46616. this._engine = this._scene.getEngine();
  46617. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46618. _this._keys = [];
  46619. });
  46620. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46621. var evt = info.event;
  46622. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46623. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46624. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46625. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46626. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46627. var index = _this._keys.indexOf(evt.keyCode);
  46628. if (index === -1) {
  46629. _this._keys.push(evt.keyCode);
  46630. }
  46631. if (!noPreventDefault) {
  46632. evt.preventDefault();
  46633. }
  46634. }
  46635. }
  46636. else {
  46637. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46638. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46639. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46640. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46641. var index = _this._keys.indexOf(evt.keyCode);
  46642. if (index >= 0) {
  46643. _this._keys.splice(index, 1);
  46644. }
  46645. if (!noPreventDefault) {
  46646. evt.preventDefault();
  46647. }
  46648. }
  46649. }
  46650. });
  46651. };
  46652. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46653. if (this._scene) {
  46654. if (this._onKeyboardObserver) {
  46655. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46656. }
  46657. if (this._onCanvasBlurObserver) {
  46658. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46659. }
  46660. this._onKeyboardObserver = null;
  46661. this._onCanvasBlurObserver = null;
  46662. }
  46663. this._keys = [];
  46664. };
  46665. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46666. if (this._onKeyboardObserver) {
  46667. var camera = this.camera;
  46668. // Keyboard
  46669. for (var index = 0; index < this._keys.length; index++) {
  46670. var keyCode = this._keys[index];
  46671. var speed = camera._computeLocalCameraSpeed();
  46672. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46673. camera._localDirection.copyFromFloats(-speed, 0, 0);
  46674. }
  46675. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46676. camera._localDirection.copyFromFloats(0, 0, speed);
  46677. }
  46678. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46679. camera._localDirection.copyFromFloats(speed, 0, 0);
  46680. }
  46681. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46682. camera._localDirection.copyFromFloats(0, 0, -speed);
  46683. }
  46684. if (camera.getScene().useRightHandedSystem) {
  46685. camera._localDirection.z *= -1;
  46686. }
  46687. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  46688. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  46689. camera.cameraDirection.addInPlace(camera._transformedDirection);
  46690. }
  46691. }
  46692. };
  46693. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  46694. return "FreeCameraKeyboardMoveInput";
  46695. };
  46696. /** @hidden */
  46697. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  46698. this._keys = [];
  46699. };
  46700. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  46701. return "keyboard";
  46702. };
  46703. __decorate([
  46704. BABYLON.serialize()
  46705. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  46706. __decorate([
  46707. BABYLON.serialize()
  46708. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  46709. __decorate([
  46710. BABYLON.serialize()
  46711. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  46712. __decorate([
  46713. BABYLON.serialize()
  46714. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  46715. return FreeCameraKeyboardMoveInput;
  46716. }());
  46717. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  46718. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  46719. })(BABYLON || (BABYLON = {}));
  46720. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  46721. var BABYLON;
  46722. (function (BABYLON) {
  46723. var FreeCameraInputsManager = /** @class */ (function (_super) {
  46724. __extends(FreeCameraInputsManager, _super);
  46725. function FreeCameraInputsManager(camera) {
  46726. return _super.call(this, camera) || this;
  46727. }
  46728. FreeCameraInputsManager.prototype.addKeyboard = function () {
  46729. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  46730. return this;
  46731. };
  46732. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  46733. if (touchEnabled === void 0) { touchEnabled = true; }
  46734. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  46735. return this;
  46736. };
  46737. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  46738. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  46739. return this;
  46740. };
  46741. FreeCameraInputsManager.prototype.addTouch = function () {
  46742. this.add(new BABYLON.FreeCameraTouchInput());
  46743. return this;
  46744. };
  46745. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  46746. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  46747. return this;
  46748. };
  46749. return FreeCameraInputsManager;
  46750. }(BABYLON.CameraInputsManager));
  46751. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  46752. })(BABYLON || (BABYLON = {}));
  46753. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  46754. var BABYLON;
  46755. (function (BABYLON) {
  46756. BABYLON.Node.AddNodeConstructor("FreeCamera", function (name, scene) {
  46757. // Forcing to use the Universal camera
  46758. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  46759. });
  46760. var FreeCamera = /** @class */ (function (_super) {
  46761. __extends(FreeCamera, _super);
  46762. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46763. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46764. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46765. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  46766. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  46767. _this.checkCollisions = false;
  46768. _this.applyGravity = false;
  46769. _this._needMoveForGravity = false;
  46770. _this._oldPosition = BABYLON.Vector3.Zero();
  46771. _this._diffPosition = BABYLON.Vector3.Zero();
  46772. _this._newPosition = BABYLON.Vector3.Zero();
  46773. // Collisions
  46774. _this._collisionMask = -1;
  46775. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  46776. if (collidedMesh === void 0) { collidedMesh = null; }
  46777. //TODO move this to the collision coordinator!
  46778. if (_this.getScene().workerCollisions)
  46779. newPosition.multiplyInPlace(_this._collider._radius);
  46780. var updatePosition = function (newPos) {
  46781. _this._newPosition.copyFrom(newPos);
  46782. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  46783. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  46784. _this.position.addInPlace(_this._diffPosition);
  46785. if (_this.onCollide && collidedMesh) {
  46786. _this.onCollide(collidedMesh);
  46787. }
  46788. }
  46789. };
  46790. updatePosition(newPosition);
  46791. };
  46792. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  46793. _this.inputs.addKeyboard().addMouse();
  46794. return _this;
  46795. }
  46796. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  46797. //-- begin properties for backward compatibility for inputs
  46798. /**
  46799. * Gets the input sensibility for a mouse input. (default is 2000.0)
  46800. * Higher values reduce sensitivity.
  46801. */
  46802. get: function () {
  46803. var mouse = this.inputs.attached["mouse"];
  46804. if (mouse)
  46805. return mouse.angularSensibility;
  46806. return 0;
  46807. },
  46808. /**
  46809. * Sets the input sensibility for a mouse input. (default is 2000.0)
  46810. * Higher values reduce sensitivity.
  46811. */
  46812. set: function (value) {
  46813. var mouse = this.inputs.attached["mouse"];
  46814. if (mouse)
  46815. mouse.angularSensibility = value;
  46816. },
  46817. enumerable: true,
  46818. configurable: true
  46819. });
  46820. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  46821. get: function () {
  46822. var keyboard = this.inputs.attached["keyboard"];
  46823. if (keyboard)
  46824. return keyboard.keysUp;
  46825. return [];
  46826. },
  46827. set: function (value) {
  46828. var keyboard = this.inputs.attached["keyboard"];
  46829. if (keyboard)
  46830. keyboard.keysUp = value;
  46831. },
  46832. enumerable: true,
  46833. configurable: true
  46834. });
  46835. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  46836. get: function () {
  46837. var keyboard = this.inputs.attached["keyboard"];
  46838. if (keyboard)
  46839. return keyboard.keysDown;
  46840. return [];
  46841. },
  46842. set: function (value) {
  46843. var keyboard = this.inputs.attached["keyboard"];
  46844. if (keyboard)
  46845. keyboard.keysDown = value;
  46846. },
  46847. enumerable: true,
  46848. configurable: true
  46849. });
  46850. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  46851. get: function () {
  46852. var keyboard = this.inputs.attached["keyboard"];
  46853. if (keyboard)
  46854. return keyboard.keysLeft;
  46855. return [];
  46856. },
  46857. set: function (value) {
  46858. var keyboard = this.inputs.attached["keyboard"];
  46859. if (keyboard)
  46860. keyboard.keysLeft = value;
  46861. },
  46862. enumerable: true,
  46863. configurable: true
  46864. });
  46865. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  46866. get: function () {
  46867. var keyboard = this.inputs.attached["keyboard"];
  46868. if (keyboard)
  46869. return keyboard.keysRight;
  46870. return [];
  46871. },
  46872. set: function (value) {
  46873. var keyboard = this.inputs.attached["keyboard"];
  46874. if (keyboard)
  46875. keyboard.keysRight = value;
  46876. },
  46877. enumerable: true,
  46878. configurable: true
  46879. });
  46880. // Controls
  46881. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  46882. this.inputs.attachElement(element, noPreventDefault);
  46883. };
  46884. FreeCamera.prototype.detachControl = function (element) {
  46885. this.inputs.detachElement(element);
  46886. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46887. this.cameraRotation = new BABYLON.Vector2(0, 0);
  46888. };
  46889. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  46890. get: function () {
  46891. return this._collisionMask;
  46892. },
  46893. set: function (mask) {
  46894. this._collisionMask = !isNaN(mask) ? mask : -1;
  46895. },
  46896. enumerable: true,
  46897. configurable: true
  46898. });
  46899. /** @hidden */
  46900. FreeCamera.prototype._collideWithWorld = function (displacement) {
  46901. var globalPosition;
  46902. if (this.parent) {
  46903. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  46904. }
  46905. else {
  46906. globalPosition = this.position;
  46907. }
  46908. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  46909. this._oldPosition.addInPlace(this.ellipsoidOffset);
  46910. if (!this._collider) {
  46911. this._collider = new BABYLON.Collider();
  46912. }
  46913. this._collider._radius = this.ellipsoid;
  46914. this._collider.collisionMask = this._collisionMask;
  46915. //no need for clone, as long as gravity is not on.
  46916. var actualDisplacement = displacement;
  46917. //add gravity to the direction to prevent the dual-collision checking
  46918. if (this.applyGravity) {
  46919. //this prevents mending with cameraDirection, a global variable of the free camera class.
  46920. actualDisplacement = displacement.add(this.getScene().gravity);
  46921. }
  46922. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  46923. };
  46924. /** @hidden */
  46925. FreeCamera.prototype._checkInputs = function () {
  46926. if (!this._localDirection) {
  46927. this._localDirection = BABYLON.Vector3.Zero();
  46928. this._transformedDirection = BABYLON.Vector3.Zero();
  46929. }
  46930. this.inputs.checkInputs();
  46931. _super.prototype._checkInputs.call(this);
  46932. };
  46933. /** @hidden */
  46934. FreeCamera.prototype._decideIfNeedsToMove = function () {
  46935. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46936. };
  46937. /** @hidden */
  46938. FreeCamera.prototype._updatePosition = function () {
  46939. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  46940. this._collideWithWorld(this.cameraDirection);
  46941. }
  46942. else {
  46943. _super.prototype._updatePosition.call(this);
  46944. }
  46945. };
  46946. FreeCamera.prototype.dispose = function () {
  46947. this.inputs.clear();
  46948. _super.prototype.dispose.call(this);
  46949. };
  46950. FreeCamera.prototype.getClassName = function () {
  46951. return "FreeCamera";
  46952. };
  46953. __decorate([
  46954. BABYLON.serializeAsVector3()
  46955. ], FreeCamera.prototype, "ellipsoid", void 0);
  46956. __decorate([
  46957. BABYLON.serializeAsVector3()
  46958. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  46959. __decorate([
  46960. BABYLON.serialize()
  46961. ], FreeCamera.prototype, "checkCollisions", void 0);
  46962. __decorate([
  46963. BABYLON.serialize()
  46964. ], FreeCamera.prototype, "applyGravity", void 0);
  46965. return FreeCamera;
  46966. }(BABYLON.TargetCamera));
  46967. BABYLON.FreeCamera = FreeCamera;
  46968. })(BABYLON || (BABYLON = {}));
  46969. //# sourceMappingURL=babylon.freeCamera.js.map
  46970. var BABYLON;
  46971. (function (BABYLON) {
  46972. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  46973. function ArcRotateCameraKeyboardMoveInput() {
  46974. this._keys = new Array();
  46975. this.keysUp = [38];
  46976. this.keysDown = [40];
  46977. this.keysLeft = [37];
  46978. this.keysRight = [39];
  46979. this.keysReset = [220];
  46980. this.panningSensibility = 50.0;
  46981. this.zoomingSensibility = 25.0;
  46982. this.useAltToZoom = true;
  46983. }
  46984. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46985. var _this = this;
  46986. if (this._onCanvasBlurObserver) {
  46987. return;
  46988. }
  46989. this._scene = this.camera.getScene();
  46990. this._engine = this._scene.getEngine();
  46991. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46992. _this._keys = [];
  46993. });
  46994. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46995. var evt = info.event;
  46996. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46997. _this._ctrlPressed = evt.ctrlKey;
  46998. _this._altPressed = evt.altKey;
  46999. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47000. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47001. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47002. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47003. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47004. var index = _this._keys.indexOf(evt.keyCode);
  47005. if (index === -1) {
  47006. _this._keys.push(evt.keyCode);
  47007. }
  47008. if (evt.preventDefault) {
  47009. if (!noPreventDefault) {
  47010. evt.preventDefault();
  47011. }
  47012. }
  47013. }
  47014. }
  47015. else {
  47016. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47017. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47018. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47019. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47020. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47021. var index = _this._keys.indexOf(evt.keyCode);
  47022. if (index >= 0) {
  47023. _this._keys.splice(index, 1);
  47024. }
  47025. if (evt.preventDefault) {
  47026. if (!noPreventDefault) {
  47027. evt.preventDefault();
  47028. }
  47029. }
  47030. }
  47031. }
  47032. });
  47033. };
  47034. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47035. if (this._scene) {
  47036. if (this._onKeyboardObserver) {
  47037. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47038. }
  47039. if (this._onCanvasBlurObserver) {
  47040. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47041. }
  47042. this._onKeyboardObserver = null;
  47043. this._onCanvasBlurObserver = null;
  47044. }
  47045. this._keys = [];
  47046. };
  47047. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47048. if (this._onKeyboardObserver) {
  47049. var camera = this.camera;
  47050. for (var index = 0; index < this._keys.length; index++) {
  47051. var keyCode = this._keys[index];
  47052. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47053. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47054. camera.inertialPanningX -= 1 / this.panningSensibility;
  47055. }
  47056. else {
  47057. camera.inertialAlphaOffset -= 0.01;
  47058. }
  47059. }
  47060. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47061. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47062. camera.inertialPanningY += 1 / this.panningSensibility;
  47063. }
  47064. else if (this._altPressed && this.useAltToZoom) {
  47065. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  47066. }
  47067. else {
  47068. camera.inertialBetaOffset -= 0.01;
  47069. }
  47070. }
  47071. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47072. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47073. camera.inertialPanningX += 1 / this.panningSensibility;
  47074. }
  47075. else {
  47076. camera.inertialAlphaOffset += 0.01;
  47077. }
  47078. }
  47079. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47080. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47081. camera.inertialPanningY -= 1 / this.panningSensibility;
  47082. }
  47083. else if (this._altPressed && this.useAltToZoom) {
  47084. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  47085. }
  47086. else {
  47087. camera.inertialBetaOffset += 0.01;
  47088. }
  47089. }
  47090. else if (this.keysReset.indexOf(keyCode) !== -1) {
  47091. camera.restoreState();
  47092. }
  47093. }
  47094. }
  47095. };
  47096. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  47097. return "ArcRotateCameraKeyboardMoveInput";
  47098. };
  47099. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47100. return "keyboard";
  47101. };
  47102. __decorate([
  47103. BABYLON.serialize()
  47104. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47105. __decorate([
  47106. BABYLON.serialize()
  47107. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47108. __decorate([
  47109. BABYLON.serialize()
  47110. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47111. __decorate([
  47112. BABYLON.serialize()
  47113. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47114. __decorate([
  47115. BABYLON.serialize()
  47116. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  47117. __decorate([
  47118. BABYLON.serialize()
  47119. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  47120. __decorate([
  47121. BABYLON.serialize()
  47122. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  47123. __decorate([
  47124. BABYLON.serialize()
  47125. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  47126. return ArcRotateCameraKeyboardMoveInput;
  47127. }());
  47128. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  47129. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  47130. })(BABYLON || (BABYLON = {}));
  47131. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  47132. var BABYLON;
  47133. (function (BABYLON) {
  47134. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  47135. function ArcRotateCameraMouseWheelInput() {
  47136. this.wheelPrecision = 3.0;
  47137. /**
  47138. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  47139. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  47140. */
  47141. this.wheelDeltaPercentage = 0;
  47142. }
  47143. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  47144. var _this = this;
  47145. this._wheel = function (p, s) {
  47146. //sanity check - this should be a PointerWheel event.
  47147. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  47148. return;
  47149. var event = p.event;
  47150. var delta = 0;
  47151. if (event.wheelDelta) {
  47152. if (_this.wheelDeltaPercentage) {
  47153. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  47154. if (event.wheelDelta > 0) {
  47155. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  47156. }
  47157. else {
  47158. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  47159. }
  47160. }
  47161. else {
  47162. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  47163. }
  47164. }
  47165. else if (event.detail) {
  47166. delta = -event.detail / _this.wheelPrecision;
  47167. }
  47168. if (delta)
  47169. _this.camera.inertialRadiusOffset += delta;
  47170. if (event.preventDefault) {
  47171. if (!noPreventDefault) {
  47172. event.preventDefault();
  47173. }
  47174. }
  47175. };
  47176. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  47177. };
  47178. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  47179. if (this._observer && element) {
  47180. this.camera.getScene().onPointerObservable.remove(this._observer);
  47181. this._observer = null;
  47182. this._wheel = null;
  47183. }
  47184. };
  47185. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  47186. return "ArcRotateCameraMouseWheelInput";
  47187. };
  47188. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  47189. return "mousewheel";
  47190. };
  47191. __decorate([
  47192. BABYLON.serialize()
  47193. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  47194. __decorate([
  47195. BABYLON.serialize()
  47196. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  47197. return ArcRotateCameraMouseWheelInput;
  47198. }());
  47199. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  47200. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  47201. })(BABYLON || (BABYLON = {}));
  47202. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  47203. var BABYLON;
  47204. (function (BABYLON) {
  47205. var ArcRotateCameraPointersInput = /** @class */ (function () {
  47206. function ArcRotateCameraPointersInput() {
  47207. this.buttons = [0, 1, 2];
  47208. this.angularSensibilityX = 1000.0;
  47209. this.angularSensibilityY = 1000.0;
  47210. this.pinchPrecision = 12.0;
  47211. /**
  47212. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  47213. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  47214. */
  47215. this.pinchDeltaPercentage = 0;
  47216. this.panningSensibility = 1000.0;
  47217. this.multiTouchPanning = true;
  47218. this.multiTouchPanAndZoom = true;
  47219. this._isPanClick = false;
  47220. this.pinchInwards = true;
  47221. }
  47222. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  47223. var _this = this;
  47224. var engine = this.camera.getEngine();
  47225. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  47226. var pointA = null;
  47227. var pointB = null;
  47228. var previousPinchSquaredDistance = 0;
  47229. var initialDistance = 0;
  47230. var twoFingerActivityCount = 0;
  47231. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  47232. this._pointerInput = function (p, s) {
  47233. var evt = p.event;
  47234. var isTouch = p.event.pointerType === "touch";
  47235. if (engine.isInVRExclusivePointerMode) {
  47236. return;
  47237. }
  47238. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47239. return;
  47240. }
  47241. var srcElement = (evt.srcElement || evt.target);
  47242. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47243. try {
  47244. srcElement.setPointerCapture(evt.pointerId);
  47245. }
  47246. catch (e) {
  47247. //Nothing to do with the error. Execution will continue.
  47248. }
  47249. // Manage panning with pan button click
  47250. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  47251. // manage pointers
  47252. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  47253. if (pointA === null) {
  47254. pointA = cacheSoloPointer;
  47255. }
  47256. else if (pointB === null) {
  47257. pointB = cacheSoloPointer;
  47258. }
  47259. if (!noPreventDefault) {
  47260. evt.preventDefault();
  47261. element.focus();
  47262. }
  47263. }
  47264. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  47265. _this.camera.restoreState();
  47266. }
  47267. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47268. try {
  47269. srcElement.releasePointerCapture(evt.pointerId);
  47270. }
  47271. catch (e) {
  47272. //Nothing to do with the error.
  47273. }
  47274. cacheSoloPointer = null;
  47275. previousPinchSquaredDistance = 0;
  47276. previousMultiTouchPanPosition.isPaning = false;
  47277. previousMultiTouchPanPosition.isPinching = false;
  47278. twoFingerActivityCount = 0;
  47279. initialDistance = 0;
  47280. if (!isTouch) {
  47281. pointB = null; // Mouse and pen are mono pointer
  47282. }
  47283. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  47284. //but emptying completly pointers collection is required to fix a bug on iPhone :
  47285. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  47286. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  47287. if (engine._badOS) {
  47288. pointA = pointB = null;
  47289. }
  47290. else {
  47291. //only remove the impacted pointer in case of multitouch allowing on most
  47292. //platforms switching from rotate to zoom and pan seamlessly.
  47293. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  47294. pointA = pointB;
  47295. pointB = null;
  47296. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47297. }
  47298. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  47299. pointB = null;
  47300. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47301. }
  47302. else {
  47303. pointA = pointB = null;
  47304. }
  47305. }
  47306. if (!noPreventDefault) {
  47307. evt.preventDefault();
  47308. }
  47309. }
  47310. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47311. if (!noPreventDefault) {
  47312. evt.preventDefault();
  47313. }
  47314. // One button down
  47315. if (pointA && pointB === null && cacheSoloPointer) {
  47316. if (_this.panningSensibility !== 0 &&
  47317. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  47318. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  47319. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  47320. }
  47321. else {
  47322. var offsetX = evt.clientX - cacheSoloPointer.x;
  47323. var offsetY = evt.clientY - cacheSoloPointer.y;
  47324. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47325. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47326. }
  47327. cacheSoloPointer.x = evt.clientX;
  47328. cacheSoloPointer.y = evt.clientY;
  47329. }
  47330. // Two buttons down: pinch/pan
  47331. else if (pointA && pointB) {
  47332. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  47333. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  47334. ed.x = evt.clientX;
  47335. ed.y = evt.clientY;
  47336. var direction = _this.pinchInwards ? 1 : -1;
  47337. var distX = pointA.x - pointB.x;
  47338. var distY = pointA.y - pointB.y;
  47339. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  47340. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  47341. if (previousPinchSquaredDistance === 0) {
  47342. initialDistance = pinchDistance;
  47343. previousPinchSquaredDistance = pinchSquaredDistance;
  47344. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  47345. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  47346. return;
  47347. }
  47348. if (_this.multiTouchPanAndZoom) {
  47349. if (_this.pinchDeltaPercentage) {
  47350. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47351. }
  47352. else {
  47353. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47354. (_this.pinchPrecision *
  47355. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47356. direction);
  47357. }
  47358. if (_this.panningSensibility !== 0) {
  47359. var pointersCenterX = (pointA.x + pointB.x) / 2;
  47360. var pointersCenterY = (pointA.y + pointB.y) / 2;
  47361. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  47362. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  47363. previousMultiTouchPanPosition.x = pointersCenterX;
  47364. previousMultiTouchPanPosition.y = pointersCenterY;
  47365. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  47366. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  47367. }
  47368. }
  47369. else {
  47370. twoFingerActivityCount++;
  47371. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  47372. if (_this.pinchDeltaPercentage) {
  47373. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47374. }
  47375. else {
  47376. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47377. (_this.pinchPrecision *
  47378. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47379. direction);
  47380. }
  47381. previousMultiTouchPanPosition.isPaning = false;
  47382. previousMultiTouchPanPosition.isPinching = true;
  47383. }
  47384. else {
  47385. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  47386. if (!previousMultiTouchPanPosition.isPaning) {
  47387. previousMultiTouchPanPosition.isPaning = true;
  47388. previousMultiTouchPanPosition.isPinching = false;
  47389. previousMultiTouchPanPosition.x = ed.x;
  47390. previousMultiTouchPanPosition.y = ed.y;
  47391. return;
  47392. }
  47393. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  47394. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  47395. }
  47396. }
  47397. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  47398. previousMultiTouchPanPosition.x = ed.x;
  47399. previousMultiTouchPanPosition.y = ed.y;
  47400. }
  47401. }
  47402. previousPinchSquaredDistance = pinchSquaredDistance;
  47403. }
  47404. }
  47405. };
  47406. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  47407. this._onContextMenu = function (evt) {
  47408. evt.preventDefault();
  47409. };
  47410. if (!this.camera._useCtrlForPanning) {
  47411. element.addEventListener("contextmenu", this._onContextMenu, false);
  47412. }
  47413. this._onLostFocus = function () {
  47414. //this._keys = [];
  47415. pointA = pointB = null;
  47416. previousPinchSquaredDistance = 0;
  47417. previousMultiTouchPanPosition.isPaning = false;
  47418. previousMultiTouchPanPosition.isPinching = false;
  47419. twoFingerActivityCount = 0;
  47420. cacheSoloPointer = null;
  47421. initialDistance = 0;
  47422. };
  47423. this._onMouseMove = function (evt) {
  47424. if (!engine.isPointerLock) {
  47425. return;
  47426. }
  47427. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47428. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47429. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47430. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47431. if (!noPreventDefault) {
  47432. evt.preventDefault();
  47433. }
  47434. };
  47435. this._onGestureStart = function (e) {
  47436. if (window.MSGesture === undefined) {
  47437. return;
  47438. }
  47439. if (!_this._MSGestureHandler) {
  47440. _this._MSGestureHandler = new MSGesture();
  47441. _this._MSGestureHandler.target = element;
  47442. }
  47443. _this._MSGestureHandler.addPointer(e.pointerId);
  47444. };
  47445. this._onGesture = function (e) {
  47446. _this.camera.radius *= e.scale;
  47447. if (e.preventDefault) {
  47448. if (!noPreventDefault) {
  47449. e.stopPropagation();
  47450. e.preventDefault();
  47451. }
  47452. }
  47453. };
  47454. element.addEventListener("mousemove", this._onMouseMove, false);
  47455. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  47456. element.addEventListener("MSGestureChange", this._onGesture, false);
  47457. BABYLON.Tools.RegisterTopRootEvents([
  47458. { name: "blur", handler: this._onLostFocus }
  47459. ]);
  47460. };
  47461. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  47462. if (this._onLostFocus) {
  47463. BABYLON.Tools.UnregisterTopRootEvents([
  47464. { name: "blur", handler: this._onLostFocus }
  47465. ]);
  47466. }
  47467. if (element && this._observer) {
  47468. this.camera.getScene().onPointerObservable.remove(this._observer);
  47469. this._observer = null;
  47470. if (this._onContextMenu) {
  47471. element.removeEventListener("contextmenu", this._onContextMenu);
  47472. }
  47473. if (this._onMouseMove) {
  47474. element.removeEventListener("mousemove", this._onMouseMove);
  47475. }
  47476. if (this._onGestureStart) {
  47477. element.removeEventListener("MSPointerDown", this._onGestureStart);
  47478. }
  47479. if (this._onGesture) {
  47480. element.removeEventListener("MSGestureChange", this._onGesture);
  47481. }
  47482. this._isPanClick = false;
  47483. this.pinchInwards = true;
  47484. this._onMouseMove = null;
  47485. this._onGestureStart = null;
  47486. this._onGesture = null;
  47487. this._MSGestureHandler = null;
  47488. this._onLostFocus = null;
  47489. this._onContextMenu = null;
  47490. }
  47491. };
  47492. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  47493. return "ArcRotateCameraPointersInput";
  47494. };
  47495. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  47496. return "pointers";
  47497. };
  47498. __decorate([
  47499. BABYLON.serialize()
  47500. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  47501. __decorate([
  47502. BABYLON.serialize()
  47503. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  47504. __decorate([
  47505. BABYLON.serialize()
  47506. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  47507. __decorate([
  47508. BABYLON.serialize()
  47509. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  47510. __decorate([
  47511. BABYLON.serialize()
  47512. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  47513. __decorate([
  47514. BABYLON.serialize()
  47515. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  47516. __decorate([
  47517. BABYLON.serialize()
  47518. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  47519. __decorate([
  47520. BABYLON.serialize()
  47521. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  47522. return ArcRotateCameraPointersInput;
  47523. }());
  47524. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  47525. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  47526. })(BABYLON || (BABYLON = {}));
  47527. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  47528. var BABYLON;
  47529. (function (BABYLON) {
  47530. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  47531. __extends(ArcRotateCameraInputsManager, _super);
  47532. function ArcRotateCameraInputsManager(camera) {
  47533. return _super.call(this, camera) || this;
  47534. }
  47535. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  47536. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  47537. return this;
  47538. };
  47539. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  47540. this.add(new BABYLON.ArcRotateCameraPointersInput());
  47541. return this;
  47542. };
  47543. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  47544. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  47545. return this;
  47546. };
  47547. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  47548. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  47549. return this;
  47550. };
  47551. return ArcRotateCameraInputsManager;
  47552. }(BABYLON.CameraInputsManager));
  47553. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  47554. })(BABYLON || (BABYLON = {}));
  47555. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  47556. var BABYLON;
  47557. (function (BABYLON) {
  47558. BABYLON.Node.AddNodeConstructor("ArcRotateCamera", function (name, scene) {
  47559. return function () { return new ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  47560. });
  47561. var ArcRotateCamera = /** @class */ (function (_super) {
  47562. __extends(ArcRotateCamera, _super);
  47563. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  47564. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47565. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  47566. _this.inertialAlphaOffset = 0;
  47567. _this.inertialBetaOffset = 0;
  47568. _this.inertialRadiusOffset = 0;
  47569. _this.lowerAlphaLimit = null;
  47570. _this.upperAlphaLimit = null;
  47571. _this.lowerBetaLimit = 0.01;
  47572. _this.upperBetaLimit = Math.PI;
  47573. _this.lowerRadiusLimit = null;
  47574. _this.upperRadiusLimit = null;
  47575. _this.inertialPanningX = 0;
  47576. _this.inertialPanningY = 0;
  47577. _this.pinchToPanMaxDistance = 20;
  47578. _this.panningDistanceLimit = null;
  47579. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  47580. _this.panningInertia = 0.9;
  47581. //-- end properties for backward compatibility for inputs
  47582. _this.zoomOnFactor = 1;
  47583. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  47584. _this.allowUpsideDown = true;
  47585. /** @hidden */
  47586. _this._viewMatrix = new BABYLON.Matrix();
  47587. // Panning
  47588. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  47589. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  47590. _this.checkCollisions = false;
  47591. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  47592. _this._previousPosition = BABYLON.Vector3.Zero();
  47593. _this._collisionVelocity = BABYLON.Vector3.Zero();
  47594. _this._newPosition = BABYLON.Vector3.Zero();
  47595. _this._computationVector = BABYLON.Vector3.Zero();
  47596. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47597. if (collidedMesh === void 0) { collidedMesh = null; }
  47598. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  47599. newPosition.multiplyInPlace(_this._collider._radius);
  47600. }
  47601. if (!collidedMesh) {
  47602. _this._previousPosition.copyFrom(_this.position);
  47603. }
  47604. else {
  47605. _this.setPosition(newPosition);
  47606. if (_this.onCollide) {
  47607. _this.onCollide(collidedMesh);
  47608. }
  47609. }
  47610. // Recompute because of constraints
  47611. var cosa = Math.cos(_this.alpha);
  47612. var sina = Math.sin(_this.alpha);
  47613. var cosb = Math.cos(_this.beta);
  47614. var sinb = Math.sin(_this.beta);
  47615. if (sinb === 0) {
  47616. sinb = 0.0001;
  47617. }
  47618. var target = _this._getTargetPosition();
  47619. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  47620. target.addToRef(_this._computationVector, _this._newPosition);
  47621. _this.position.copyFrom(_this._newPosition);
  47622. var up = _this.upVector;
  47623. if (_this.allowUpsideDown && _this.beta < 0) {
  47624. up = up.clone();
  47625. up = up.negate();
  47626. }
  47627. _this._computeViewMatrix(_this.position, target, up);
  47628. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  47629. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  47630. _this._collisionTriggered = false;
  47631. };
  47632. _this._target = BABYLON.Vector3.Zero();
  47633. if (target) {
  47634. _this.setTarget(target);
  47635. }
  47636. _this.alpha = alpha;
  47637. _this.beta = beta;
  47638. _this.radius = radius;
  47639. _this.getViewMatrix();
  47640. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  47641. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  47642. return _this;
  47643. }
  47644. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  47645. get: function () {
  47646. return this._target;
  47647. },
  47648. set: function (value) {
  47649. this.setTarget(value);
  47650. },
  47651. enumerable: true,
  47652. configurable: true
  47653. });
  47654. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  47655. //-- begin properties for backward compatibility for inputs
  47656. get: function () {
  47657. var pointers = this.inputs.attached["pointers"];
  47658. if (pointers)
  47659. return pointers.angularSensibilityX;
  47660. return 0;
  47661. },
  47662. set: function (value) {
  47663. var pointers = this.inputs.attached["pointers"];
  47664. if (pointers) {
  47665. pointers.angularSensibilityX = value;
  47666. }
  47667. },
  47668. enumerable: true,
  47669. configurable: true
  47670. });
  47671. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  47672. get: function () {
  47673. var pointers = this.inputs.attached["pointers"];
  47674. if (pointers)
  47675. return pointers.angularSensibilityY;
  47676. return 0;
  47677. },
  47678. set: function (value) {
  47679. var pointers = this.inputs.attached["pointers"];
  47680. if (pointers) {
  47681. pointers.angularSensibilityY = value;
  47682. }
  47683. },
  47684. enumerable: true,
  47685. configurable: true
  47686. });
  47687. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  47688. get: function () {
  47689. var pointers = this.inputs.attached["pointers"];
  47690. if (pointers)
  47691. return pointers.pinchPrecision;
  47692. return 0;
  47693. },
  47694. set: function (value) {
  47695. var pointers = this.inputs.attached["pointers"];
  47696. if (pointers) {
  47697. pointers.pinchPrecision = value;
  47698. }
  47699. },
  47700. enumerable: true,
  47701. configurable: true
  47702. });
  47703. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  47704. get: function () {
  47705. var pointers = this.inputs.attached["pointers"];
  47706. if (pointers)
  47707. return pointers.pinchDeltaPercentage;
  47708. return 0;
  47709. },
  47710. set: function (value) {
  47711. var pointers = this.inputs.attached["pointers"];
  47712. if (pointers) {
  47713. pointers.pinchDeltaPercentage = value;
  47714. }
  47715. },
  47716. enumerable: true,
  47717. configurable: true
  47718. });
  47719. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  47720. get: function () {
  47721. var pointers = this.inputs.attached["pointers"];
  47722. if (pointers)
  47723. return pointers.panningSensibility;
  47724. return 0;
  47725. },
  47726. set: function (value) {
  47727. var pointers = this.inputs.attached["pointers"];
  47728. if (pointers) {
  47729. pointers.panningSensibility = value;
  47730. }
  47731. },
  47732. enumerable: true,
  47733. configurable: true
  47734. });
  47735. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  47736. get: function () {
  47737. var keyboard = this.inputs.attached["keyboard"];
  47738. if (keyboard)
  47739. return keyboard.keysUp;
  47740. return [];
  47741. },
  47742. set: function (value) {
  47743. var keyboard = this.inputs.attached["keyboard"];
  47744. if (keyboard)
  47745. keyboard.keysUp = value;
  47746. },
  47747. enumerable: true,
  47748. configurable: true
  47749. });
  47750. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  47751. get: function () {
  47752. var keyboard = this.inputs.attached["keyboard"];
  47753. if (keyboard)
  47754. return keyboard.keysDown;
  47755. return [];
  47756. },
  47757. set: function (value) {
  47758. var keyboard = this.inputs.attached["keyboard"];
  47759. if (keyboard)
  47760. keyboard.keysDown = value;
  47761. },
  47762. enumerable: true,
  47763. configurable: true
  47764. });
  47765. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  47766. get: function () {
  47767. var keyboard = this.inputs.attached["keyboard"];
  47768. if (keyboard)
  47769. return keyboard.keysLeft;
  47770. return [];
  47771. },
  47772. set: function (value) {
  47773. var keyboard = this.inputs.attached["keyboard"];
  47774. if (keyboard)
  47775. keyboard.keysLeft = value;
  47776. },
  47777. enumerable: true,
  47778. configurable: true
  47779. });
  47780. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  47781. get: function () {
  47782. var keyboard = this.inputs.attached["keyboard"];
  47783. if (keyboard)
  47784. return keyboard.keysRight;
  47785. return [];
  47786. },
  47787. set: function (value) {
  47788. var keyboard = this.inputs.attached["keyboard"];
  47789. if (keyboard)
  47790. keyboard.keysRight = value;
  47791. },
  47792. enumerable: true,
  47793. configurable: true
  47794. });
  47795. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  47796. get: function () {
  47797. var mousewheel = this.inputs.attached["mousewheel"];
  47798. if (mousewheel)
  47799. return mousewheel.wheelPrecision;
  47800. return 0;
  47801. },
  47802. set: function (value) {
  47803. var mousewheel = this.inputs.attached["mousewheel"];
  47804. if (mousewheel)
  47805. mousewheel.wheelPrecision = value;
  47806. },
  47807. enumerable: true,
  47808. configurable: true
  47809. });
  47810. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  47811. get: function () {
  47812. var mousewheel = this.inputs.attached["mousewheel"];
  47813. if (mousewheel)
  47814. return mousewheel.wheelDeltaPercentage;
  47815. return 0;
  47816. },
  47817. set: function (value) {
  47818. var mousewheel = this.inputs.attached["mousewheel"];
  47819. if (mousewheel)
  47820. mousewheel.wheelDeltaPercentage = value;
  47821. },
  47822. enumerable: true,
  47823. configurable: true
  47824. });
  47825. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  47826. get: function () {
  47827. return this._bouncingBehavior;
  47828. },
  47829. enumerable: true,
  47830. configurable: true
  47831. });
  47832. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  47833. get: function () {
  47834. return this._bouncingBehavior != null;
  47835. },
  47836. set: function (value) {
  47837. if (value === this.useBouncingBehavior) {
  47838. return;
  47839. }
  47840. if (value) {
  47841. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  47842. this.addBehavior(this._bouncingBehavior);
  47843. }
  47844. else if (this._bouncingBehavior) {
  47845. this.removeBehavior(this._bouncingBehavior);
  47846. this._bouncingBehavior = null;
  47847. }
  47848. },
  47849. enumerable: true,
  47850. configurable: true
  47851. });
  47852. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  47853. get: function () {
  47854. return this._framingBehavior;
  47855. },
  47856. enumerable: true,
  47857. configurable: true
  47858. });
  47859. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  47860. get: function () {
  47861. return this._framingBehavior != null;
  47862. },
  47863. set: function (value) {
  47864. if (value === this.useFramingBehavior) {
  47865. return;
  47866. }
  47867. if (value) {
  47868. this._framingBehavior = new BABYLON.FramingBehavior();
  47869. this.addBehavior(this._framingBehavior);
  47870. }
  47871. else if (this._framingBehavior) {
  47872. this.removeBehavior(this._framingBehavior);
  47873. this._framingBehavior = null;
  47874. }
  47875. },
  47876. enumerable: true,
  47877. configurable: true
  47878. });
  47879. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  47880. get: function () {
  47881. return this._autoRotationBehavior;
  47882. },
  47883. enumerable: true,
  47884. configurable: true
  47885. });
  47886. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  47887. get: function () {
  47888. return this._autoRotationBehavior != null;
  47889. },
  47890. set: function (value) {
  47891. if (value === this.useAutoRotationBehavior) {
  47892. return;
  47893. }
  47894. if (value) {
  47895. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  47896. this.addBehavior(this._autoRotationBehavior);
  47897. }
  47898. else if (this._autoRotationBehavior) {
  47899. this.removeBehavior(this._autoRotationBehavior);
  47900. this._autoRotationBehavior = null;
  47901. }
  47902. },
  47903. enumerable: true,
  47904. configurable: true
  47905. });
  47906. // Cache
  47907. /** @hidden */
  47908. ArcRotateCamera.prototype._initCache = function () {
  47909. _super.prototype._initCache.call(this);
  47910. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47911. this._cache.alpha = undefined;
  47912. this._cache.beta = undefined;
  47913. this._cache.radius = undefined;
  47914. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  47915. };
  47916. /** @hidden */
  47917. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  47918. if (!ignoreParentClass) {
  47919. _super.prototype._updateCache.call(this);
  47920. }
  47921. this._cache._target.copyFrom(this._getTargetPosition());
  47922. this._cache.alpha = this.alpha;
  47923. this._cache.beta = this.beta;
  47924. this._cache.radius = this.radius;
  47925. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  47926. };
  47927. ArcRotateCamera.prototype._getTargetPosition = function () {
  47928. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  47929. var pos = this._targetHost.getAbsolutePosition();
  47930. if (this._targetBoundingCenter) {
  47931. pos.addToRef(this._targetBoundingCenter, this._target);
  47932. }
  47933. else {
  47934. this._target.copyFrom(pos);
  47935. }
  47936. }
  47937. var lockedTargetPosition = this._getLockedTargetPosition();
  47938. if (lockedTargetPosition) {
  47939. return lockedTargetPosition;
  47940. }
  47941. return this._target;
  47942. };
  47943. ArcRotateCamera.prototype.storeState = function () {
  47944. this._storedAlpha = this.alpha;
  47945. this._storedBeta = this.beta;
  47946. this._storedRadius = this.radius;
  47947. this._storedTarget = this._getTargetPosition().clone();
  47948. return _super.prototype.storeState.call(this);
  47949. };
  47950. /**
  47951. * @hidden
  47952. * Restored camera state. You must call storeState() first
  47953. */
  47954. ArcRotateCamera.prototype._restoreStateValues = function () {
  47955. if (!_super.prototype._restoreStateValues.call(this)) {
  47956. return false;
  47957. }
  47958. this.alpha = this._storedAlpha;
  47959. this.beta = this._storedBeta;
  47960. this.radius = this._storedRadius;
  47961. this.setTarget(this._storedTarget.clone());
  47962. this.inertialAlphaOffset = 0;
  47963. this.inertialBetaOffset = 0;
  47964. this.inertialRadiusOffset = 0;
  47965. this.inertialPanningX = 0;
  47966. this.inertialPanningY = 0;
  47967. return true;
  47968. };
  47969. // Synchronized
  47970. /** @hidden */
  47971. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  47972. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  47973. return false;
  47974. return this._cache._target.equals(this._getTargetPosition())
  47975. && this._cache.alpha === this.alpha
  47976. && this._cache.beta === this.beta
  47977. && this._cache.radius === this.radius
  47978. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  47979. };
  47980. // Methods
  47981. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  47982. var _this = this;
  47983. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  47984. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  47985. this._useCtrlForPanning = useCtrlForPanning;
  47986. this._panningMouseButton = panningMouseButton;
  47987. this.inputs.attachElement(element, noPreventDefault);
  47988. this._reset = function () {
  47989. _this.inertialAlphaOffset = 0;
  47990. _this.inertialBetaOffset = 0;
  47991. _this.inertialRadiusOffset = 0;
  47992. _this.inertialPanningX = 0;
  47993. _this.inertialPanningY = 0;
  47994. };
  47995. };
  47996. ArcRotateCamera.prototype.detachControl = function (element) {
  47997. this.inputs.detachElement(element);
  47998. if (this._reset) {
  47999. this._reset();
  48000. }
  48001. };
  48002. /** @hidden */
  48003. ArcRotateCamera.prototype._checkInputs = function () {
  48004. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  48005. if (this._collisionTriggered) {
  48006. return;
  48007. }
  48008. this.inputs.checkInputs();
  48009. // Inertia
  48010. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  48011. var inertialAlphaOffset = this.inertialAlphaOffset;
  48012. if (this.beta <= 0)
  48013. inertialAlphaOffset *= -1;
  48014. if (this.getScene().useRightHandedSystem)
  48015. inertialAlphaOffset *= -1;
  48016. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  48017. inertialAlphaOffset *= -1;
  48018. this.alpha += inertialAlphaOffset;
  48019. this.beta += this.inertialBetaOffset;
  48020. this.radius -= this.inertialRadiusOffset;
  48021. this.inertialAlphaOffset *= this.inertia;
  48022. this.inertialBetaOffset *= this.inertia;
  48023. this.inertialRadiusOffset *= this.inertia;
  48024. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  48025. this.inertialAlphaOffset = 0;
  48026. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  48027. this.inertialBetaOffset = 0;
  48028. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  48029. this.inertialRadiusOffset = 0;
  48030. }
  48031. // Panning inertia
  48032. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  48033. if (!this._localDirection) {
  48034. this._localDirection = BABYLON.Vector3.Zero();
  48035. this._transformedDirection = BABYLON.Vector3.Zero();
  48036. }
  48037. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  48038. this._localDirection.multiplyInPlace(this.panningAxis);
  48039. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  48040. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  48041. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  48042. if (!this.panningAxis.y) {
  48043. this._transformedDirection.y = 0;
  48044. }
  48045. if (!this._targetHost) {
  48046. if (this.panningDistanceLimit) {
  48047. this._transformedDirection.addInPlace(this._target);
  48048. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  48049. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  48050. this._target.copyFrom(this._transformedDirection);
  48051. }
  48052. }
  48053. else {
  48054. this._target.addInPlace(this._transformedDirection);
  48055. }
  48056. }
  48057. this.inertialPanningX *= this.panningInertia;
  48058. this.inertialPanningY *= this.panningInertia;
  48059. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  48060. this.inertialPanningX = 0;
  48061. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  48062. this.inertialPanningY = 0;
  48063. }
  48064. // Limits
  48065. this._checkLimits();
  48066. _super.prototype._checkInputs.call(this);
  48067. };
  48068. ArcRotateCamera.prototype._checkLimits = function () {
  48069. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  48070. if (this.allowUpsideDown && this.beta > Math.PI) {
  48071. this.beta = this.beta - (2 * Math.PI);
  48072. }
  48073. }
  48074. else {
  48075. if (this.beta < this.lowerBetaLimit) {
  48076. this.beta = this.lowerBetaLimit;
  48077. }
  48078. }
  48079. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  48080. if (this.allowUpsideDown && this.beta < -Math.PI) {
  48081. this.beta = this.beta + (2 * Math.PI);
  48082. }
  48083. }
  48084. else {
  48085. if (this.beta > this.upperBetaLimit) {
  48086. this.beta = this.upperBetaLimit;
  48087. }
  48088. }
  48089. if (this.lowerAlphaLimit !== null && this.alpha < this.lowerAlphaLimit) {
  48090. this.alpha = this.lowerAlphaLimit;
  48091. }
  48092. if (this.upperAlphaLimit !== null && this.alpha > this.upperAlphaLimit) {
  48093. this.alpha = this.upperAlphaLimit;
  48094. }
  48095. if (this.lowerRadiusLimit !== null && this.radius < this.lowerRadiusLimit) {
  48096. this.radius = this.lowerRadiusLimit;
  48097. }
  48098. if (this.upperRadiusLimit !== null && this.radius > this.upperRadiusLimit) {
  48099. this.radius = this.upperRadiusLimit;
  48100. }
  48101. };
  48102. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  48103. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  48104. this.radius = this._computationVector.length();
  48105. if (this.radius === 0) {
  48106. this.radius = 0.0001; // Just to avoid division by zero
  48107. }
  48108. // Alpha
  48109. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  48110. if (this._computationVector.z < 0) {
  48111. this.alpha = 2 * Math.PI - this.alpha;
  48112. }
  48113. // Beta
  48114. this.beta = Math.acos(this._computationVector.y / this.radius);
  48115. this._checkLimits();
  48116. };
  48117. ArcRotateCamera.prototype.setPosition = function (position) {
  48118. if (this.position.equals(position)) {
  48119. return;
  48120. }
  48121. this.position.copyFrom(position);
  48122. this.rebuildAnglesAndRadius();
  48123. };
  48124. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  48125. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  48126. if (allowSamePosition === void 0) { allowSamePosition = false; }
  48127. if (target.getBoundingInfo) {
  48128. if (toBoundingCenter) {
  48129. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  48130. }
  48131. else {
  48132. this._targetBoundingCenter = null;
  48133. }
  48134. this._targetHost = target;
  48135. this._target = this._getTargetPosition();
  48136. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  48137. }
  48138. else {
  48139. var newTarget = target;
  48140. var currentTarget = this._getTargetPosition();
  48141. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  48142. return;
  48143. }
  48144. this._targetHost = null;
  48145. this._target = newTarget;
  48146. this._targetBoundingCenter = null;
  48147. this.onMeshTargetChangedObservable.notifyObservers(null);
  48148. }
  48149. this.rebuildAnglesAndRadius();
  48150. };
  48151. /** @hidden */
  48152. ArcRotateCamera.prototype._getViewMatrix = function () {
  48153. // Compute
  48154. var cosa = Math.cos(this.alpha);
  48155. var sina = Math.sin(this.alpha);
  48156. var cosb = Math.cos(this.beta);
  48157. var sinb = Math.sin(this.beta);
  48158. if (sinb === 0) {
  48159. sinb = 0.0001;
  48160. }
  48161. var target = this._getTargetPosition();
  48162. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  48163. target.addToRef(this._computationVector, this._newPosition);
  48164. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  48165. if (!this._collider) {
  48166. this._collider = new BABYLON.Collider();
  48167. }
  48168. this._collider._radius = this.collisionRadius;
  48169. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  48170. this._collisionTriggered = true;
  48171. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  48172. }
  48173. else {
  48174. this.position.copyFrom(this._newPosition);
  48175. var up = this.upVector;
  48176. if (this.allowUpsideDown && sinb < 0) {
  48177. up = up.clone();
  48178. up = up.negate();
  48179. }
  48180. this._computeViewMatrix(this.position, target, up);
  48181. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  48182. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  48183. }
  48184. this._currentTarget = target;
  48185. return this._viewMatrix;
  48186. };
  48187. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  48188. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48189. meshes = meshes || this.getScene().meshes;
  48190. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  48191. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  48192. this.radius = distance * this.zoomOnFactor;
  48193. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  48194. };
  48195. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  48196. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48197. var meshesOrMinMaxVector;
  48198. var distance;
  48199. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  48200. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  48201. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  48202. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  48203. }
  48204. else { //minMaxVector and distance
  48205. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  48206. meshesOrMinMaxVector = minMaxVectorAndDistance;
  48207. distance = minMaxVectorAndDistance.distance;
  48208. }
  48209. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  48210. if (!doNotUpdateMaxZ) {
  48211. this.maxZ = distance * 2;
  48212. }
  48213. };
  48214. /**
  48215. * @override
  48216. * Override Camera.createRigCamera
  48217. */
  48218. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  48219. var alphaShift = 0;
  48220. switch (this.cameraRigMode) {
  48221. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48222. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48223. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48224. case BABYLON.Camera.RIG_MODE_VR:
  48225. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  48226. break;
  48227. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48228. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  48229. break;
  48230. }
  48231. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  48232. rigCam._cameraRigParams = {};
  48233. return rigCam;
  48234. };
  48235. /**
  48236. * @hidden
  48237. * @override
  48238. * Override Camera._updateRigCameras
  48239. */
  48240. ArcRotateCamera.prototype._updateRigCameras = function () {
  48241. var camLeft = this._rigCameras[0];
  48242. var camRight = this._rigCameras[1];
  48243. camLeft.beta = camRight.beta = this.beta;
  48244. camLeft.radius = camRight.radius = this.radius;
  48245. switch (this.cameraRigMode) {
  48246. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48247. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48248. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48249. case BABYLON.Camera.RIG_MODE_VR:
  48250. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48251. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48252. break;
  48253. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48254. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48255. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48256. break;
  48257. }
  48258. _super.prototype._updateRigCameras.call(this);
  48259. };
  48260. ArcRotateCamera.prototype.dispose = function () {
  48261. this.inputs.clear();
  48262. _super.prototype.dispose.call(this);
  48263. };
  48264. ArcRotateCamera.prototype.getClassName = function () {
  48265. return "ArcRotateCamera";
  48266. };
  48267. __decorate([
  48268. BABYLON.serialize()
  48269. ], ArcRotateCamera.prototype, "alpha", void 0);
  48270. __decorate([
  48271. BABYLON.serialize()
  48272. ], ArcRotateCamera.prototype, "beta", void 0);
  48273. __decorate([
  48274. BABYLON.serialize()
  48275. ], ArcRotateCamera.prototype, "radius", void 0);
  48276. __decorate([
  48277. BABYLON.serializeAsVector3("target")
  48278. ], ArcRotateCamera.prototype, "_target", void 0);
  48279. __decorate([
  48280. BABYLON.serialize()
  48281. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  48282. __decorate([
  48283. BABYLON.serialize()
  48284. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  48285. __decorate([
  48286. BABYLON.serialize()
  48287. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  48288. __decorate([
  48289. BABYLON.serialize()
  48290. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  48291. __decorate([
  48292. BABYLON.serialize()
  48293. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  48294. __decorate([
  48295. BABYLON.serialize()
  48296. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  48297. __decorate([
  48298. BABYLON.serialize()
  48299. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  48300. __decorate([
  48301. BABYLON.serialize()
  48302. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  48303. __decorate([
  48304. BABYLON.serialize()
  48305. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  48306. __decorate([
  48307. BABYLON.serialize()
  48308. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  48309. __decorate([
  48310. BABYLON.serialize()
  48311. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  48312. __decorate([
  48313. BABYLON.serialize()
  48314. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  48315. __decorate([
  48316. BABYLON.serialize()
  48317. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  48318. __decorate([
  48319. BABYLON.serializeAsVector3()
  48320. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  48321. __decorate([
  48322. BABYLON.serialize()
  48323. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  48324. __decorate([
  48325. BABYLON.serialize()
  48326. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  48327. __decorate([
  48328. BABYLON.serialize()
  48329. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  48330. return ArcRotateCamera;
  48331. }(BABYLON.TargetCamera));
  48332. BABYLON.ArcRotateCamera = ArcRotateCamera;
  48333. })(BABYLON || (BABYLON = {}));
  48334. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  48335. var BABYLON;
  48336. (function (BABYLON) {
  48337. BABYLON.Node.AddNodeConstructor("Light_Type_3", function (name, scene) {
  48338. return function () { return new HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  48339. });
  48340. /**
  48341. * The HemisphericLight simulates the ambient environment light,
  48342. * so the passed direction is the light reflection direction, not the incoming direction.
  48343. */
  48344. var HemisphericLight = /** @class */ (function (_super) {
  48345. __extends(HemisphericLight, _super);
  48346. /**
  48347. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  48348. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  48349. * The HemisphericLight can't cast shadows.
  48350. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48351. * @param name The friendly name of the light
  48352. * @param direction The direction of the light reflection
  48353. * @param scene The scene the light belongs to
  48354. */
  48355. function HemisphericLight(name, direction, scene) {
  48356. var _this = _super.call(this, name, scene) || this;
  48357. /**
  48358. * The groundColor is the light in the opposite direction to the one specified during creation.
  48359. * 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.
  48360. */
  48361. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  48362. _this.direction = direction || BABYLON.Vector3.Up();
  48363. return _this;
  48364. }
  48365. HemisphericLight.prototype._buildUniformLayout = function () {
  48366. this._uniformBuffer.addUniform("vLightData", 4);
  48367. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48368. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48369. this._uniformBuffer.addUniform("vLightGround", 3);
  48370. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48371. this._uniformBuffer.addUniform("depthValues", 2);
  48372. this._uniformBuffer.create();
  48373. };
  48374. /**
  48375. * Returns the string "HemisphericLight".
  48376. * @return The class name
  48377. */
  48378. HemisphericLight.prototype.getClassName = function () {
  48379. return "HemisphericLight";
  48380. };
  48381. /**
  48382. * Sets the HemisphericLight direction towards the passed target (Vector3).
  48383. * Returns the updated direction.
  48384. * @param target The target the direction should point to
  48385. * @return The computed direction
  48386. */
  48387. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  48388. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  48389. return this.direction;
  48390. };
  48391. /**
  48392. * Returns the shadow generator associated to the light.
  48393. * @returns Always null for hemispheric lights because it does not support shadows.
  48394. */
  48395. HemisphericLight.prototype.getShadowGenerator = function () {
  48396. return null;
  48397. };
  48398. /**
  48399. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  48400. * @param effect The effect to update
  48401. * @param lightIndex The index of the light in the effect to update
  48402. * @returns The hemispheric light
  48403. */
  48404. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  48405. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  48406. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  48407. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  48408. return this;
  48409. };
  48410. /**
  48411. * @hidden internal use only.
  48412. */
  48413. HemisphericLight.prototype._getWorldMatrix = function () {
  48414. if (!this._worldMatrix) {
  48415. this._worldMatrix = BABYLON.Matrix.Identity();
  48416. }
  48417. return this._worldMatrix;
  48418. };
  48419. /**
  48420. * Returns the integer 3.
  48421. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48422. */
  48423. HemisphericLight.prototype.getTypeID = function () {
  48424. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  48425. };
  48426. /**
  48427. * Prepares the list of defines specific to the light type.
  48428. * @param defines the list of defines
  48429. * @param lightIndex defines the index of the light for the effect
  48430. */
  48431. HemisphericLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  48432. defines["HEMILIGHT" + lightIndex] = true;
  48433. };
  48434. __decorate([
  48435. BABYLON.serializeAsColor3()
  48436. ], HemisphericLight.prototype, "groundColor", void 0);
  48437. __decorate([
  48438. BABYLON.serializeAsVector3()
  48439. ], HemisphericLight.prototype, "direction", void 0);
  48440. return HemisphericLight;
  48441. }(BABYLON.Light));
  48442. BABYLON.HemisphericLight = HemisphericLight;
  48443. })(BABYLON || (BABYLON = {}));
  48444. //# sourceMappingURL=babylon.hemisphericLight.js.map
  48445. var BABYLON;
  48446. (function (BABYLON) {
  48447. /**
  48448. * Base implementation IShadowLight
  48449. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  48450. */
  48451. var ShadowLight = /** @class */ (function (_super) {
  48452. __extends(ShadowLight, _super);
  48453. function ShadowLight() {
  48454. var _this = _super !== null && _super.apply(this, arguments) || this;
  48455. _this._needProjectionMatrixCompute = true;
  48456. return _this;
  48457. }
  48458. ShadowLight.prototype._setPosition = function (value) {
  48459. this._position = value;
  48460. };
  48461. Object.defineProperty(ShadowLight.prototype, "position", {
  48462. /**
  48463. * Sets the position the shadow will be casted from. Also use as the light position for both
  48464. * point and spot lights.
  48465. */
  48466. get: function () {
  48467. return this._position;
  48468. },
  48469. /**
  48470. * Sets the position the shadow will be casted from. Also use as the light position for both
  48471. * point and spot lights.
  48472. */
  48473. set: function (value) {
  48474. this._setPosition(value);
  48475. },
  48476. enumerable: true,
  48477. configurable: true
  48478. });
  48479. ShadowLight.prototype._setDirection = function (value) {
  48480. this._direction = value;
  48481. };
  48482. Object.defineProperty(ShadowLight.prototype, "direction", {
  48483. /**
  48484. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  48485. * Also use as the light direction on spot and directional lights.
  48486. */
  48487. get: function () {
  48488. return this._direction;
  48489. },
  48490. /**
  48491. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  48492. * Also use as the light direction on spot and directional lights.
  48493. */
  48494. set: function (value) {
  48495. this._setDirection(value);
  48496. },
  48497. enumerable: true,
  48498. configurable: true
  48499. });
  48500. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  48501. /**
  48502. * Gets the shadow projection clipping minimum z value.
  48503. */
  48504. get: function () {
  48505. return this._shadowMinZ;
  48506. },
  48507. /**
  48508. * Sets the shadow projection clipping minimum z value.
  48509. */
  48510. set: function (value) {
  48511. this._shadowMinZ = value;
  48512. this.forceProjectionMatrixCompute();
  48513. },
  48514. enumerable: true,
  48515. configurable: true
  48516. });
  48517. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  48518. /**
  48519. * Sets the shadow projection clipping maximum z value.
  48520. */
  48521. get: function () {
  48522. return this._shadowMaxZ;
  48523. },
  48524. /**
  48525. * Gets the shadow projection clipping maximum z value.
  48526. */
  48527. set: function (value) {
  48528. this._shadowMaxZ = value;
  48529. this.forceProjectionMatrixCompute();
  48530. },
  48531. enumerable: true,
  48532. configurable: true
  48533. });
  48534. /**
  48535. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  48536. * @returns true if the information has been computed, false if it does not need to (no parenting)
  48537. */
  48538. ShadowLight.prototype.computeTransformedInformation = function () {
  48539. if (this.parent && this.parent.getWorldMatrix) {
  48540. if (!this.transformedPosition) {
  48541. this.transformedPosition = BABYLON.Vector3.Zero();
  48542. }
  48543. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  48544. // In case the direction is present.
  48545. if (this.direction) {
  48546. if (!this.transformedDirection) {
  48547. this.transformedDirection = BABYLON.Vector3.Zero();
  48548. }
  48549. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  48550. }
  48551. return true;
  48552. }
  48553. return false;
  48554. };
  48555. /**
  48556. * Return the depth scale used for the shadow map.
  48557. * @returns the depth scale.
  48558. */
  48559. ShadowLight.prototype.getDepthScale = function () {
  48560. return 50.0;
  48561. };
  48562. /**
  48563. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  48564. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48565. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48566. */
  48567. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  48568. return this.transformedDirection ? this.transformedDirection : this.direction;
  48569. };
  48570. /**
  48571. * Returns the ShadowLight absolute position in the World.
  48572. * @returns the position vector in world space
  48573. */
  48574. ShadowLight.prototype.getAbsolutePosition = function () {
  48575. return this.transformedPosition ? this.transformedPosition : this.position;
  48576. };
  48577. /**
  48578. * Sets the ShadowLight direction toward the passed target.
  48579. * @param target The point tot target in local space
  48580. * @returns the updated ShadowLight direction
  48581. */
  48582. ShadowLight.prototype.setDirectionToTarget = function (target) {
  48583. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  48584. return this.direction;
  48585. };
  48586. /**
  48587. * Returns the light rotation in euler definition.
  48588. * @returns the x y z rotation in local space.
  48589. */
  48590. ShadowLight.prototype.getRotation = function () {
  48591. this.direction.normalize();
  48592. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  48593. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  48594. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  48595. };
  48596. /**
  48597. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  48598. * @returns true if a cube texture needs to be use
  48599. */
  48600. ShadowLight.prototype.needCube = function () {
  48601. return false;
  48602. };
  48603. /**
  48604. * Detects if the projection matrix requires to be recomputed this frame.
  48605. * @returns true if it requires to be recomputed otherwise, false.
  48606. */
  48607. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  48608. return this._needProjectionMatrixCompute;
  48609. };
  48610. /**
  48611. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  48612. */
  48613. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  48614. this._needProjectionMatrixCompute = true;
  48615. };
  48616. /**
  48617. * Get the world matrix of the sahdow lights.
  48618. * @hidden Internal Use Only
  48619. */
  48620. ShadowLight.prototype._getWorldMatrix = function () {
  48621. if (!this._worldMatrix) {
  48622. this._worldMatrix = BABYLON.Matrix.Identity();
  48623. }
  48624. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  48625. return this._worldMatrix;
  48626. };
  48627. /**
  48628. * Gets the minZ used for shadow according to both the scene and the light.
  48629. * @param activeCamera The camera we are returning the min for
  48630. * @returns the depth min z
  48631. */
  48632. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  48633. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  48634. };
  48635. /**
  48636. * Gets the maxZ used for shadow according to both the scene and the light.
  48637. * @param activeCamera The camera we are returning the max for
  48638. * @returns the depth max z
  48639. */
  48640. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  48641. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  48642. };
  48643. /**
  48644. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  48645. * @param matrix The materix to updated with the projection information
  48646. * @param viewMatrix The transform matrix of the light
  48647. * @param renderList The list of mesh to render in the map
  48648. * @returns The current light
  48649. */
  48650. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48651. if (this.customProjectionMatrixBuilder) {
  48652. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  48653. }
  48654. else {
  48655. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48656. }
  48657. return this;
  48658. };
  48659. __decorate([
  48660. BABYLON.serializeAsVector3()
  48661. ], ShadowLight.prototype, "position", null);
  48662. __decorate([
  48663. BABYLON.serializeAsVector3()
  48664. ], ShadowLight.prototype, "direction", null);
  48665. __decorate([
  48666. BABYLON.serialize()
  48667. ], ShadowLight.prototype, "shadowMinZ", null);
  48668. __decorate([
  48669. BABYLON.serialize()
  48670. ], ShadowLight.prototype, "shadowMaxZ", null);
  48671. return ShadowLight;
  48672. }(BABYLON.Light));
  48673. BABYLON.ShadowLight = ShadowLight;
  48674. })(BABYLON || (BABYLON = {}));
  48675. //# sourceMappingURL=babylon.shadowLight.js.map
  48676. var BABYLON;
  48677. (function (BABYLON) {
  48678. BABYLON.Node.AddNodeConstructor("Light_Type_0", function (name, scene) {
  48679. return function () { return new PointLight(name, BABYLON.Vector3.Zero(), scene); };
  48680. });
  48681. /**
  48682. * A point light is a light defined by an unique point in world space.
  48683. * The light is emitted in every direction from this point.
  48684. * A good example of a point light is a standard light bulb.
  48685. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48686. */
  48687. var PointLight = /** @class */ (function (_super) {
  48688. __extends(PointLight, _super);
  48689. /**
  48690. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  48691. * A PointLight emits the light in every direction.
  48692. * It can cast shadows.
  48693. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  48694. * ```javascript
  48695. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  48696. * ```
  48697. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48698. * @param name The light friendly name
  48699. * @param position The position of the point light in the scene
  48700. * @param scene The scene the lights belongs to
  48701. */
  48702. function PointLight(name, position, scene) {
  48703. var _this = _super.call(this, name, scene) || this;
  48704. _this._shadowAngle = Math.PI / 2;
  48705. _this.position = position;
  48706. return _this;
  48707. }
  48708. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  48709. /**
  48710. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48711. * This specifies what angle the shadow will use to be created.
  48712. *
  48713. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48714. */
  48715. get: function () {
  48716. return this._shadowAngle;
  48717. },
  48718. /**
  48719. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48720. * This specifies what angle the shadow will use to be created.
  48721. *
  48722. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48723. */
  48724. set: function (value) {
  48725. this._shadowAngle = value;
  48726. this.forceProjectionMatrixCompute();
  48727. },
  48728. enumerable: true,
  48729. configurable: true
  48730. });
  48731. Object.defineProperty(PointLight.prototype, "direction", {
  48732. /**
  48733. * Gets the direction if it has been set.
  48734. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48735. */
  48736. get: function () {
  48737. return this._direction;
  48738. },
  48739. /**
  48740. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48741. */
  48742. set: function (value) {
  48743. var previousNeedCube = this.needCube();
  48744. this._direction = value;
  48745. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  48746. this._shadowGenerator.recreateShadowMap();
  48747. }
  48748. },
  48749. enumerable: true,
  48750. configurable: true
  48751. });
  48752. /**
  48753. * Returns the string "PointLight"
  48754. * @returns the class name
  48755. */
  48756. PointLight.prototype.getClassName = function () {
  48757. return "PointLight";
  48758. };
  48759. /**
  48760. * Returns the integer 0.
  48761. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48762. */
  48763. PointLight.prototype.getTypeID = function () {
  48764. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  48765. };
  48766. /**
  48767. * Specifies wether or not the shadowmap should be a cube texture.
  48768. * @returns true if the shadowmap needs to be a cube texture.
  48769. */
  48770. PointLight.prototype.needCube = function () {
  48771. return !this.direction;
  48772. };
  48773. /**
  48774. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  48775. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48776. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48777. */
  48778. PointLight.prototype.getShadowDirection = function (faceIndex) {
  48779. if (this.direction) {
  48780. return _super.prototype.getShadowDirection.call(this, faceIndex);
  48781. }
  48782. else {
  48783. switch (faceIndex) {
  48784. case 0:
  48785. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  48786. case 1:
  48787. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  48788. case 2:
  48789. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  48790. case 3:
  48791. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  48792. case 4:
  48793. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  48794. case 5:
  48795. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  48796. }
  48797. }
  48798. return BABYLON.Vector3.Zero();
  48799. };
  48800. /**
  48801. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  48802. * - fov = PI / 2
  48803. * - aspect ratio : 1.0
  48804. * - z-near and far equal to the active camera minZ and maxZ.
  48805. * Returns the PointLight.
  48806. */
  48807. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48808. var activeCamera = this.getScene().activeCamera;
  48809. if (!activeCamera) {
  48810. return;
  48811. }
  48812. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  48813. };
  48814. PointLight.prototype._buildUniformLayout = function () {
  48815. this._uniformBuffer.addUniform("vLightData", 4);
  48816. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48817. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48818. this._uniformBuffer.addUniform("vLightFalloff", 4);
  48819. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48820. this._uniformBuffer.addUniform("depthValues", 2);
  48821. this._uniformBuffer.create();
  48822. };
  48823. /**
  48824. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  48825. * @param effect The effect to update
  48826. * @param lightIndex The index of the light in the effect to update
  48827. * @returns The point light
  48828. */
  48829. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  48830. if (this.computeTransformedInformation()) {
  48831. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  48832. }
  48833. else {
  48834. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  48835. }
  48836. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, 0, 0, lightIndex);
  48837. return this;
  48838. };
  48839. /**
  48840. * Prepares the list of defines specific to the light type.
  48841. * @param defines the list of defines
  48842. * @param lightIndex defines the index of the light for the effect
  48843. */
  48844. PointLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  48845. defines["POINTLIGHT" + lightIndex] = true;
  48846. };
  48847. __decorate([
  48848. BABYLON.serialize()
  48849. ], PointLight.prototype, "shadowAngle", null);
  48850. return PointLight;
  48851. }(BABYLON.ShadowLight));
  48852. BABYLON.PointLight = PointLight;
  48853. })(BABYLON || (BABYLON = {}));
  48854. //# sourceMappingURL=babylon.pointLight.js.map
  48855. var BABYLON;
  48856. (function (BABYLON) {
  48857. BABYLON.Node.AddNodeConstructor("Light_Type_1", function (name, scene) {
  48858. return function () { return new DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  48859. });
  48860. /**
  48861. * A directional light is defined by a direction (what a surprise!).
  48862. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  48863. * 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.
  48864. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48865. */
  48866. var DirectionalLight = /** @class */ (function (_super) {
  48867. __extends(DirectionalLight, _super);
  48868. /**
  48869. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  48870. * The directional light is emitted from everywhere in the given direction.
  48871. * It can cast shawdows.
  48872. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48873. * @param name The friendly name of the light
  48874. * @param direction The direction of the light
  48875. * @param scene The scene the light belongs to
  48876. */
  48877. function DirectionalLight(name, direction, scene) {
  48878. var _this = _super.call(this, name, scene) || this;
  48879. _this._shadowFrustumSize = 0;
  48880. _this._shadowOrthoScale = 0.1;
  48881. /**
  48882. * Automatically compute the projection matrix to best fit (including all the casters)
  48883. * on each frame.
  48884. */
  48885. _this.autoUpdateExtends = true;
  48886. // Cache
  48887. _this._orthoLeft = Number.MAX_VALUE;
  48888. _this._orthoRight = Number.MIN_VALUE;
  48889. _this._orthoTop = Number.MIN_VALUE;
  48890. _this._orthoBottom = Number.MAX_VALUE;
  48891. _this.position = direction.scale(-1.0);
  48892. _this.direction = direction;
  48893. return _this;
  48894. }
  48895. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  48896. /**
  48897. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  48898. */
  48899. get: function () {
  48900. return this._shadowFrustumSize;
  48901. },
  48902. /**
  48903. * Specifies a fix frustum size for the shadow generation.
  48904. */
  48905. set: function (value) {
  48906. this._shadowFrustumSize = value;
  48907. this.forceProjectionMatrixCompute();
  48908. },
  48909. enumerable: true,
  48910. configurable: true
  48911. });
  48912. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  48913. /**
  48914. * Gets the shadow projection scale against the optimal computed one.
  48915. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48916. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48917. */
  48918. get: function () {
  48919. return this._shadowOrthoScale;
  48920. },
  48921. /**
  48922. * Sets the shadow projection scale against the optimal computed one.
  48923. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48924. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48925. */
  48926. set: function (value) {
  48927. this._shadowOrthoScale = value;
  48928. this.forceProjectionMatrixCompute();
  48929. },
  48930. enumerable: true,
  48931. configurable: true
  48932. });
  48933. /**
  48934. * Returns the string "DirectionalLight".
  48935. * @return The class name
  48936. */
  48937. DirectionalLight.prototype.getClassName = function () {
  48938. return "DirectionalLight";
  48939. };
  48940. /**
  48941. * Returns the integer 1.
  48942. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48943. */
  48944. DirectionalLight.prototype.getTypeID = function () {
  48945. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  48946. };
  48947. /**
  48948. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  48949. * Returns the DirectionalLight Shadow projection matrix.
  48950. */
  48951. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48952. if (this.shadowFrustumSize > 0) {
  48953. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  48954. }
  48955. else {
  48956. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48957. }
  48958. };
  48959. /**
  48960. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  48961. * Returns the DirectionalLight Shadow projection matrix.
  48962. */
  48963. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  48964. var activeCamera = this.getScene().activeCamera;
  48965. if (!activeCamera) {
  48966. return;
  48967. }
  48968. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  48969. };
  48970. /**
  48971. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  48972. * Returns the DirectionalLight Shadow projection matrix.
  48973. */
  48974. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48975. var activeCamera = this.getScene().activeCamera;
  48976. if (!activeCamera) {
  48977. return;
  48978. }
  48979. // Check extends
  48980. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  48981. var tempVector3 = BABYLON.Vector3.Zero();
  48982. this._orthoLeft = Number.MAX_VALUE;
  48983. this._orthoRight = Number.MIN_VALUE;
  48984. this._orthoTop = Number.MIN_VALUE;
  48985. this._orthoBottom = Number.MAX_VALUE;
  48986. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  48987. var mesh = renderList[meshIndex];
  48988. if (!mesh) {
  48989. continue;
  48990. }
  48991. var boundingInfo = mesh.getBoundingInfo();
  48992. var boundingBox = boundingInfo.boundingBox;
  48993. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  48994. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  48995. if (tempVector3.x < this._orthoLeft)
  48996. this._orthoLeft = tempVector3.x;
  48997. if (tempVector3.y < this._orthoBottom)
  48998. this._orthoBottom = tempVector3.y;
  48999. if (tempVector3.x > this._orthoRight)
  49000. this._orthoRight = tempVector3.x;
  49001. if (tempVector3.y > this._orthoTop)
  49002. this._orthoTop = tempVector3.y;
  49003. }
  49004. }
  49005. }
  49006. var xOffset = this._orthoRight - this._orthoLeft;
  49007. var yOffset = this._orthoTop - this._orthoBottom;
  49008. 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);
  49009. };
  49010. DirectionalLight.prototype._buildUniformLayout = function () {
  49011. this._uniformBuffer.addUniform("vLightData", 4);
  49012. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49013. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49014. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49015. this._uniformBuffer.addUniform("depthValues", 2);
  49016. this._uniformBuffer.create();
  49017. };
  49018. /**
  49019. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  49020. * @param effect The effect to update
  49021. * @param lightIndex The index of the light in the effect to update
  49022. * @returns The directional light
  49023. */
  49024. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  49025. if (this.computeTransformedInformation()) {
  49026. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  49027. return this;
  49028. }
  49029. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  49030. return this;
  49031. };
  49032. /**
  49033. * Gets the minZ used for shadow according to both the scene and the light.
  49034. *
  49035. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49036. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49037. * @param activeCamera The camera we are returning the min for
  49038. * @returns the depth min z
  49039. */
  49040. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  49041. return 1;
  49042. };
  49043. /**
  49044. * Gets the maxZ used for shadow according to both the scene and the light.
  49045. *
  49046. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49047. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49048. * @param activeCamera The camera we are returning the max for
  49049. * @returns the depth max z
  49050. */
  49051. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  49052. return 1;
  49053. };
  49054. /**
  49055. * Prepares the list of defines specific to the light type.
  49056. * @param defines the list of defines
  49057. * @param lightIndex defines the index of the light for the effect
  49058. */
  49059. DirectionalLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  49060. defines["DIRLIGHT" + lightIndex] = true;
  49061. };
  49062. __decorate([
  49063. BABYLON.serialize()
  49064. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  49065. __decorate([
  49066. BABYLON.serialize()
  49067. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  49068. __decorate([
  49069. BABYLON.serialize()
  49070. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  49071. return DirectionalLight;
  49072. }(BABYLON.ShadowLight));
  49073. BABYLON.DirectionalLight = DirectionalLight;
  49074. })(BABYLON || (BABYLON = {}));
  49075. //# sourceMappingURL=babylon.directionalLight.js.map
  49076. var BABYLON;
  49077. (function (BABYLON) {
  49078. BABYLON.Node.AddNodeConstructor("Light_Type_2", function (name, scene) {
  49079. return function () { return new SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  49080. });
  49081. /**
  49082. * A spot light is defined by a position, a direction, an angle, and an exponent.
  49083. * These values define a cone of light starting from the position, emitting toward the direction.
  49084. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  49085. * and the exponent defines the speed of the decay of the light with distance (reach).
  49086. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49087. */
  49088. var SpotLight = /** @class */ (function (_super) {
  49089. __extends(SpotLight, _super);
  49090. /**
  49091. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  49092. * It can cast shadows.
  49093. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49094. * @param name The light friendly name
  49095. * @param position The position of the spot light in the scene
  49096. * @param direction The direction of the light in the scene
  49097. * @param angle The cone angle of the light in Radians
  49098. * @param exponent The light decay speed with the distance from the emission spot
  49099. * @param scene The scene the lights belongs to
  49100. */
  49101. function SpotLight(name, position, direction, angle, exponent, scene) {
  49102. var _this = _super.call(this, name, scene) || this;
  49103. _this._innerAngle = 0;
  49104. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  49105. _this._projectionTextureLightNear = 1e-6;
  49106. _this._projectionTextureLightFar = 1000.0;
  49107. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  49108. _this._projectionTextureViewLightDirty = true;
  49109. _this._projectionTextureProjectionLightDirty = true;
  49110. _this._projectionTextureDirty = true;
  49111. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  49112. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  49113. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  49114. _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);
  49115. _this.position = position;
  49116. _this.direction = direction;
  49117. _this.angle = angle;
  49118. _this.exponent = exponent;
  49119. return _this;
  49120. }
  49121. Object.defineProperty(SpotLight.prototype, "angle", {
  49122. /**
  49123. * Gets the cone angle of the spot light in Radians.
  49124. */
  49125. get: function () {
  49126. return this._angle;
  49127. },
  49128. /**
  49129. * Sets the cone angle of the spot light in Radians.
  49130. */
  49131. set: function (value) {
  49132. this._angle = value;
  49133. this._cosHalfAngle = Math.cos(value * 0.5);
  49134. this._projectionTextureProjectionLightDirty = true;
  49135. this.forceProjectionMatrixCompute();
  49136. this._computeAngleValues();
  49137. },
  49138. enumerable: true,
  49139. configurable: true
  49140. });
  49141. Object.defineProperty(SpotLight.prototype, "innerAngle", {
  49142. /**
  49143. * Only used in gltf falloff mode, this defines the angle where
  49144. * the directional falloff will start before cutting at angle which could be seen
  49145. * as outer angle.
  49146. */
  49147. get: function () {
  49148. return this._angle;
  49149. },
  49150. /**
  49151. * Only used in gltf falloff mode, this defines the angle where
  49152. * the directional falloff will start before cutting at angle which could be seen
  49153. * as outer angle.
  49154. */
  49155. set: function (value) {
  49156. this._innerAngle = value;
  49157. this._computeAngleValues();
  49158. },
  49159. enumerable: true,
  49160. configurable: true
  49161. });
  49162. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  49163. /**
  49164. * Allows scaling the angle of the light for shadow generation only.
  49165. */
  49166. get: function () {
  49167. return this._shadowAngleScale;
  49168. },
  49169. /**
  49170. * Allows scaling the angle of the light for shadow generation only.
  49171. */
  49172. set: function (value) {
  49173. this._shadowAngleScale = value;
  49174. this.forceProjectionMatrixCompute();
  49175. },
  49176. enumerable: true,
  49177. configurable: true
  49178. });
  49179. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  49180. /**
  49181. * Allows reading the projecton texture
  49182. */
  49183. get: function () {
  49184. return this._projectionTextureMatrix;
  49185. },
  49186. enumerable: true,
  49187. configurable: true
  49188. });
  49189. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  49190. /**
  49191. * Gets the near clip of the Spotlight for texture projection.
  49192. */
  49193. get: function () {
  49194. return this._projectionTextureLightNear;
  49195. },
  49196. /**
  49197. * Sets the near clip of the Spotlight for texture projection.
  49198. */
  49199. set: function (value) {
  49200. this._projectionTextureLightNear = value;
  49201. this._projectionTextureProjectionLightDirty = true;
  49202. },
  49203. enumerable: true,
  49204. configurable: true
  49205. });
  49206. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  49207. /**
  49208. * Gets the far clip of the Spotlight for texture projection.
  49209. */
  49210. get: function () {
  49211. return this._projectionTextureLightFar;
  49212. },
  49213. /**
  49214. * Sets the far clip of the Spotlight for texture projection.
  49215. */
  49216. set: function (value) {
  49217. this._projectionTextureLightFar = value;
  49218. this._projectionTextureProjectionLightDirty = true;
  49219. },
  49220. enumerable: true,
  49221. configurable: true
  49222. });
  49223. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  49224. /**
  49225. * Gets the Up vector of the Spotlight for texture projection.
  49226. */
  49227. get: function () {
  49228. return this._projectionTextureUpDirection;
  49229. },
  49230. /**
  49231. * Sets the Up vector of the Spotlight for texture projection.
  49232. */
  49233. set: function (value) {
  49234. this._projectionTextureUpDirection = value;
  49235. this._projectionTextureProjectionLightDirty = true;
  49236. },
  49237. enumerable: true,
  49238. configurable: true
  49239. });
  49240. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  49241. /**
  49242. * Gets the projection texture of the light.
  49243. */
  49244. get: function () {
  49245. return this._projectionTexture;
  49246. },
  49247. /**
  49248. * Sets the projection texture of the light.
  49249. */
  49250. set: function (value) {
  49251. this._projectionTexture = value;
  49252. this._projectionTextureDirty = true;
  49253. },
  49254. enumerable: true,
  49255. configurable: true
  49256. });
  49257. /**
  49258. * Returns the string "SpotLight".
  49259. * @returns the class name
  49260. */
  49261. SpotLight.prototype.getClassName = function () {
  49262. return "SpotLight";
  49263. };
  49264. /**
  49265. * Returns the integer 2.
  49266. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49267. */
  49268. SpotLight.prototype.getTypeID = function () {
  49269. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  49270. };
  49271. /**
  49272. * Overrides the direction setter to recompute the projection texture view light Matrix.
  49273. */
  49274. SpotLight.prototype._setDirection = function (value) {
  49275. _super.prototype._setDirection.call(this, value);
  49276. this._projectionTextureViewLightDirty = true;
  49277. };
  49278. /**
  49279. * Overrides the position setter to recompute the projection texture view light Matrix.
  49280. */
  49281. SpotLight.prototype._setPosition = function (value) {
  49282. _super.prototype._setPosition.call(this, value);
  49283. this._projectionTextureViewLightDirty = true;
  49284. };
  49285. /**
  49286. * 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.
  49287. * Returns the SpotLight.
  49288. */
  49289. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49290. var activeCamera = this.getScene().activeCamera;
  49291. if (!activeCamera) {
  49292. return;
  49293. }
  49294. this._shadowAngleScale = this._shadowAngleScale || 1;
  49295. var angle = this._shadowAngleScale * this._angle;
  49296. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49297. };
  49298. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  49299. this._projectionTextureViewLightDirty = false;
  49300. this._projectionTextureDirty = true;
  49301. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  49302. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  49303. };
  49304. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  49305. this._projectionTextureProjectionLightDirty = false;
  49306. this._projectionTextureDirty = true;
  49307. var light_far = this.projectionTextureLightFar;
  49308. var light_near = this.projectionTextureLightNear;
  49309. var P = light_far / (light_far - light_near);
  49310. var Q = -P * light_near;
  49311. var S = 1.0 / Math.tan(this._angle / 2.0);
  49312. var A = 1.0;
  49313. 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);
  49314. };
  49315. /**
  49316. * Main function for light texture projection matrix computing.
  49317. */
  49318. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  49319. this._projectionTextureDirty = false;
  49320. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  49321. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  49322. };
  49323. SpotLight.prototype._buildUniformLayout = function () {
  49324. this._uniformBuffer.addUniform("vLightData", 4);
  49325. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49326. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49327. this._uniformBuffer.addUniform("vLightDirection", 3);
  49328. this._uniformBuffer.addUniform("vLightFalloff", 4);
  49329. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49330. this._uniformBuffer.addUniform("depthValues", 2);
  49331. this._uniformBuffer.create();
  49332. };
  49333. SpotLight.prototype._computeAngleValues = function () {
  49334. this._lightAngleScale = 1.0 / Math.max(0.001, (Math.cos(this._innerAngle * 0.5) - this._cosHalfAngle));
  49335. this._lightAngleOffset = -this._cosHalfAngle * this._lightAngleScale;
  49336. };
  49337. /**
  49338. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  49339. * @param effect The effect to update
  49340. * @param lightIndex The index of the light in the effect to update
  49341. * @returns The spot light
  49342. */
  49343. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  49344. var normalizeDirection;
  49345. if (this.computeTransformedInformation()) {
  49346. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  49347. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  49348. }
  49349. else {
  49350. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  49351. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49352. }
  49353. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, this._cosHalfAngle, lightIndex);
  49354. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, this._lightAngleScale, this._lightAngleOffset, lightIndex);
  49355. if (this.projectionTexture && this.projectionTexture.isReady()) {
  49356. if (this._projectionTextureViewLightDirty) {
  49357. this._computeProjectionTextureViewLightMatrix();
  49358. }
  49359. if (this._projectionTextureProjectionLightDirty) {
  49360. this._computeProjectionTextureProjectionLightMatrix();
  49361. }
  49362. if (this._projectionTextureDirty) {
  49363. this._computeProjectionTextureMatrix();
  49364. }
  49365. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  49366. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  49367. }
  49368. return this;
  49369. };
  49370. /**
  49371. * Disposes the light and the associated resources.
  49372. */
  49373. SpotLight.prototype.dispose = function () {
  49374. _super.prototype.dispose.call(this);
  49375. if (this._projectionTexture) {
  49376. this._projectionTexture.dispose();
  49377. }
  49378. };
  49379. /**
  49380. * Prepares the list of defines specific to the light type.
  49381. * @param defines the list of defines
  49382. * @param lightIndex defines the index of the light for the effect
  49383. */
  49384. SpotLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  49385. defines["SPOTLIGHT" + lightIndex] = true;
  49386. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = this.projectionTexture ? true : false;
  49387. };
  49388. __decorate([
  49389. BABYLON.serialize()
  49390. ], SpotLight.prototype, "angle", null);
  49391. __decorate([
  49392. BABYLON.serialize()
  49393. ], SpotLight.prototype, "innerAngle", null);
  49394. __decorate([
  49395. BABYLON.serialize()
  49396. ], SpotLight.prototype, "shadowAngleScale", null);
  49397. __decorate([
  49398. BABYLON.serialize()
  49399. ], SpotLight.prototype, "exponent", void 0);
  49400. __decorate([
  49401. BABYLON.serialize()
  49402. ], SpotLight.prototype, "projectionTextureLightNear", null);
  49403. __decorate([
  49404. BABYLON.serialize()
  49405. ], SpotLight.prototype, "projectionTextureLightFar", null);
  49406. __decorate([
  49407. BABYLON.serialize()
  49408. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  49409. __decorate([
  49410. BABYLON.serializeAsTexture("projectedLightTexture")
  49411. ], SpotLight.prototype, "_projectionTexture", void 0);
  49412. return SpotLight;
  49413. }(BABYLON.ShadowLight));
  49414. BABYLON.SpotLight = SpotLight;
  49415. })(BABYLON || (BABYLON = {}));
  49416. //# sourceMappingURL=babylon.spotLight.js.map
  49417. var BABYLON;
  49418. (function (BABYLON) {
  49419. /**
  49420. * Class used to override all child animations of a given target
  49421. */
  49422. var AnimationPropertiesOverride = /** @class */ (function () {
  49423. function AnimationPropertiesOverride() {
  49424. /**
  49425. * Gets or sets a value indicating if animation blending must be used
  49426. */
  49427. this.enableBlending = false;
  49428. /**
  49429. * Gets or sets the blending speed to use when enableBlending is true
  49430. */
  49431. this.blendingSpeed = 0.01;
  49432. /**
  49433. * Gets or sets the default loop mode to use
  49434. */
  49435. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  49436. }
  49437. return AnimationPropertiesOverride;
  49438. }());
  49439. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  49440. })(BABYLON || (BABYLON = {}));
  49441. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  49442. var BABYLON;
  49443. (function (BABYLON) {
  49444. /**
  49445. * Represents the range of an animation
  49446. */
  49447. var AnimationRange = /** @class */ (function () {
  49448. /**
  49449. * Initializes the range of an animation
  49450. * @param name The name of the animation range
  49451. * @param from The starting frame of the animation
  49452. * @param to The ending frame of the animation
  49453. */
  49454. function AnimationRange(
  49455. /**The name of the animation range**/
  49456. name,
  49457. /**The starting frame of the animation */
  49458. from,
  49459. /**The ending frame of the animation*/
  49460. to) {
  49461. this.name = name;
  49462. this.from = from;
  49463. this.to = to;
  49464. }
  49465. /**
  49466. * Makes a copy of the animation range
  49467. * @returns A copy of the animation range
  49468. */
  49469. AnimationRange.prototype.clone = function () {
  49470. return new AnimationRange(this.name, this.from, this.to);
  49471. };
  49472. return AnimationRange;
  49473. }());
  49474. BABYLON.AnimationRange = AnimationRange;
  49475. /**
  49476. * Composed of a frame, and an action function
  49477. */
  49478. var AnimationEvent = /** @class */ (function () {
  49479. /**
  49480. * Initializes the animation event
  49481. * @param frame The frame for which the event is triggered
  49482. * @param action The event to perform when triggered
  49483. * @param onlyOnce Specifies if the event should be triggered only once
  49484. */
  49485. function AnimationEvent(
  49486. /** The frame for which the event is triggered **/
  49487. frame,
  49488. /** The event to perform when triggered **/
  49489. action,
  49490. /** Specifies if the event should be triggered only once**/
  49491. onlyOnce) {
  49492. this.frame = frame;
  49493. this.action = action;
  49494. this.onlyOnce = onlyOnce;
  49495. /**
  49496. * Specifies if the animation event is done
  49497. */
  49498. this.isDone = false;
  49499. }
  49500. /** @hidden */
  49501. AnimationEvent.prototype._clone = function () {
  49502. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  49503. };
  49504. return AnimationEvent;
  49505. }());
  49506. BABYLON.AnimationEvent = AnimationEvent;
  49507. /**
  49508. * A cursor which tracks a point on a path
  49509. */
  49510. var PathCursor = /** @class */ (function () {
  49511. /**
  49512. * Initializes the path cursor
  49513. * @param path The path to track
  49514. */
  49515. function PathCursor(path) {
  49516. this.path = path;
  49517. /**
  49518. * Stores path cursor callbacks for when an onchange event is triggered
  49519. */
  49520. this._onchange = new Array();
  49521. /**
  49522. * The value of the path cursor
  49523. */
  49524. this.value = 0;
  49525. /**
  49526. * The animation array of the path cursor
  49527. */
  49528. this.animations = new Array();
  49529. }
  49530. /**
  49531. * Gets the cursor point on the path
  49532. * @returns A point on the path cursor at the cursor location
  49533. */
  49534. PathCursor.prototype.getPoint = function () {
  49535. var point = this.path.getPointAtLengthPosition(this.value);
  49536. return new BABYLON.Vector3(point.x, 0, point.y);
  49537. };
  49538. /**
  49539. * Moves the cursor ahead by the step amount
  49540. * @param step The amount to move the cursor forward
  49541. * @returns This path cursor
  49542. */
  49543. PathCursor.prototype.moveAhead = function (step) {
  49544. if (step === void 0) { step = 0.002; }
  49545. this.move(step);
  49546. return this;
  49547. };
  49548. /**
  49549. * Moves the cursor behind by the step amount
  49550. * @param step The amount to move the cursor back
  49551. * @returns This path cursor
  49552. */
  49553. PathCursor.prototype.moveBack = function (step) {
  49554. if (step === void 0) { step = 0.002; }
  49555. this.move(-step);
  49556. return this;
  49557. };
  49558. /**
  49559. * Moves the cursor by the step amount
  49560. * If the step amount is greater than one, an exception is thrown
  49561. * @param step The amount to move the cursor
  49562. * @returns This path cursor
  49563. */
  49564. PathCursor.prototype.move = function (step) {
  49565. if (Math.abs(step) > 1) {
  49566. throw "step size should be less than 1.";
  49567. }
  49568. this.value += step;
  49569. this.ensureLimits();
  49570. this.raiseOnChange();
  49571. return this;
  49572. };
  49573. /**
  49574. * Ensures that the value is limited between zero and one
  49575. * @returns This path cursor
  49576. */
  49577. PathCursor.prototype.ensureLimits = function () {
  49578. while (this.value > 1) {
  49579. this.value -= 1;
  49580. }
  49581. while (this.value < 0) {
  49582. this.value += 1;
  49583. }
  49584. return this;
  49585. };
  49586. /**
  49587. * Runs onchange callbacks on change (used by the animation engine)
  49588. * @returns This path cursor
  49589. */
  49590. PathCursor.prototype.raiseOnChange = function () {
  49591. var _this = this;
  49592. this._onchange.forEach(function (f) { return f(_this); });
  49593. return this;
  49594. };
  49595. /**
  49596. * Executes a function on change
  49597. * @param f A path cursor onchange callback
  49598. * @returns This path cursor
  49599. */
  49600. PathCursor.prototype.onchange = function (f) {
  49601. this._onchange.push(f);
  49602. return this;
  49603. };
  49604. return PathCursor;
  49605. }());
  49606. BABYLON.PathCursor = PathCursor;
  49607. /**
  49608. * Enum for the animation key frame interpolation type
  49609. */
  49610. var AnimationKeyInterpolation;
  49611. (function (AnimationKeyInterpolation) {
  49612. /**
  49613. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  49614. */
  49615. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  49616. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  49617. /**
  49618. * Class used to store any kind of animation
  49619. */
  49620. var Animation = /** @class */ (function () {
  49621. /**
  49622. * Initializes the animation
  49623. * @param name Name of the animation
  49624. * @param targetProperty Property to animate
  49625. * @param framePerSecond The frames per second of the animation
  49626. * @param dataType The data type of the animation
  49627. * @param loopMode The loop mode of the animation
  49628. * @param enableBlendings Specifies if blending should be enabled
  49629. */
  49630. function Animation(
  49631. /**Name of the animation */
  49632. name,
  49633. /**Property to animate */
  49634. targetProperty,
  49635. /**The frames per second of the animation */
  49636. framePerSecond,
  49637. /**The data type of the animation */
  49638. dataType,
  49639. /**The loop mode of the animation */
  49640. loopMode,
  49641. /**Specifies if blending should be enabled */
  49642. enableBlending) {
  49643. this.name = name;
  49644. this.targetProperty = targetProperty;
  49645. this.framePerSecond = framePerSecond;
  49646. this.dataType = dataType;
  49647. this.loopMode = loopMode;
  49648. this.enableBlending = enableBlending;
  49649. /**
  49650. * @hidden Internal use only
  49651. */
  49652. this._runtimeAnimations = new Array();
  49653. /**
  49654. * The set of event that will be linked to this animation
  49655. */
  49656. this._events = new Array();
  49657. /**
  49658. * Stores the blending speed of the animation
  49659. */
  49660. this.blendingSpeed = 0.01;
  49661. /**
  49662. * Stores the animation ranges for the animation
  49663. */
  49664. this._ranges = {};
  49665. this.targetPropertyPath = targetProperty.split(".");
  49666. this.dataType = dataType;
  49667. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  49668. }
  49669. /**
  49670. * @hidden Internal use
  49671. */
  49672. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  49673. var dataType = undefined;
  49674. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  49675. dataType = Animation.ANIMATIONTYPE_FLOAT;
  49676. }
  49677. else if (from instanceof BABYLON.Quaternion) {
  49678. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  49679. }
  49680. else if (from instanceof BABYLON.Vector3) {
  49681. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  49682. }
  49683. else if (from instanceof BABYLON.Vector2) {
  49684. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  49685. }
  49686. else if (from instanceof BABYLON.Color3) {
  49687. dataType = Animation.ANIMATIONTYPE_COLOR3;
  49688. }
  49689. else if (from instanceof BABYLON.Size) {
  49690. dataType = Animation.ANIMATIONTYPE_SIZE;
  49691. }
  49692. if (dataType == undefined) {
  49693. return null;
  49694. }
  49695. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  49696. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  49697. animation.setKeys(keys);
  49698. if (easingFunction !== undefined) {
  49699. animation.setEasingFunction(easingFunction);
  49700. }
  49701. return animation;
  49702. };
  49703. /**
  49704. * Sets up an animation
  49705. * @param property The property to animate
  49706. * @param animationType The animation type to apply
  49707. * @param framePerSecond The frames per second of the animation
  49708. * @param easingFunction The easing function used in the animation
  49709. * @returns The created animation
  49710. */
  49711. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  49712. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  49713. animation.setEasingFunction(easingFunction);
  49714. return animation;
  49715. };
  49716. /**
  49717. * Create and start an animation on a node
  49718. * @param name defines the name of the global animation that will be run on all nodes
  49719. * @param node defines the root node where the animation will take place
  49720. * @param targetProperty defines property to animate
  49721. * @param framePerSecond defines the number of frame per second yo use
  49722. * @param totalFrame defines the number of frames in total
  49723. * @param from defines the initial value
  49724. * @param to defines the final value
  49725. * @param loopMode defines which loop mode you want to use (off by default)
  49726. * @param easingFunction defines the easing function to use (linear by default)
  49727. * @param onAnimationEnd defines the callback to call when animation end
  49728. * @returns the animatable created for this animation
  49729. */
  49730. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49731. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49732. if (!animation) {
  49733. return null;
  49734. }
  49735. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49736. };
  49737. /**
  49738. * Create and start an animation on a node and its descendants
  49739. * @param name defines the name of the global animation that will be run on all nodes
  49740. * @param node defines the root node where the animation will take place
  49741. * @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
  49742. * @param targetProperty defines property to animate
  49743. * @param framePerSecond defines the number of frame per second to use
  49744. * @param totalFrame defines the number of frames in total
  49745. * @param from defines the initial value
  49746. * @param to defines the final value
  49747. * @param loopMode defines which loop mode you want to use (off by default)
  49748. * @param easingFunction defines the easing function to use (linear by default)
  49749. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  49750. * @returns the list of animatables created for all nodes
  49751. * @example https://www.babylonjs-playground.com/#MH0VLI
  49752. */
  49753. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49754. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49755. if (!animation) {
  49756. return null;
  49757. }
  49758. var scene = node.getScene();
  49759. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49760. };
  49761. /**
  49762. * Creates a new animation, merges it with the existing animations and starts it
  49763. * @param name Name of the animation
  49764. * @param node Node which contains the scene that begins the animations
  49765. * @param targetProperty Specifies which property to animate
  49766. * @param framePerSecond The frames per second of the animation
  49767. * @param totalFrame The total number of frames
  49768. * @param from The frame at the beginning of the animation
  49769. * @param to The frame at the end of the animation
  49770. * @param loopMode Specifies the loop mode of the animation
  49771. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  49772. * @param onAnimationEnd Callback to run once the animation is complete
  49773. * @returns Nullable animation
  49774. */
  49775. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49776. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49777. if (!animation) {
  49778. return null;
  49779. }
  49780. node.animations.push(animation);
  49781. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49782. };
  49783. /**
  49784. * Transition property of an host to the target Value
  49785. * @param property The property to transition
  49786. * @param targetValue The target Value of the property
  49787. * @param host The object where the property to animate belongs
  49788. * @param scene Scene used to run the animation
  49789. * @param frameRate Framerate (in frame/s) to use
  49790. * @param transition The transition type we want to use
  49791. * @param duration The duration of the animation, in milliseconds
  49792. * @param onAnimationEnd Callback trigger at the end of the animation
  49793. * @returns Nullable animation
  49794. */
  49795. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  49796. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  49797. if (duration <= 0) {
  49798. host[property] = targetValue;
  49799. if (onAnimationEnd) {
  49800. onAnimationEnd();
  49801. }
  49802. return null;
  49803. }
  49804. var endFrame = frameRate * (duration / 1000);
  49805. transition.setKeys([{
  49806. frame: 0,
  49807. value: host[property].clone ? host[property].clone() : host[property]
  49808. },
  49809. {
  49810. frame: endFrame,
  49811. value: targetValue
  49812. }]);
  49813. if (!host.animations) {
  49814. host.animations = [];
  49815. }
  49816. host.animations.push(transition);
  49817. var animation = scene.beginAnimation(host, 0, endFrame, false);
  49818. animation.onAnimationEnd = onAnimationEnd;
  49819. return animation;
  49820. };
  49821. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  49822. /**
  49823. * Return the array of runtime animations currently using this animation
  49824. */
  49825. get: function () {
  49826. return this._runtimeAnimations;
  49827. },
  49828. enumerable: true,
  49829. configurable: true
  49830. });
  49831. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  49832. /**
  49833. * Specifies if any of the runtime animations are currently running
  49834. */
  49835. get: function () {
  49836. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  49837. var runtimeAnimation = _a[_i];
  49838. if (!runtimeAnimation.isStopped) {
  49839. return true;
  49840. }
  49841. }
  49842. return false;
  49843. },
  49844. enumerable: true,
  49845. configurable: true
  49846. });
  49847. // Methods
  49848. /**
  49849. * Converts the animation to a string
  49850. * @param fullDetails support for multiple levels of logging within scene loading
  49851. * @returns String form of the animation
  49852. */
  49853. Animation.prototype.toString = function (fullDetails) {
  49854. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  49855. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  49856. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  49857. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  49858. if (fullDetails) {
  49859. ret += ", Ranges: {";
  49860. var first = true;
  49861. for (var name in this._ranges) {
  49862. if (first) {
  49863. ret += ", ";
  49864. first = false;
  49865. }
  49866. ret += name;
  49867. }
  49868. ret += "}";
  49869. }
  49870. return ret;
  49871. };
  49872. /**
  49873. * Add an event to this animation
  49874. * @param event Event to add
  49875. */
  49876. Animation.prototype.addEvent = function (event) {
  49877. this._events.push(event);
  49878. };
  49879. /**
  49880. * Remove all events found at the given frame
  49881. * @param frame The frame to remove events from
  49882. */
  49883. Animation.prototype.removeEvents = function (frame) {
  49884. for (var index = 0; index < this._events.length; index++) {
  49885. if (this._events[index].frame === frame) {
  49886. this._events.splice(index, 1);
  49887. index--;
  49888. }
  49889. }
  49890. };
  49891. /**
  49892. * Retrieves all the events from the animation
  49893. * @returns Events from the animation
  49894. */
  49895. Animation.prototype.getEvents = function () {
  49896. return this._events;
  49897. };
  49898. /**
  49899. * Creates an animation range
  49900. * @param name Name of the animation range
  49901. * @param from Starting frame of the animation range
  49902. * @param to Ending frame of the animation
  49903. */
  49904. Animation.prototype.createRange = function (name, from, to) {
  49905. // check name not already in use; could happen for bones after serialized
  49906. if (!this._ranges[name]) {
  49907. this._ranges[name] = new AnimationRange(name, from, to);
  49908. }
  49909. };
  49910. /**
  49911. * Deletes an animation range by name
  49912. * @param name Name of the animation range to delete
  49913. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  49914. */
  49915. Animation.prototype.deleteRange = function (name, deleteFrames) {
  49916. if (deleteFrames === void 0) { deleteFrames = true; }
  49917. var range = this._ranges[name];
  49918. if (!range) {
  49919. return;
  49920. }
  49921. if (deleteFrames) {
  49922. var from = range.from;
  49923. var to = range.to;
  49924. // this loop MUST go high to low for multiple splices to work
  49925. for (var key = this._keys.length - 1; key >= 0; key--) {
  49926. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  49927. this._keys.splice(key, 1);
  49928. }
  49929. }
  49930. }
  49931. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  49932. };
  49933. /**
  49934. * Gets the animation range by name, or null if not defined
  49935. * @param name Name of the animation range
  49936. * @returns Nullable animation range
  49937. */
  49938. Animation.prototype.getRange = function (name) {
  49939. return this._ranges[name];
  49940. };
  49941. /**
  49942. * Gets the key frames from the animation
  49943. * @returns The key frames of the animation
  49944. */
  49945. Animation.prototype.getKeys = function () {
  49946. return this._keys;
  49947. };
  49948. /**
  49949. * Gets the highest frame rate of the animation
  49950. * @returns Highest frame rate of the animation
  49951. */
  49952. Animation.prototype.getHighestFrame = function () {
  49953. var ret = 0;
  49954. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  49955. if (ret < this._keys[key].frame) {
  49956. ret = this._keys[key].frame;
  49957. }
  49958. }
  49959. return ret;
  49960. };
  49961. /**
  49962. * Gets the easing function of the animation
  49963. * @returns Easing function of the animation
  49964. */
  49965. Animation.prototype.getEasingFunction = function () {
  49966. return this._easingFunction;
  49967. };
  49968. /**
  49969. * Sets the easing function of the animation
  49970. * @param easingFunction A custom mathematical formula for animation
  49971. */
  49972. Animation.prototype.setEasingFunction = function (easingFunction) {
  49973. this._easingFunction = easingFunction;
  49974. };
  49975. /**
  49976. * Interpolates a scalar linearly
  49977. * @param startValue Start value of the animation curve
  49978. * @param endValue End value of the animation curve
  49979. * @param gradient Scalar amount to interpolate
  49980. * @returns Interpolated scalar value
  49981. */
  49982. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  49983. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  49984. };
  49985. /**
  49986. * Interpolates a scalar cubically
  49987. * @param startValue Start value of the animation curve
  49988. * @param outTangent End tangent of the animation
  49989. * @param endValue End value of the animation curve
  49990. * @param inTangent Start tangent of the animation curve
  49991. * @param gradient Scalar amount to interpolate
  49992. * @returns Interpolated scalar value
  49993. */
  49994. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49995. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49996. };
  49997. /**
  49998. * Interpolates a quaternion using a spherical linear interpolation
  49999. * @param startValue Start value of the animation curve
  50000. * @param endValue End value of the animation curve
  50001. * @param gradient Scalar amount to interpolate
  50002. * @returns Interpolated quaternion value
  50003. */
  50004. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  50005. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  50006. };
  50007. /**
  50008. * Interpolates a quaternion cubically
  50009. * @param startValue Start value of the animation curve
  50010. * @param outTangent End tangent of the animation curve
  50011. * @param endValue End value of the animation curve
  50012. * @param inTangent Start tangent of the animation curve
  50013. * @param gradient Scalar amount to interpolate
  50014. * @returns Interpolated quaternion value
  50015. */
  50016. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50017. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  50018. };
  50019. /**
  50020. * Interpolates a Vector3 linearl
  50021. * @param startValue Start value of the animation curve
  50022. * @param endValue End value of the animation curve
  50023. * @param gradient Scalar amount to interpolate
  50024. * @returns Interpolated scalar value
  50025. */
  50026. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  50027. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  50028. };
  50029. /**
  50030. * Interpolates a Vector3 cubically
  50031. * @param startValue Start value of the animation curve
  50032. * @param outTangent End tangent of the animation
  50033. * @param endValue End value of the animation curve
  50034. * @param inTangent Start tangent of the animation curve
  50035. * @param gradient Scalar amount to interpolate
  50036. * @returns InterpolatedVector3 value
  50037. */
  50038. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50039. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50040. };
  50041. /**
  50042. * Interpolates a Vector2 linearly
  50043. * @param startValue Start value of the animation curve
  50044. * @param endValue End value of the animation curve
  50045. * @param gradient Scalar amount to interpolate
  50046. * @returns Interpolated Vector2 value
  50047. */
  50048. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  50049. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  50050. };
  50051. /**
  50052. * Interpolates a Vector2 cubically
  50053. * @param startValue Start value of the animation curve
  50054. * @param outTangent End tangent of the animation
  50055. * @param endValue End value of the animation curve
  50056. * @param inTangent Start tangent of the animation curve
  50057. * @param gradient Scalar amount to interpolate
  50058. * @returns Interpolated Vector2 value
  50059. */
  50060. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50061. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50062. };
  50063. /**
  50064. * Interpolates a size linearly
  50065. * @param startValue Start value of the animation curve
  50066. * @param endValue End value of the animation curve
  50067. * @param gradient Scalar amount to interpolate
  50068. * @returns Interpolated Size value
  50069. */
  50070. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  50071. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  50072. };
  50073. /**
  50074. * Interpolates a Color3 linearly
  50075. * @param startValue Start value of the animation curve
  50076. * @param endValue End value of the animation curve
  50077. * @param gradient Scalar amount to interpolate
  50078. * @returns Interpolated Color3 value
  50079. */
  50080. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  50081. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  50082. };
  50083. /**
  50084. * @hidden Internal use only
  50085. */
  50086. Animation.prototype._getKeyValue = function (value) {
  50087. if (typeof value === "function") {
  50088. return value();
  50089. }
  50090. return value;
  50091. };
  50092. /**
  50093. * @hidden Internal use only
  50094. */
  50095. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  50096. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  50097. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  50098. }
  50099. var keys = this.getKeys();
  50100. // Try to get a hash to find the right key
  50101. 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));
  50102. if (keys[startKeyIndex].frame >= currentFrame) {
  50103. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  50104. startKeyIndex--;
  50105. }
  50106. }
  50107. for (var key = startKeyIndex; key < keys.length; key++) {
  50108. var endKey = keys[key + 1];
  50109. if (endKey.frame >= currentFrame) {
  50110. var startKey = keys[key];
  50111. var startValue = this._getKeyValue(startKey.value);
  50112. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  50113. return startValue;
  50114. }
  50115. var endValue = this._getKeyValue(endKey.value);
  50116. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  50117. var frameDelta = endKey.frame - startKey.frame;
  50118. // gradient : percent of currentFrame between the frame inf and the frame sup
  50119. var gradient = (currentFrame - startKey.frame) / frameDelta;
  50120. // check for easingFunction and correction of gradient
  50121. var easingFunction = this.getEasingFunction();
  50122. if (easingFunction != null) {
  50123. gradient = easingFunction.ease(gradient);
  50124. }
  50125. switch (this.dataType) {
  50126. // Float
  50127. case Animation.ANIMATIONTYPE_FLOAT:
  50128. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  50129. switch (loopMode) {
  50130. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50131. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50132. return floatValue;
  50133. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50134. return offsetValue * repeatCount + floatValue;
  50135. }
  50136. break;
  50137. // Quaternion
  50138. case Animation.ANIMATIONTYPE_QUATERNION:
  50139. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  50140. switch (loopMode) {
  50141. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50142. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50143. return quatValue;
  50144. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50145. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  50146. }
  50147. return quatValue;
  50148. // Vector3
  50149. case Animation.ANIMATIONTYPE_VECTOR3:
  50150. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  50151. switch (loopMode) {
  50152. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50153. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50154. return vec3Value;
  50155. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50156. return vec3Value.add(offsetValue.scale(repeatCount));
  50157. }
  50158. // Vector2
  50159. case Animation.ANIMATIONTYPE_VECTOR2:
  50160. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  50161. switch (loopMode) {
  50162. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50163. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50164. return vec2Value;
  50165. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50166. return vec2Value.add(offsetValue.scale(repeatCount));
  50167. }
  50168. // Size
  50169. case Animation.ANIMATIONTYPE_SIZE:
  50170. switch (loopMode) {
  50171. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50172. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50173. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  50174. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50175. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50176. }
  50177. // Color3
  50178. case Animation.ANIMATIONTYPE_COLOR3:
  50179. switch (loopMode) {
  50180. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50181. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50182. return this.color3InterpolateFunction(startValue, endValue, gradient);
  50183. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50184. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50185. }
  50186. // Matrix
  50187. case Animation.ANIMATIONTYPE_MATRIX:
  50188. switch (loopMode) {
  50189. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50190. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50191. if (Animation.AllowMatricesInterpolation) {
  50192. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  50193. }
  50194. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50195. return startValue;
  50196. }
  50197. default:
  50198. break;
  50199. }
  50200. break;
  50201. }
  50202. }
  50203. return this._getKeyValue(keys[keys.length - 1].value);
  50204. };
  50205. /**
  50206. * Defines the function to use to interpolate matrices
  50207. * @param startValue defines the start matrix
  50208. * @param endValue defines the end matrix
  50209. * @param gradient defines the gradient between both matrices
  50210. * @param result defines an optional target matrix where to store the interpolation
  50211. * @returns the interpolated matrix
  50212. */
  50213. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  50214. if (Animation.AllowMatrixDecomposeForInterpolation) {
  50215. if (result) {
  50216. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  50217. return result;
  50218. }
  50219. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  50220. }
  50221. if (result) {
  50222. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  50223. return result;
  50224. }
  50225. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  50226. };
  50227. /**
  50228. * Makes a copy of the animation
  50229. * @returns Cloned animation
  50230. */
  50231. Animation.prototype.clone = function () {
  50232. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  50233. clone.enableBlending = this.enableBlending;
  50234. clone.blendingSpeed = this.blendingSpeed;
  50235. if (this._keys) {
  50236. clone.setKeys(this._keys);
  50237. }
  50238. if (this._ranges) {
  50239. clone._ranges = {};
  50240. for (var name in this._ranges) {
  50241. var range = this._ranges[name];
  50242. if (!range) {
  50243. continue;
  50244. }
  50245. clone._ranges[name] = range.clone();
  50246. }
  50247. }
  50248. return clone;
  50249. };
  50250. /**
  50251. * Sets the key frames of the animation
  50252. * @param values The animation key frames to set
  50253. */
  50254. Animation.prototype.setKeys = function (values) {
  50255. this._keys = values.slice(0);
  50256. };
  50257. /**
  50258. * Serializes the animation to an object
  50259. * @returns Serialized object
  50260. */
  50261. Animation.prototype.serialize = function () {
  50262. var serializationObject = {};
  50263. serializationObject.name = this.name;
  50264. serializationObject.property = this.targetProperty;
  50265. serializationObject.framePerSecond = this.framePerSecond;
  50266. serializationObject.dataType = this.dataType;
  50267. serializationObject.loopBehavior = this.loopMode;
  50268. serializationObject.enableBlending = this.enableBlending;
  50269. serializationObject.blendingSpeed = this.blendingSpeed;
  50270. var dataType = this.dataType;
  50271. serializationObject.keys = [];
  50272. var keys = this.getKeys();
  50273. for (var index = 0; index < keys.length; index++) {
  50274. var animationKey = keys[index];
  50275. var key = {};
  50276. key.frame = animationKey.frame;
  50277. switch (dataType) {
  50278. case Animation.ANIMATIONTYPE_FLOAT:
  50279. key.values = [animationKey.value];
  50280. break;
  50281. case Animation.ANIMATIONTYPE_QUATERNION:
  50282. case Animation.ANIMATIONTYPE_MATRIX:
  50283. case Animation.ANIMATIONTYPE_VECTOR3:
  50284. case Animation.ANIMATIONTYPE_COLOR3:
  50285. key.values = animationKey.value.asArray();
  50286. break;
  50287. }
  50288. serializationObject.keys.push(key);
  50289. }
  50290. serializationObject.ranges = [];
  50291. for (var name in this._ranges) {
  50292. var source = this._ranges[name];
  50293. if (!source) {
  50294. continue;
  50295. }
  50296. var range = {};
  50297. range.name = name;
  50298. range.from = source.from;
  50299. range.to = source.to;
  50300. serializationObject.ranges.push(range);
  50301. }
  50302. return serializationObject;
  50303. };
  50304. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  50305. /**
  50306. * Get the float animation type
  50307. */
  50308. get: function () {
  50309. return Animation._ANIMATIONTYPE_FLOAT;
  50310. },
  50311. enumerable: true,
  50312. configurable: true
  50313. });
  50314. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  50315. /**
  50316. * Get the Vector3 animation type
  50317. */
  50318. get: function () {
  50319. return Animation._ANIMATIONTYPE_VECTOR3;
  50320. },
  50321. enumerable: true,
  50322. configurable: true
  50323. });
  50324. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  50325. /**
  50326. * Get the Vector2 animation type
  50327. */
  50328. get: function () {
  50329. return Animation._ANIMATIONTYPE_VECTOR2;
  50330. },
  50331. enumerable: true,
  50332. configurable: true
  50333. });
  50334. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  50335. /**
  50336. * Get the Size animation type
  50337. */
  50338. get: function () {
  50339. return Animation._ANIMATIONTYPE_SIZE;
  50340. },
  50341. enumerable: true,
  50342. configurable: true
  50343. });
  50344. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  50345. /**
  50346. * Get the Quaternion animation type
  50347. */
  50348. get: function () {
  50349. return Animation._ANIMATIONTYPE_QUATERNION;
  50350. },
  50351. enumerable: true,
  50352. configurable: true
  50353. });
  50354. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  50355. /**
  50356. * Get the Matrix animation type
  50357. */
  50358. get: function () {
  50359. return Animation._ANIMATIONTYPE_MATRIX;
  50360. },
  50361. enumerable: true,
  50362. configurable: true
  50363. });
  50364. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  50365. /**
  50366. * Get the Color3 animation type
  50367. */
  50368. get: function () {
  50369. return Animation._ANIMATIONTYPE_COLOR3;
  50370. },
  50371. enumerable: true,
  50372. configurable: true
  50373. });
  50374. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  50375. /**
  50376. * Get the Relative Loop Mode
  50377. */
  50378. get: function () {
  50379. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  50380. },
  50381. enumerable: true,
  50382. configurable: true
  50383. });
  50384. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  50385. /**
  50386. * Get the Cycle Loop Mode
  50387. */
  50388. get: function () {
  50389. return Animation._ANIMATIONLOOPMODE_CYCLE;
  50390. },
  50391. enumerable: true,
  50392. configurable: true
  50393. });
  50394. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  50395. /**
  50396. * Get the Constant Loop Mode
  50397. */
  50398. get: function () {
  50399. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  50400. },
  50401. enumerable: true,
  50402. configurable: true
  50403. });
  50404. /** @hidden */
  50405. Animation._UniversalLerp = function (left, right, amount) {
  50406. var constructor = left.constructor;
  50407. if (constructor.Lerp) { // Lerp supported
  50408. return constructor.Lerp(left, right, amount);
  50409. }
  50410. else if (constructor.Slerp) { // Slerp supported
  50411. return constructor.Slerp(left, right, amount);
  50412. }
  50413. else if (left.toFixed) { // Number
  50414. return left * (1.0 - amount) + amount * right;
  50415. }
  50416. else { // Blending not supported
  50417. return right;
  50418. }
  50419. };
  50420. /**
  50421. * Parses an animation object and creates an animation
  50422. * @param parsedAnimation Parsed animation object
  50423. * @returns Animation object
  50424. */
  50425. Animation.Parse = function (parsedAnimation) {
  50426. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  50427. var dataType = parsedAnimation.dataType;
  50428. var keys = [];
  50429. var data;
  50430. var index;
  50431. if (parsedAnimation.enableBlending) {
  50432. animation.enableBlending = parsedAnimation.enableBlending;
  50433. }
  50434. if (parsedAnimation.blendingSpeed) {
  50435. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  50436. }
  50437. for (index = 0; index < parsedAnimation.keys.length; index++) {
  50438. var key = parsedAnimation.keys[index];
  50439. var inTangent;
  50440. var outTangent;
  50441. switch (dataType) {
  50442. case Animation.ANIMATIONTYPE_FLOAT:
  50443. data = key.values[0];
  50444. if (key.values.length >= 1) {
  50445. inTangent = key.values[1];
  50446. }
  50447. if (key.values.length >= 2) {
  50448. outTangent = key.values[2];
  50449. }
  50450. break;
  50451. case Animation.ANIMATIONTYPE_QUATERNION:
  50452. data = BABYLON.Quaternion.FromArray(key.values);
  50453. if (key.values.length >= 8) {
  50454. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  50455. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  50456. inTangent = _inTangent;
  50457. }
  50458. }
  50459. if (key.values.length >= 12) {
  50460. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  50461. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  50462. outTangent = _outTangent;
  50463. }
  50464. }
  50465. break;
  50466. case Animation.ANIMATIONTYPE_MATRIX:
  50467. data = BABYLON.Matrix.FromArray(key.values);
  50468. break;
  50469. case Animation.ANIMATIONTYPE_COLOR3:
  50470. data = BABYLON.Color3.FromArray(key.values);
  50471. break;
  50472. case Animation.ANIMATIONTYPE_VECTOR3:
  50473. default:
  50474. data = BABYLON.Vector3.FromArray(key.values);
  50475. break;
  50476. }
  50477. var keyData = {};
  50478. keyData.frame = key.frame;
  50479. keyData.value = data;
  50480. if (inTangent != undefined) {
  50481. keyData.inTangent = inTangent;
  50482. }
  50483. if (outTangent != undefined) {
  50484. keyData.outTangent = outTangent;
  50485. }
  50486. keys.push(keyData);
  50487. }
  50488. animation.setKeys(keys);
  50489. if (parsedAnimation.ranges) {
  50490. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  50491. data = parsedAnimation.ranges[index];
  50492. animation.createRange(data.name, data.from, data.to);
  50493. }
  50494. }
  50495. return animation;
  50496. };
  50497. /**
  50498. * Appends the serialized animations from the source animations
  50499. * @param source Source containing the animations
  50500. * @param destination Target to store the animations
  50501. */
  50502. Animation.AppendSerializedAnimations = function (source, destination) {
  50503. if (source.animations) {
  50504. destination.animations = [];
  50505. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  50506. var animation = source.animations[animationIndex];
  50507. destination.animations.push(animation.serialize());
  50508. }
  50509. }
  50510. };
  50511. /**
  50512. * Use matrix interpolation instead of using direct key value when animating matrices
  50513. */
  50514. Animation.AllowMatricesInterpolation = false;
  50515. /**
  50516. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  50517. */
  50518. Animation.AllowMatrixDecomposeForInterpolation = true;
  50519. // Statics
  50520. /**
  50521. * Float animation type
  50522. */
  50523. Animation._ANIMATIONTYPE_FLOAT = 0;
  50524. /**
  50525. * Vector3 animation type
  50526. */
  50527. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  50528. /**
  50529. * Quaternion animation type
  50530. */
  50531. Animation._ANIMATIONTYPE_QUATERNION = 2;
  50532. /**
  50533. * Matrix animation type
  50534. */
  50535. Animation._ANIMATIONTYPE_MATRIX = 3;
  50536. /**
  50537. * Color3 animation type
  50538. */
  50539. Animation._ANIMATIONTYPE_COLOR3 = 4;
  50540. /**
  50541. * Vector2 animation type
  50542. */
  50543. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  50544. /**
  50545. * Size animation type
  50546. */
  50547. Animation._ANIMATIONTYPE_SIZE = 6;
  50548. /**
  50549. * Relative Loop Mode
  50550. */
  50551. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  50552. /**
  50553. * Cycle Loop Mode
  50554. */
  50555. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  50556. /**
  50557. * Constant Loop Mode
  50558. */
  50559. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  50560. return Animation;
  50561. }());
  50562. BABYLON.Animation = Animation;
  50563. })(BABYLON || (BABYLON = {}));
  50564. //# sourceMappingURL=babylon.animation.js.map
  50565. var BABYLON;
  50566. (function (BABYLON) {
  50567. /**
  50568. * This class defines the direct association between an animation and a target
  50569. */
  50570. var TargetedAnimation = /** @class */ (function () {
  50571. function TargetedAnimation() {
  50572. }
  50573. return TargetedAnimation;
  50574. }());
  50575. BABYLON.TargetedAnimation = TargetedAnimation;
  50576. /**
  50577. * Use this class to create coordinated animations on multiple targets
  50578. */
  50579. var AnimationGroup = /** @class */ (function () {
  50580. function AnimationGroup(name, scene) {
  50581. if (scene === void 0) { scene = null; }
  50582. this.name = name;
  50583. this._targetedAnimations = new Array();
  50584. this._animatables = new Array();
  50585. this._from = Number.MAX_VALUE;
  50586. this._to = -Number.MAX_VALUE;
  50587. this._speedRatio = 1;
  50588. this.onAnimationEndObservable = new BABYLON.Observable();
  50589. /**
  50590. * This observable will notify when all animations have ended.
  50591. */
  50592. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  50593. /**
  50594. * This observable will notify when all animations have paused.
  50595. */
  50596. this.onAnimationGroupPauseObservable = new BABYLON.Observable();
  50597. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50598. this._scene.animationGroups.push(this);
  50599. }
  50600. Object.defineProperty(AnimationGroup.prototype, "from", {
  50601. /**
  50602. * Gets the first frame
  50603. */
  50604. get: function () {
  50605. return this._from;
  50606. },
  50607. enumerable: true,
  50608. configurable: true
  50609. });
  50610. Object.defineProperty(AnimationGroup.prototype, "to", {
  50611. /**
  50612. * Gets the last frame
  50613. */
  50614. get: function () {
  50615. return this._to;
  50616. },
  50617. enumerable: true,
  50618. configurable: true
  50619. });
  50620. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  50621. /**
  50622. * Define if the animations are started
  50623. */
  50624. get: function () {
  50625. return this._isStarted;
  50626. },
  50627. enumerable: true,
  50628. configurable: true
  50629. });
  50630. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  50631. /**
  50632. * Gets or sets the speed ratio to use for all animations
  50633. */
  50634. get: function () {
  50635. return this._speedRatio;
  50636. },
  50637. /**
  50638. * Gets or sets the speed ratio to use for all animations
  50639. */
  50640. set: function (value) {
  50641. if (this._speedRatio === value) {
  50642. return;
  50643. }
  50644. this._speedRatio = value;
  50645. for (var index = 0; index < this._animatables.length; index++) {
  50646. var animatable = this._animatables[index];
  50647. animatable.speedRatio = this._speedRatio;
  50648. }
  50649. },
  50650. enumerable: true,
  50651. configurable: true
  50652. });
  50653. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  50654. /**
  50655. * Gets the targeted animations for this animation group
  50656. */
  50657. get: function () {
  50658. return this._targetedAnimations;
  50659. },
  50660. enumerable: true,
  50661. configurable: true
  50662. });
  50663. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  50664. /**
  50665. * returning the list of animatables controlled by this animation group.
  50666. */
  50667. get: function () {
  50668. return this._animatables;
  50669. },
  50670. enumerable: true,
  50671. configurable: true
  50672. });
  50673. /**
  50674. * Add an animation (with its target) in the group
  50675. * @param animation defines the animation we want to add
  50676. * @param target defines the target of the animation
  50677. * @returns the {BABYLON.TargetedAnimation} object
  50678. */
  50679. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  50680. var targetedAnimation = {
  50681. animation: animation,
  50682. target: target
  50683. };
  50684. var keys = animation.getKeys();
  50685. if (this._from > keys[0].frame) {
  50686. this._from = keys[0].frame;
  50687. }
  50688. if (this._to < keys[keys.length - 1].frame) {
  50689. this._to = keys[keys.length - 1].frame;
  50690. }
  50691. this._targetedAnimations.push(targetedAnimation);
  50692. return targetedAnimation;
  50693. };
  50694. /**
  50695. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  50696. * It can add constant keys at begin or end
  50697. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  50698. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  50699. */
  50700. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  50701. if (beginFrame === void 0) { beginFrame = null; }
  50702. if (endFrame === void 0) { endFrame = null; }
  50703. if (beginFrame == null)
  50704. beginFrame = this._from;
  50705. if (endFrame == null)
  50706. endFrame = this._to;
  50707. for (var index = 0; index < this._targetedAnimations.length; index++) {
  50708. var targetedAnimation = this._targetedAnimations[index];
  50709. var keys = targetedAnimation.animation.getKeys();
  50710. var startKey = keys[0];
  50711. var endKey = keys[keys.length - 1];
  50712. if (startKey.frame > beginFrame) {
  50713. var newKey = {
  50714. frame: beginFrame,
  50715. value: startKey.value,
  50716. inTangent: startKey.inTangent,
  50717. outTangent: startKey.outTangent,
  50718. interpolation: startKey.interpolation
  50719. };
  50720. keys.splice(0, 0, newKey);
  50721. }
  50722. if (endKey.frame < endFrame) {
  50723. var newKey = {
  50724. frame: endFrame,
  50725. value: endKey.value,
  50726. inTangent: endKey.outTangent,
  50727. outTangent: endKey.outTangent,
  50728. interpolation: endKey.interpolation
  50729. };
  50730. keys.push(newKey);
  50731. }
  50732. }
  50733. this._from = beginFrame;
  50734. this._to = endFrame;
  50735. return this;
  50736. };
  50737. /**
  50738. * Start all animations on given targets
  50739. * @param loop defines if animations must loop
  50740. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  50741. * @param from defines the from key (optional)
  50742. * @param to defines the to key (optional)
  50743. * @returns the current animation group
  50744. */
  50745. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  50746. var _this = this;
  50747. if (loop === void 0) { loop = false; }
  50748. if (speedRatio === void 0) { speedRatio = 1; }
  50749. if (this._isStarted || this._targetedAnimations.length === 0) {
  50750. return this;
  50751. }
  50752. var _loop_1 = function (targetedAnimation) {
  50753. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  50754. animatable.onAnimationEnd = function () {
  50755. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  50756. _this._checkAnimationGroupEnded(animatable);
  50757. };
  50758. this_1._animatables.push(animatable);
  50759. };
  50760. var this_1 = this;
  50761. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  50762. var targetedAnimation = _a[_i];
  50763. _loop_1(targetedAnimation);
  50764. }
  50765. this._speedRatio = speedRatio;
  50766. this._isStarted = true;
  50767. return this;
  50768. };
  50769. /**
  50770. * Pause all animations
  50771. */
  50772. AnimationGroup.prototype.pause = function () {
  50773. if (!this._isStarted) {
  50774. return this;
  50775. }
  50776. for (var index = 0; index < this._animatables.length; index++) {
  50777. var animatable = this._animatables[index];
  50778. animatable.pause();
  50779. }
  50780. this.onAnimationGroupPauseObservable.notifyObservers(this);
  50781. return this;
  50782. };
  50783. /**
  50784. * Play all animations to initial state
  50785. * This function will start() the animations if they were not started or will restart() them if they were paused
  50786. * @param loop defines if animations must loop
  50787. */
  50788. AnimationGroup.prototype.play = function (loop) {
  50789. // only if all animatables are ready and exist
  50790. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  50791. if (loop !== undefined) {
  50792. for (var index = 0; index < this._animatables.length; index++) {
  50793. var animatable = this._animatables[index];
  50794. animatable.loopAnimation = loop;
  50795. }
  50796. }
  50797. this.restart();
  50798. }
  50799. else {
  50800. this.stop();
  50801. this.start(loop, this._speedRatio);
  50802. }
  50803. return this;
  50804. };
  50805. /**
  50806. * Reset all animations to initial state
  50807. */
  50808. AnimationGroup.prototype.reset = function () {
  50809. if (!this._isStarted) {
  50810. return this;
  50811. }
  50812. for (var index = 0; index < this._animatables.length; index++) {
  50813. var animatable = this._animatables[index];
  50814. animatable.reset();
  50815. }
  50816. return this;
  50817. };
  50818. /**
  50819. * Restart animations from key 0
  50820. */
  50821. AnimationGroup.prototype.restart = function () {
  50822. if (!this._isStarted) {
  50823. return this;
  50824. }
  50825. for (var index = 0; index < this._animatables.length; index++) {
  50826. var animatable = this._animatables[index];
  50827. animatable.restart();
  50828. }
  50829. return this;
  50830. };
  50831. /**
  50832. * Stop all animations
  50833. */
  50834. AnimationGroup.prototype.stop = function () {
  50835. if (!this._isStarted) {
  50836. return this;
  50837. }
  50838. var list = this._animatables.slice();
  50839. for (var index = 0; index < list.length; index++) {
  50840. list[index].stop();
  50841. }
  50842. this._isStarted = false;
  50843. return this;
  50844. };
  50845. /**
  50846. * Set animation weight for all animatables
  50847. * @param weight defines the weight to use
  50848. * @return the animationGroup
  50849. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  50850. */
  50851. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  50852. for (var index = 0; index < this._animatables.length; index++) {
  50853. var animatable = this._animatables[index];
  50854. animatable.weight = weight;
  50855. }
  50856. return this;
  50857. };
  50858. /**
  50859. * Synchronize and normalize all animatables with a source animatable
  50860. * @param root defines the root animatable to synchronize with
  50861. * @return the animationGroup
  50862. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  50863. */
  50864. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  50865. for (var index = 0; index < this._animatables.length; index++) {
  50866. var animatable = this._animatables[index];
  50867. animatable.syncWith(root);
  50868. }
  50869. return this;
  50870. };
  50871. /**
  50872. * Goes to a specific frame in this animation group
  50873. * @param frame the frame number to go to
  50874. * @return the animationGroup
  50875. */
  50876. AnimationGroup.prototype.goToFrame = function (frame) {
  50877. if (!this._isStarted) {
  50878. return this;
  50879. }
  50880. for (var index = 0; index < this._animatables.length; index++) {
  50881. var animatable = this._animatables[index];
  50882. animatable.goToFrame(frame);
  50883. }
  50884. return this;
  50885. };
  50886. /**
  50887. * Dispose all associated resources
  50888. */
  50889. AnimationGroup.prototype.dispose = function () {
  50890. this._targetedAnimations = [];
  50891. this._animatables = [];
  50892. var index = this._scene.animationGroups.indexOf(this);
  50893. if (index > -1) {
  50894. this._scene.animationGroups.splice(index, 1);
  50895. }
  50896. };
  50897. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  50898. // animatable should be taken out of the array
  50899. var idx = this._animatables.indexOf(animatable);
  50900. if (idx > -1) {
  50901. this._animatables.splice(idx, 1);
  50902. }
  50903. // all animatables were removed? animation group ended!
  50904. if (this._animatables.length === 0) {
  50905. this._isStarted = false;
  50906. this.onAnimationGroupEndObservable.notifyObservers(this);
  50907. }
  50908. };
  50909. return AnimationGroup;
  50910. }());
  50911. BABYLON.AnimationGroup = AnimationGroup;
  50912. })(BABYLON || (BABYLON = {}));
  50913. //# sourceMappingURL=babylon.animationGroup.js.map
  50914. var BABYLON;
  50915. (function (BABYLON) {
  50916. // Static values to help the garbage collector
  50917. // Quaternion
  50918. var _staticOffsetValueQuaternion = Object.freeze(new BABYLON.Quaternion(0, 0, 0, 0));
  50919. // Vector3
  50920. var _staticOffsetValueVector3 = Object.freeze(BABYLON.Vector3.Zero());
  50921. // Vector2
  50922. var _staticOffsetValueVector2 = Object.freeze(BABYLON.Vector2.Zero());
  50923. // Size
  50924. var _staticOffsetValueSize = Object.freeze(BABYLON.Size.Zero());
  50925. // Color3
  50926. var _staticOffsetValueColor3 = Object.freeze(BABYLON.Color3.Black());
  50927. /**
  50928. * Defines a runtime animation
  50929. */
  50930. var RuntimeAnimation = /** @class */ (function () {
  50931. /**
  50932. * Create a new RuntimeAnimation object
  50933. * @param target defines the target of the animation
  50934. * @param animation defines the source animation object
  50935. * @param scene defines the hosting scene
  50936. * @param host defines the initiating Animatable
  50937. */
  50938. function RuntimeAnimation(target, animation, scene, host) {
  50939. var _this = this;
  50940. this._events = new Array();
  50941. /**
  50942. * The current frame of the runtime animation
  50943. */
  50944. this._currentFrame = 0;
  50945. /**
  50946. * The original value of the runtime animation
  50947. */
  50948. this._originalValue = new Array();
  50949. /**
  50950. * The offsets cache of the runtime animation
  50951. */
  50952. this._offsetsCache = {};
  50953. /**
  50954. * The high limits cache of the runtime animation
  50955. */
  50956. this._highLimitsCache = {};
  50957. /**
  50958. * Specifies if the runtime animation has been stopped
  50959. */
  50960. this._stopped = false;
  50961. /**
  50962. * The blending factor of the runtime animation
  50963. */
  50964. this._blendingFactor = 0;
  50965. /**
  50966. * The target path of the runtime animation
  50967. */
  50968. this._targetPath = "";
  50969. /**
  50970. * The weight of the runtime animation
  50971. */
  50972. this._weight = 1.0;
  50973. /**
  50974. * The ratio offset of the runtime animation
  50975. */
  50976. this._ratioOffset = 0;
  50977. /**
  50978. * The previous delay of the runtime animation
  50979. */
  50980. this._previousDelay = 0;
  50981. /**
  50982. * The previous ratio of the runtime animation
  50983. */
  50984. this._previousRatio = 0;
  50985. this._animation = animation;
  50986. this._target = target;
  50987. this._scene = scene;
  50988. this._host = host;
  50989. animation._runtimeAnimations.push(this);
  50990. // Cloning events locally
  50991. var events = animation.getEvents();
  50992. if (events && events.length > 0) {
  50993. events.forEach(function (e) {
  50994. _this._events.push(e._clone());
  50995. });
  50996. }
  50997. }
  50998. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  50999. /**
  51000. * Gets the current frame of the runtime animation
  51001. */
  51002. get: function () {
  51003. return this._currentFrame;
  51004. },
  51005. enumerable: true,
  51006. configurable: true
  51007. });
  51008. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  51009. /**
  51010. * Gets the weight of the runtime animation
  51011. */
  51012. get: function () {
  51013. return this._weight;
  51014. },
  51015. enumerable: true,
  51016. configurable: true
  51017. });
  51018. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  51019. /**
  51020. * Gets the current value of the runtime animation
  51021. */
  51022. get: function () {
  51023. return this._currentValue;
  51024. },
  51025. enumerable: true,
  51026. configurable: true
  51027. });
  51028. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  51029. /**
  51030. * Gets the target path of the runtime animation
  51031. */
  51032. get: function () {
  51033. return this._targetPath;
  51034. },
  51035. enumerable: true,
  51036. configurable: true
  51037. });
  51038. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  51039. /**
  51040. * Gets the actual target of the runtime animation
  51041. */
  51042. get: function () {
  51043. return this._activeTarget;
  51044. },
  51045. enumerable: true,
  51046. configurable: true
  51047. });
  51048. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  51049. /**
  51050. * Gets the animation from the runtime animation
  51051. */
  51052. get: function () {
  51053. return this._animation;
  51054. },
  51055. enumerable: true,
  51056. configurable: true
  51057. });
  51058. /**
  51059. * Resets the runtime animation to the beginning
  51060. * @param restoreOriginal defines whether to restore the target property to the original value
  51061. */
  51062. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  51063. if (restoreOriginal === void 0) { restoreOriginal = false; }
  51064. if (restoreOriginal) {
  51065. if (this._target instanceof Array) {
  51066. var index = 0;
  51067. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  51068. var target = _a[_i];
  51069. if (this._originalValue[index] !== undefined) {
  51070. this._setValue(target, this._originalValue[index], -1);
  51071. }
  51072. index++;
  51073. }
  51074. }
  51075. else {
  51076. if (this._originalValue[0] !== undefined) {
  51077. this._setValue(this._target, this._originalValue[0], -1);
  51078. }
  51079. }
  51080. }
  51081. this._offsetsCache = {};
  51082. this._highLimitsCache = {};
  51083. this._currentFrame = 0;
  51084. this._blendingFactor = 0;
  51085. this._originalValue = new Array();
  51086. // Events
  51087. for (var index = 0; index < this._events.length; index++) {
  51088. this._events[index].isDone = false;
  51089. }
  51090. };
  51091. /**
  51092. * Specifies if the runtime animation is stopped
  51093. * @returns Boolean specifying if the runtime animation is stopped
  51094. */
  51095. RuntimeAnimation.prototype.isStopped = function () {
  51096. return this._stopped;
  51097. };
  51098. /**
  51099. * Disposes of the runtime animation
  51100. */
  51101. RuntimeAnimation.prototype.dispose = function () {
  51102. var index = this._animation.runtimeAnimations.indexOf(this);
  51103. if (index > -1) {
  51104. this._animation.runtimeAnimations.splice(index, 1);
  51105. }
  51106. };
  51107. /**
  51108. * Interpolates the animation from the current frame
  51109. * @param currentFrame The frame to interpolate the animation to
  51110. * @param repeatCount The number of times that the animation should loop
  51111. * @param loopMode The type of looping mode to use
  51112. * @param offsetValue Animation offset value
  51113. * @param highLimitValue The high limit value
  51114. * @returns The interpolated value
  51115. */
  51116. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  51117. this._currentFrame = currentFrame;
  51118. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  51119. this._workValue = BABYLON.Matrix.Zero();
  51120. }
  51121. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  51122. };
  51123. /**
  51124. * Apply the interpolated value to the target
  51125. * @param currentValue defines the value computed by the animation
  51126. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  51127. */
  51128. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  51129. if (weight === void 0) { weight = 1.0; }
  51130. if (this._target instanceof Array) {
  51131. var index = 0;
  51132. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  51133. var target = _a[_i];
  51134. this._setValue(target, currentValue, weight, index);
  51135. index++;
  51136. }
  51137. }
  51138. else {
  51139. this._setValue(this._target, currentValue, weight);
  51140. }
  51141. };
  51142. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  51143. if (targetIndex === void 0) { targetIndex = 0; }
  51144. // Set value
  51145. var path;
  51146. var destination;
  51147. var targetPropertyPath = this._animation.targetPropertyPath;
  51148. if (targetPropertyPath.length > 1) {
  51149. var property = target[targetPropertyPath[0]];
  51150. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  51151. property = property[targetPropertyPath[index]];
  51152. }
  51153. path = targetPropertyPath[targetPropertyPath.length - 1];
  51154. destination = property;
  51155. }
  51156. else {
  51157. path = targetPropertyPath[0];
  51158. destination = target;
  51159. }
  51160. this._targetPath = path;
  51161. this._activeTarget = destination;
  51162. this._weight = weight;
  51163. if (this._originalValue[targetIndex] === undefined) {
  51164. var originalValue = void 0;
  51165. if (destination.getRestPose && path === "_matrix") { // For bones
  51166. originalValue = destination.getRestPose();
  51167. }
  51168. else {
  51169. originalValue = destination[path];
  51170. }
  51171. if (originalValue && originalValue.clone) {
  51172. this._originalValue[targetIndex] = originalValue.clone();
  51173. }
  51174. else {
  51175. this._originalValue[targetIndex] = originalValue;
  51176. }
  51177. }
  51178. // Blending
  51179. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  51180. if (enableBlending && this._blendingFactor <= 1.0) {
  51181. if (!this._originalBlendValue) {
  51182. var originalValue = destination[path];
  51183. if (originalValue.clone) {
  51184. this._originalBlendValue = originalValue.clone();
  51185. }
  51186. else {
  51187. this._originalBlendValue = originalValue;
  51188. }
  51189. }
  51190. if (this._originalBlendValue.m) { // Matrix
  51191. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  51192. if (this._currentValue) {
  51193. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51194. }
  51195. else {
  51196. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51197. }
  51198. }
  51199. else {
  51200. if (this._currentValue) {
  51201. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51202. }
  51203. else {
  51204. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51205. }
  51206. }
  51207. }
  51208. else {
  51209. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51210. }
  51211. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  51212. this._blendingFactor += blendingSpeed;
  51213. }
  51214. else {
  51215. this._currentValue = currentValue;
  51216. }
  51217. if (weight !== -1.0) {
  51218. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  51219. }
  51220. else {
  51221. destination[path] = this._currentValue;
  51222. }
  51223. if (target.markAsDirty) {
  51224. target.markAsDirty(this._animation.targetProperty);
  51225. }
  51226. };
  51227. /**
  51228. * Gets the loop pmode of the runtime animation
  51229. * @returns Loop Mode
  51230. */
  51231. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  51232. if (this._target && this._target.animationPropertiesOverride) {
  51233. return this._target.animationPropertiesOverride.loopMode;
  51234. }
  51235. return this._animation.loopMode;
  51236. };
  51237. /**
  51238. * Move the current animation to a given frame
  51239. * @param frame defines the frame to move to
  51240. */
  51241. RuntimeAnimation.prototype.goToFrame = function (frame) {
  51242. var keys = this._animation.getKeys();
  51243. if (frame < keys[0].frame) {
  51244. frame = keys[0].frame;
  51245. }
  51246. else if (frame > keys[keys.length - 1].frame) {
  51247. frame = keys[keys.length - 1].frame;
  51248. }
  51249. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  51250. this.setValue(currentValue, -1);
  51251. };
  51252. /**
  51253. * @hidden Internal use only
  51254. */
  51255. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  51256. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  51257. this._ratioOffset = this._previousRatio - newRatio;
  51258. };
  51259. /**
  51260. * Execute the current animation
  51261. * @param delay defines the delay to add to the current frame
  51262. * @param from defines the lower bound of the animation range
  51263. * @param to defines the upper bound of the animation range
  51264. * @param loop defines if the current animation must loop
  51265. * @param speedRatio defines the current speed ratio
  51266. * @param weight defines the weight of the animation (default is -1 so no weight)
  51267. * @returns a boolean indicating if the animation is running
  51268. */
  51269. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  51270. if (weight === void 0) { weight = -1.0; }
  51271. var targetPropertyPath = this._animation.targetPropertyPath;
  51272. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  51273. this._stopped = true;
  51274. return false;
  51275. }
  51276. var returnValue = true;
  51277. var keys = this._animation.getKeys();
  51278. // Adding a start key at frame 0 if missing
  51279. if (keys[0].frame !== 0) {
  51280. var newKey = { frame: 0, value: keys[0].value };
  51281. keys.splice(0, 0, newKey);
  51282. }
  51283. // Adding a duplicate key when there is only one key at frame zero
  51284. else if (keys.length === 1) {
  51285. var newKey = { frame: 0.001, value: keys[0].value };
  51286. keys.push(newKey);
  51287. }
  51288. // Check limits
  51289. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  51290. from = keys[0].frame;
  51291. }
  51292. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  51293. to = keys[keys.length - 1].frame;
  51294. }
  51295. //to and from cannot be the same key
  51296. if (from === to) {
  51297. if (from > keys[0].frame) {
  51298. from--;
  51299. }
  51300. else if (to < keys[keys.length - 1].frame) {
  51301. to++;
  51302. }
  51303. }
  51304. // Compute ratio
  51305. var range = to - from;
  51306. var offsetValue;
  51307. // ratio represents the frame delta between from and to
  51308. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  51309. var highLimitValue = 0;
  51310. this._previousDelay = delay;
  51311. this._previousRatio = ratio;
  51312. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  51313. returnValue = false;
  51314. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  51315. }
  51316. else {
  51317. // Get max value if required
  51318. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  51319. var keyOffset = to.toString() + from.toString();
  51320. if (!this._offsetsCache[keyOffset]) {
  51321. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51322. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51323. switch (this._animation.dataType) {
  51324. // Float
  51325. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51326. this._offsetsCache[keyOffset] = toValue - fromValue;
  51327. break;
  51328. // Quaternion
  51329. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51330. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51331. break;
  51332. // Vector3
  51333. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51334. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51335. // Vector2
  51336. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51337. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51338. // Size
  51339. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51340. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51341. // Color3
  51342. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51343. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51344. default:
  51345. break;
  51346. }
  51347. this._highLimitsCache[keyOffset] = toValue;
  51348. }
  51349. highLimitValue = this._highLimitsCache[keyOffset];
  51350. offsetValue = this._offsetsCache[keyOffset];
  51351. }
  51352. }
  51353. if (offsetValue === undefined) {
  51354. switch (this._animation.dataType) {
  51355. // Float
  51356. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51357. offsetValue = 0;
  51358. break;
  51359. // Quaternion
  51360. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51361. offsetValue = _staticOffsetValueQuaternion;
  51362. break;
  51363. // Vector3
  51364. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51365. offsetValue = _staticOffsetValueVector3;
  51366. break;
  51367. // Vector2
  51368. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51369. offsetValue = _staticOffsetValueVector2;
  51370. break;
  51371. // Size
  51372. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51373. offsetValue = _staticOffsetValueSize;
  51374. break;
  51375. // Color3
  51376. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51377. offsetValue = _staticOffsetValueColor3;
  51378. }
  51379. }
  51380. // Compute value
  51381. var repeatCount = (ratio / range) >> 0;
  51382. var currentFrame = returnValue ? from + ratio % range : to;
  51383. // Need to normalize?
  51384. if (this._host && this._host.syncRoot) {
  51385. var syncRoot = this._host.syncRoot;
  51386. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  51387. currentFrame = from + (to - from) * hostNormalizedFrame;
  51388. }
  51389. // Reset events if looping
  51390. var events = this._events;
  51391. if (range > 0 && this.currentFrame > currentFrame ||
  51392. range < 0 && this.currentFrame < currentFrame) {
  51393. // Need to reset animation events
  51394. for (var index = 0; index < events.length; index++) {
  51395. if (!events[index].onlyOnce) {
  51396. // reset event, the animation is looping
  51397. events[index].isDone = false;
  51398. }
  51399. }
  51400. }
  51401. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  51402. // Set value
  51403. this.setValue(currentValue, weight);
  51404. // Check events
  51405. for (var index = 0; index < events.length; index++) {
  51406. // Make sure current frame has passed event frame and that event frame is within the current range
  51407. // Also, handle both forward and reverse animations
  51408. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  51409. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  51410. var event = events[index];
  51411. if (!event.isDone) {
  51412. // If event should be done only once, remove it.
  51413. if (event.onlyOnce) {
  51414. events.splice(index, 1);
  51415. index--;
  51416. }
  51417. event.isDone = true;
  51418. event.action(currentFrame);
  51419. } // Don't do anything if the event has already be done.
  51420. }
  51421. }
  51422. if (!returnValue) {
  51423. this._stopped = true;
  51424. }
  51425. return returnValue;
  51426. };
  51427. return RuntimeAnimation;
  51428. }());
  51429. BABYLON.RuntimeAnimation = RuntimeAnimation;
  51430. })(BABYLON || (BABYLON = {}));
  51431. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  51432. var BABYLON;
  51433. (function (BABYLON) {
  51434. /**
  51435. * Class used to store an actual running animation
  51436. */
  51437. var Animatable = /** @class */ (function () {
  51438. /**
  51439. * Creates a new Animatable
  51440. * @param scene defines the hosting scene
  51441. * @param target defines the target object
  51442. * @param fromFrame defines the starting frame number (default is 0)
  51443. * @param toFrame defines the ending frame number (default is 100)
  51444. * @param loopAnimation defines if the animation must loop (default is false)
  51445. * @param speedRatio defines the factor to apply to animation speed (default is 1)
  51446. * @param onAnimationEnd defines a callback to call when animation ends if it is not looping
  51447. * @param animations defines a group of animation to add to the new Animatable
  51448. */
  51449. function Animatable(scene,
  51450. /** defines the target object */
  51451. target,
  51452. /** defines the starting frame number (default is 0) */
  51453. fromFrame,
  51454. /** defines the ending frame number (default is 100) */
  51455. toFrame,
  51456. /** defines if the animation must loop (default is false) */
  51457. loopAnimation, speedRatio,
  51458. /** defines a callback to call when animation ends if it is not looping */
  51459. onAnimationEnd, animations) {
  51460. if (fromFrame === void 0) { fromFrame = 0; }
  51461. if (toFrame === void 0) { toFrame = 100; }
  51462. if (loopAnimation === void 0) { loopAnimation = false; }
  51463. if (speedRatio === void 0) { speedRatio = 1.0; }
  51464. this.target = target;
  51465. this.fromFrame = fromFrame;
  51466. this.toFrame = toFrame;
  51467. this.loopAnimation = loopAnimation;
  51468. this.onAnimationEnd = onAnimationEnd;
  51469. this._localDelayOffset = null;
  51470. this._pausedDelay = null;
  51471. this._runtimeAnimations = new Array();
  51472. this._paused = false;
  51473. this._speedRatio = 1;
  51474. this._weight = -1.0;
  51475. /**
  51476. * Gets or sets a boolean indicating if the animatable must be disposed and removed at the end of the animation.
  51477. * This will only apply for non looping animation (default is true)
  51478. */
  51479. this.disposeOnEnd = true;
  51480. /**
  51481. * Gets a boolean indicating if the animation has started
  51482. */
  51483. this.animationStarted = false;
  51484. /**
  51485. * Observer raised when the animation ends
  51486. */
  51487. this.onAnimationEndObservable = new BABYLON.Observable();
  51488. this._scene = scene;
  51489. if (animations) {
  51490. this.appendAnimations(target, animations);
  51491. }
  51492. this._speedRatio = speedRatio;
  51493. scene._activeAnimatables.push(this);
  51494. }
  51495. Object.defineProperty(Animatable.prototype, "syncRoot", {
  51496. /**
  51497. * Gets the root Animatable used to synchronize and normalize animations
  51498. */
  51499. get: function () {
  51500. return this._syncRoot;
  51501. },
  51502. enumerable: true,
  51503. configurable: true
  51504. });
  51505. Object.defineProperty(Animatable.prototype, "masterFrame", {
  51506. /**
  51507. * Gets the current frame of the first RuntimeAnimation
  51508. * Used to synchronize Animatables
  51509. */
  51510. get: function () {
  51511. if (this._runtimeAnimations.length === 0) {
  51512. return 0;
  51513. }
  51514. return this._runtimeAnimations[0].currentFrame;
  51515. },
  51516. enumerable: true,
  51517. configurable: true
  51518. });
  51519. Object.defineProperty(Animatable.prototype, "weight", {
  51520. /**
  51521. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  51522. */
  51523. get: function () {
  51524. return this._weight;
  51525. },
  51526. set: function (value) {
  51527. if (value === -1) { // -1 is ok and means no weight
  51528. this._weight = -1;
  51529. return;
  51530. }
  51531. // Else weight must be in [0, 1] range
  51532. this._weight = Math.min(Math.max(value, 0), 1.0);
  51533. },
  51534. enumerable: true,
  51535. configurable: true
  51536. });
  51537. Object.defineProperty(Animatable.prototype, "speedRatio", {
  51538. /**
  51539. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  51540. */
  51541. get: function () {
  51542. return this._speedRatio;
  51543. },
  51544. set: function (value) {
  51545. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  51546. var animation = this._runtimeAnimations[index];
  51547. animation._prepareForSpeedRatioChange(value);
  51548. }
  51549. this._speedRatio = value;
  51550. },
  51551. enumerable: true,
  51552. configurable: true
  51553. });
  51554. // Methods
  51555. /**
  51556. * Synchronize and normalize current Animatable with a source Animatable
  51557. * This is useful when using animation weights and when animations are not of the same length
  51558. * @param root defines the root Animatable to synchronize with
  51559. * @returns the current Animatable
  51560. */
  51561. Animatable.prototype.syncWith = function (root) {
  51562. this._syncRoot = root;
  51563. if (root) {
  51564. // Make sure this animatable will animate after the root
  51565. var index = this._scene._activeAnimatables.indexOf(this);
  51566. if (index > -1) {
  51567. this._scene._activeAnimatables.splice(index, 1);
  51568. this._scene._activeAnimatables.push(this);
  51569. }
  51570. }
  51571. return this;
  51572. };
  51573. /**
  51574. * Gets the list of runtime animations
  51575. * @returns an array of RuntimeAnimation
  51576. */
  51577. Animatable.prototype.getAnimations = function () {
  51578. return this._runtimeAnimations;
  51579. };
  51580. /**
  51581. * Adds more animations to the current animatable
  51582. * @param target defines the target of the animations
  51583. * @param animations defines the new animations to add
  51584. */
  51585. Animatable.prototype.appendAnimations = function (target, animations) {
  51586. for (var index = 0; index < animations.length; index++) {
  51587. var animation = animations[index];
  51588. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  51589. }
  51590. };
  51591. /**
  51592. * Gets the source animation for a specific property
  51593. * @param property defines the propertyu to look for
  51594. * @returns null or the source animation for the given property
  51595. */
  51596. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  51597. var runtimeAnimations = this._runtimeAnimations;
  51598. for (var index = 0; index < runtimeAnimations.length; index++) {
  51599. if (runtimeAnimations[index].animation.targetProperty === property) {
  51600. return runtimeAnimations[index].animation;
  51601. }
  51602. }
  51603. return null;
  51604. };
  51605. /**
  51606. * Gets the runtime animation for a specific property
  51607. * @param property defines the propertyu to look for
  51608. * @returns null or the runtime animation for the given property
  51609. */
  51610. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  51611. var runtimeAnimations = this._runtimeAnimations;
  51612. for (var index = 0; index < runtimeAnimations.length; index++) {
  51613. if (runtimeAnimations[index].animation.targetProperty === property) {
  51614. return runtimeAnimations[index];
  51615. }
  51616. }
  51617. return null;
  51618. };
  51619. /**
  51620. * Resets the animatable to its original state
  51621. */
  51622. Animatable.prototype.reset = function () {
  51623. var runtimeAnimations = this._runtimeAnimations;
  51624. for (var index = 0; index < runtimeAnimations.length; index++) {
  51625. runtimeAnimations[index].reset(true);
  51626. }
  51627. this._localDelayOffset = null;
  51628. this._pausedDelay = null;
  51629. };
  51630. /**
  51631. * Allows the animatable to blend with current running animations
  51632. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  51633. * @param blendingSpeed defines the blending speed to use
  51634. */
  51635. Animatable.prototype.enableBlending = function (blendingSpeed) {
  51636. var runtimeAnimations = this._runtimeAnimations;
  51637. for (var index = 0; index < runtimeAnimations.length; index++) {
  51638. runtimeAnimations[index].animation.enableBlending = true;
  51639. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  51640. }
  51641. };
  51642. /**
  51643. * Disable animation blending
  51644. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  51645. */
  51646. Animatable.prototype.disableBlending = function () {
  51647. var runtimeAnimations = this._runtimeAnimations;
  51648. for (var index = 0; index < runtimeAnimations.length; index++) {
  51649. runtimeAnimations[index].animation.enableBlending = false;
  51650. }
  51651. };
  51652. /**
  51653. * Jump directly to a given frame
  51654. * @param frame defines the frame to jump to
  51655. */
  51656. Animatable.prototype.goToFrame = function (frame) {
  51657. var runtimeAnimations = this._runtimeAnimations;
  51658. if (runtimeAnimations[0]) {
  51659. var fps = runtimeAnimations[0].animation.framePerSecond;
  51660. var currentFrame = runtimeAnimations[0].currentFrame;
  51661. var adjustTime = frame - currentFrame;
  51662. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  51663. if (this._localDelayOffset === null) {
  51664. this._localDelayOffset = 0;
  51665. }
  51666. this._localDelayOffset -= delay;
  51667. }
  51668. for (var index = 0; index < runtimeAnimations.length; index++) {
  51669. runtimeAnimations[index].goToFrame(frame);
  51670. }
  51671. };
  51672. /**
  51673. * Pause the animation
  51674. */
  51675. Animatable.prototype.pause = function () {
  51676. if (this._paused) {
  51677. return;
  51678. }
  51679. this._paused = true;
  51680. };
  51681. /**
  51682. * Restart the animation
  51683. */
  51684. Animatable.prototype.restart = function () {
  51685. this._paused = false;
  51686. };
  51687. Animatable.prototype._raiseOnAnimationEnd = function () {
  51688. if (this.onAnimationEnd) {
  51689. this.onAnimationEnd();
  51690. }
  51691. this.onAnimationEndObservable.notifyObservers(this);
  51692. };
  51693. /**
  51694. * Stop and delete the current animation
  51695. * @param animationName defines a string used to only stop some of the runtime animations instead of all
  51696. * @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)
  51697. */
  51698. Animatable.prototype.stop = function (animationName, targetMask) {
  51699. if (animationName || targetMask) {
  51700. var idx = this._scene._activeAnimatables.indexOf(this);
  51701. if (idx > -1) {
  51702. var runtimeAnimations = this._runtimeAnimations;
  51703. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  51704. var runtimeAnimation = runtimeAnimations[index];
  51705. if (animationName && runtimeAnimation.animation.name != animationName) {
  51706. continue;
  51707. }
  51708. if (targetMask && !targetMask(runtimeAnimation.target)) {
  51709. continue;
  51710. }
  51711. runtimeAnimation.dispose();
  51712. runtimeAnimations.splice(index, 1);
  51713. }
  51714. if (runtimeAnimations.length == 0) {
  51715. this._scene._activeAnimatables.splice(idx, 1);
  51716. this._raiseOnAnimationEnd();
  51717. }
  51718. }
  51719. }
  51720. else {
  51721. var index = this._scene._activeAnimatables.indexOf(this);
  51722. if (index > -1) {
  51723. this._scene._activeAnimatables.splice(index, 1);
  51724. var runtimeAnimations = this._runtimeAnimations;
  51725. for (var index = 0; index < runtimeAnimations.length; index++) {
  51726. runtimeAnimations[index].dispose();
  51727. }
  51728. this._raiseOnAnimationEnd();
  51729. }
  51730. }
  51731. };
  51732. /**
  51733. * Wait asynchronously for the animation to end
  51734. * @returns a promise which will be fullfilled when the animation ends
  51735. */
  51736. Animatable.prototype.waitAsync = function () {
  51737. var _this = this;
  51738. return new Promise(function (resolve, reject) {
  51739. _this.onAnimationEndObservable.add(function () {
  51740. resolve(_this);
  51741. }, undefined, undefined, _this, true);
  51742. });
  51743. };
  51744. /** @hidden */
  51745. Animatable.prototype._animate = function (delay) {
  51746. if (this._paused) {
  51747. this.animationStarted = false;
  51748. if (this._pausedDelay === null) {
  51749. this._pausedDelay = delay;
  51750. }
  51751. return true;
  51752. }
  51753. if (this._localDelayOffset === null) {
  51754. this._localDelayOffset = delay;
  51755. this._pausedDelay = null;
  51756. }
  51757. else if (this._pausedDelay !== null) {
  51758. this._localDelayOffset += delay - this._pausedDelay;
  51759. this._pausedDelay = null;
  51760. }
  51761. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  51762. return true;
  51763. }
  51764. // Animating
  51765. var running = false;
  51766. var runtimeAnimations = this._runtimeAnimations;
  51767. var index;
  51768. for (index = 0; index < runtimeAnimations.length; index++) {
  51769. var animation = runtimeAnimations[index];
  51770. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  51771. running = running || isRunning;
  51772. }
  51773. this.animationStarted = running;
  51774. if (!running) {
  51775. if (this.disposeOnEnd) {
  51776. // Remove from active animatables
  51777. index = this._scene._activeAnimatables.indexOf(this);
  51778. this._scene._activeAnimatables.splice(index, 1);
  51779. // Dispose all runtime animations
  51780. for (index = 0; index < runtimeAnimations.length; index++) {
  51781. runtimeAnimations[index].dispose();
  51782. }
  51783. }
  51784. this._raiseOnAnimationEnd();
  51785. if (this.disposeOnEnd) {
  51786. this.onAnimationEnd = null;
  51787. this.onAnimationEndObservable.clear();
  51788. }
  51789. }
  51790. return running;
  51791. };
  51792. return Animatable;
  51793. }());
  51794. BABYLON.Animatable = Animatable;
  51795. })(BABYLON || (BABYLON = {}));
  51796. //# sourceMappingURL=babylon.animatable.js.map
  51797. var BABYLON;
  51798. (function (BABYLON) {
  51799. var EasingFunction = /** @class */ (function () {
  51800. function EasingFunction() {
  51801. // Properties
  51802. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  51803. }
  51804. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  51805. get: function () {
  51806. return EasingFunction._EASINGMODE_EASEIN;
  51807. },
  51808. enumerable: true,
  51809. configurable: true
  51810. });
  51811. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  51812. get: function () {
  51813. return EasingFunction._EASINGMODE_EASEOUT;
  51814. },
  51815. enumerable: true,
  51816. configurable: true
  51817. });
  51818. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  51819. get: function () {
  51820. return EasingFunction._EASINGMODE_EASEINOUT;
  51821. },
  51822. enumerable: true,
  51823. configurable: true
  51824. });
  51825. EasingFunction.prototype.setEasingMode = function (easingMode) {
  51826. var n = Math.min(Math.max(easingMode, 0), 2);
  51827. this._easingMode = n;
  51828. };
  51829. EasingFunction.prototype.getEasingMode = function () {
  51830. return this._easingMode;
  51831. };
  51832. EasingFunction.prototype.easeInCore = function (gradient) {
  51833. throw new Error('You must implement this method');
  51834. };
  51835. EasingFunction.prototype.ease = function (gradient) {
  51836. switch (this._easingMode) {
  51837. case EasingFunction.EASINGMODE_EASEIN:
  51838. return this.easeInCore(gradient);
  51839. case EasingFunction.EASINGMODE_EASEOUT:
  51840. return (1 - this.easeInCore(1 - gradient));
  51841. }
  51842. if (gradient >= 0.5) {
  51843. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  51844. }
  51845. return (this.easeInCore(gradient * 2) * 0.5);
  51846. };
  51847. //Statics
  51848. EasingFunction._EASINGMODE_EASEIN = 0;
  51849. EasingFunction._EASINGMODE_EASEOUT = 1;
  51850. EasingFunction._EASINGMODE_EASEINOUT = 2;
  51851. return EasingFunction;
  51852. }());
  51853. BABYLON.EasingFunction = EasingFunction;
  51854. var CircleEase = /** @class */ (function (_super) {
  51855. __extends(CircleEase, _super);
  51856. function CircleEase() {
  51857. return _super !== null && _super.apply(this, arguments) || this;
  51858. }
  51859. CircleEase.prototype.easeInCore = function (gradient) {
  51860. gradient = Math.max(0, Math.min(1, gradient));
  51861. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  51862. };
  51863. return CircleEase;
  51864. }(EasingFunction));
  51865. BABYLON.CircleEase = CircleEase;
  51866. var BackEase = /** @class */ (function (_super) {
  51867. __extends(BackEase, _super);
  51868. function BackEase(amplitude) {
  51869. if (amplitude === void 0) { amplitude = 1; }
  51870. var _this = _super.call(this) || this;
  51871. _this.amplitude = amplitude;
  51872. return _this;
  51873. }
  51874. BackEase.prototype.easeInCore = function (gradient) {
  51875. var num = Math.max(0, this.amplitude);
  51876. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  51877. };
  51878. return BackEase;
  51879. }(EasingFunction));
  51880. BABYLON.BackEase = BackEase;
  51881. var BounceEase = /** @class */ (function (_super) {
  51882. __extends(BounceEase, _super);
  51883. function BounceEase(bounces, bounciness) {
  51884. if (bounces === void 0) { bounces = 3; }
  51885. if (bounciness === void 0) { bounciness = 2; }
  51886. var _this = _super.call(this) || this;
  51887. _this.bounces = bounces;
  51888. _this.bounciness = bounciness;
  51889. return _this;
  51890. }
  51891. BounceEase.prototype.easeInCore = function (gradient) {
  51892. var y = Math.max(0.0, this.bounces);
  51893. var bounciness = this.bounciness;
  51894. if (bounciness <= 1.0) {
  51895. bounciness = 1.001;
  51896. }
  51897. var num9 = Math.pow(bounciness, y);
  51898. var num5 = 1.0 - bounciness;
  51899. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  51900. var num15 = gradient * num4;
  51901. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  51902. var num3 = Math.floor(num65);
  51903. var num13 = num3 + 1.0;
  51904. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  51905. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  51906. var num7 = (num8 + num12) * 0.5;
  51907. var num6 = gradient - num7;
  51908. var num2 = num7 - num8;
  51909. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  51910. };
  51911. return BounceEase;
  51912. }(EasingFunction));
  51913. BABYLON.BounceEase = BounceEase;
  51914. var CubicEase = /** @class */ (function (_super) {
  51915. __extends(CubicEase, _super);
  51916. function CubicEase() {
  51917. return _super !== null && _super.apply(this, arguments) || this;
  51918. }
  51919. CubicEase.prototype.easeInCore = function (gradient) {
  51920. return (gradient * gradient * gradient);
  51921. };
  51922. return CubicEase;
  51923. }(EasingFunction));
  51924. BABYLON.CubicEase = CubicEase;
  51925. var ElasticEase = /** @class */ (function (_super) {
  51926. __extends(ElasticEase, _super);
  51927. function ElasticEase(oscillations, springiness) {
  51928. if (oscillations === void 0) { oscillations = 3; }
  51929. if (springiness === void 0) { springiness = 3; }
  51930. var _this = _super.call(this) || this;
  51931. _this.oscillations = oscillations;
  51932. _this.springiness = springiness;
  51933. return _this;
  51934. }
  51935. ElasticEase.prototype.easeInCore = function (gradient) {
  51936. var num2;
  51937. var num3 = Math.max(0.0, this.oscillations);
  51938. var num = Math.max(0.0, this.springiness);
  51939. if (num == 0) {
  51940. num2 = gradient;
  51941. }
  51942. else {
  51943. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  51944. }
  51945. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  51946. };
  51947. return ElasticEase;
  51948. }(EasingFunction));
  51949. BABYLON.ElasticEase = ElasticEase;
  51950. var ExponentialEase = /** @class */ (function (_super) {
  51951. __extends(ExponentialEase, _super);
  51952. function ExponentialEase(exponent) {
  51953. if (exponent === void 0) { exponent = 2; }
  51954. var _this = _super.call(this) || this;
  51955. _this.exponent = exponent;
  51956. return _this;
  51957. }
  51958. ExponentialEase.prototype.easeInCore = function (gradient) {
  51959. if (this.exponent <= 0) {
  51960. return gradient;
  51961. }
  51962. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  51963. };
  51964. return ExponentialEase;
  51965. }(EasingFunction));
  51966. BABYLON.ExponentialEase = ExponentialEase;
  51967. var PowerEase = /** @class */ (function (_super) {
  51968. __extends(PowerEase, _super);
  51969. function PowerEase(power) {
  51970. if (power === void 0) { power = 2; }
  51971. var _this = _super.call(this) || this;
  51972. _this.power = power;
  51973. return _this;
  51974. }
  51975. PowerEase.prototype.easeInCore = function (gradient) {
  51976. var y = Math.max(0.0, this.power);
  51977. return Math.pow(gradient, y);
  51978. };
  51979. return PowerEase;
  51980. }(EasingFunction));
  51981. BABYLON.PowerEase = PowerEase;
  51982. var QuadraticEase = /** @class */ (function (_super) {
  51983. __extends(QuadraticEase, _super);
  51984. function QuadraticEase() {
  51985. return _super !== null && _super.apply(this, arguments) || this;
  51986. }
  51987. QuadraticEase.prototype.easeInCore = function (gradient) {
  51988. return (gradient * gradient);
  51989. };
  51990. return QuadraticEase;
  51991. }(EasingFunction));
  51992. BABYLON.QuadraticEase = QuadraticEase;
  51993. var QuarticEase = /** @class */ (function (_super) {
  51994. __extends(QuarticEase, _super);
  51995. function QuarticEase() {
  51996. return _super !== null && _super.apply(this, arguments) || this;
  51997. }
  51998. QuarticEase.prototype.easeInCore = function (gradient) {
  51999. return (gradient * gradient * gradient * gradient);
  52000. };
  52001. return QuarticEase;
  52002. }(EasingFunction));
  52003. BABYLON.QuarticEase = QuarticEase;
  52004. var QuinticEase = /** @class */ (function (_super) {
  52005. __extends(QuinticEase, _super);
  52006. function QuinticEase() {
  52007. return _super !== null && _super.apply(this, arguments) || this;
  52008. }
  52009. QuinticEase.prototype.easeInCore = function (gradient) {
  52010. return (gradient * gradient * gradient * gradient * gradient);
  52011. };
  52012. return QuinticEase;
  52013. }(EasingFunction));
  52014. BABYLON.QuinticEase = QuinticEase;
  52015. var SineEase = /** @class */ (function (_super) {
  52016. __extends(SineEase, _super);
  52017. function SineEase() {
  52018. return _super !== null && _super.apply(this, arguments) || this;
  52019. }
  52020. SineEase.prototype.easeInCore = function (gradient) {
  52021. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  52022. };
  52023. return SineEase;
  52024. }(EasingFunction));
  52025. BABYLON.SineEase = SineEase;
  52026. var BezierCurveEase = /** @class */ (function (_super) {
  52027. __extends(BezierCurveEase, _super);
  52028. function BezierCurveEase(x1, y1, x2, y2) {
  52029. if (x1 === void 0) { x1 = 0; }
  52030. if (y1 === void 0) { y1 = 0; }
  52031. if (x2 === void 0) { x2 = 1; }
  52032. if (y2 === void 0) { y2 = 1; }
  52033. var _this = _super.call(this) || this;
  52034. _this.x1 = x1;
  52035. _this.y1 = y1;
  52036. _this.x2 = x2;
  52037. _this.y2 = y2;
  52038. return _this;
  52039. }
  52040. BezierCurveEase.prototype.easeInCore = function (gradient) {
  52041. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  52042. };
  52043. return BezierCurveEase;
  52044. }(EasingFunction));
  52045. BABYLON.BezierCurveEase = BezierCurveEase;
  52046. })(BABYLON || (BABYLON = {}));
  52047. //# sourceMappingURL=babylon.easing.js.map
  52048. var BABYLON;
  52049. (function (BABYLON) {
  52050. /**
  52051. * A Condition applied to an Action
  52052. */
  52053. var Condition = /** @class */ (function () {
  52054. /**
  52055. * Creates a new Condition
  52056. * @param actionManager the manager of the action the condition is applied to
  52057. */
  52058. function Condition(actionManager) {
  52059. this._actionManager = actionManager;
  52060. }
  52061. /**
  52062. * Check if the current condition is valid
  52063. * @returns a boolean
  52064. */
  52065. Condition.prototype.isValid = function () {
  52066. return true;
  52067. };
  52068. /**
  52069. * Internal only
  52070. * @hidden
  52071. */
  52072. Condition.prototype._getProperty = function (propertyPath) {
  52073. return this._actionManager._getProperty(propertyPath);
  52074. };
  52075. /**
  52076. * Internal only
  52077. * @hidden
  52078. */
  52079. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  52080. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52081. };
  52082. /**
  52083. * Serialize placeholder for child classes
  52084. * @returns the serialized object
  52085. */
  52086. Condition.prototype.serialize = function () {
  52087. };
  52088. /**
  52089. * Internal only
  52090. * @hidden
  52091. */
  52092. Condition.prototype._serialize = function (serializedCondition) {
  52093. return {
  52094. type: 2,
  52095. children: [],
  52096. name: serializedCondition.name,
  52097. properties: serializedCondition.properties
  52098. };
  52099. };
  52100. return Condition;
  52101. }());
  52102. BABYLON.Condition = Condition;
  52103. /**
  52104. * Defines specific conditional operators as extensions of Condition
  52105. */
  52106. var ValueCondition = /** @class */ (function (_super) {
  52107. __extends(ValueCondition, _super);
  52108. /**
  52109. * Creates a new ValueCondition
  52110. * @param actionManager manager for the action the condition applies to
  52111. * @param target for the action
  52112. * @param propertyPath path to specify the property of the target the conditional operator uses
  52113. * @param value the value compared by the conditional operator against the current value of the property
  52114. * @param operator the conditional operator, default ValueCondition.IsEqual
  52115. */
  52116. function ValueCondition(actionManager, target,
  52117. /** path to specify the property of the target the conditional operator uses */
  52118. propertyPath,
  52119. /** the value compared by the conditional operator against the current value of the property */
  52120. value,
  52121. /** the conditional operator, default ValueCondition.IsEqual */
  52122. operator) {
  52123. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  52124. var _this = _super.call(this, actionManager) || this;
  52125. _this.propertyPath = propertyPath;
  52126. _this.value = value;
  52127. _this.operator = operator;
  52128. _this._target = target;
  52129. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  52130. _this._property = _this._getProperty(_this.propertyPath);
  52131. return _this;
  52132. }
  52133. Object.defineProperty(ValueCondition, "IsEqual", {
  52134. /**
  52135. * returns the number for IsEqual
  52136. */
  52137. get: function () {
  52138. return ValueCondition._IsEqual;
  52139. },
  52140. enumerable: true,
  52141. configurable: true
  52142. });
  52143. Object.defineProperty(ValueCondition, "IsDifferent", {
  52144. /**
  52145. * Returns the number for IsDifferent
  52146. */
  52147. get: function () {
  52148. return ValueCondition._IsDifferent;
  52149. },
  52150. enumerable: true,
  52151. configurable: true
  52152. });
  52153. Object.defineProperty(ValueCondition, "IsGreater", {
  52154. /**
  52155. * Returns the number for IsGreater
  52156. */
  52157. get: function () {
  52158. return ValueCondition._IsGreater;
  52159. },
  52160. enumerable: true,
  52161. configurable: true
  52162. });
  52163. Object.defineProperty(ValueCondition, "IsLesser", {
  52164. /**
  52165. * Returns the number for IsLesser
  52166. */
  52167. get: function () {
  52168. return ValueCondition._IsLesser;
  52169. },
  52170. enumerable: true,
  52171. configurable: true
  52172. });
  52173. /**
  52174. * Compares the given value with the property value for the specified conditional operator
  52175. * @returns the result of the comparison
  52176. */
  52177. ValueCondition.prototype.isValid = function () {
  52178. switch (this.operator) {
  52179. case ValueCondition.IsGreater:
  52180. return this._effectiveTarget[this._property] > this.value;
  52181. case ValueCondition.IsLesser:
  52182. return this._effectiveTarget[this._property] < this.value;
  52183. case ValueCondition.IsEqual:
  52184. case ValueCondition.IsDifferent:
  52185. var check;
  52186. if (this.value.equals) {
  52187. check = this.value.equals(this._effectiveTarget[this._property]);
  52188. }
  52189. else {
  52190. check = this.value === this._effectiveTarget[this._property];
  52191. }
  52192. return this.operator === ValueCondition.IsEqual ? check : !check;
  52193. }
  52194. return false;
  52195. };
  52196. /**
  52197. * Serialize the ValueCondition into a JSON compatible object
  52198. * @returns serialization object
  52199. */
  52200. ValueCondition.prototype.serialize = function () {
  52201. return this._serialize({
  52202. name: "ValueCondition",
  52203. properties: [
  52204. BABYLON.Action._GetTargetProperty(this._target),
  52205. { name: "propertyPath", value: this.propertyPath },
  52206. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  52207. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  52208. ]
  52209. });
  52210. };
  52211. /**
  52212. * Gets the name of the conditional operator for the ValueCondition
  52213. * @param operator the conditional operator
  52214. * @returns the name
  52215. */
  52216. ValueCondition.GetOperatorName = function (operator) {
  52217. switch (operator) {
  52218. case ValueCondition._IsEqual: return "IsEqual";
  52219. case ValueCondition._IsDifferent: return "IsDifferent";
  52220. case ValueCondition._IsGreater: return "IsGreater";
  52221. case ValueCondition._IsLesser: return "IsLesser";
  52222. default: return "";
  52223. }
  52224. };
  52225. /**
  52226. * Internal only
  52227. * @hidden
  52228. */
  52229. ValueCondition._IsEqual = 0;
  52230. /**
  52231. * Internal only
  52232. * @hidden
  52233. */
  52234. ValueCondition._IsDifferent = 1;
  52235. /**
  52236. * Internal only
  52237. * @hidden
  52238. */
  52239. ValueCondition._IsGreater = 2;
  52240. /**
  52241. * Internal only
  52242. * @hidden
  52243. */
  52244. ValueCondition._IsLesser = 3;
  52245. return ValueCondition;
  52246. }(Condition));
  52247. BABYLON.ValueCondition = ValueCondition;
  52248. /**
  52249. * Defines a predicate condition as an extension of Condition
  52250. */
  52251. var PredicateCondition = /** @class */ (function (_super) {
  52252. __extends(PredicateCondition, _super);
  52253. /**
  52254. * Creates a new PredicateCondition
  52255. * @param actionManager manager for the action the condition applies to
  52256. * @param predicate defines the predicate function used to validate the condition
  52257. */
  52258. function PredicateCondition(actionManager,
  52259. /** defines the predicate function used to validate the condition */
  52260. predicate) {
  52261. var _this = _super.call(this, actionManager) || this;
  52262. _this.predicate = predicate;
  52263. return _this;
  52264. }
  52265. /**
  52266. * @returns the validity of the predicate condition
  52267. */
  52268. PredicateCondition.prototype.isValid = function () {
  52269. return this.predicate();
  52270. };
  52271. return PredicateCondition;
  52272. }(Condition));
  52273. BABYLON.PredicateCondition = PredicateCondition;
  52274. /**
  52275. * Defines a state condition as an extension of Condition
  52276. */
  52277. var StateCondition = /** @class */ (function (_super) {
  52278. __extends(StateCondition, _super);
  52279. /**
  52280. * Creates a new StateCondition
  52281. * @param actionManager manager for the action the condition applies to
  52282. * @param target of the condition
  52283. * @param value to compare with target state
  52284. */
  52285. function StateCondition(actionManager, target, value) {
  52286. var _this = _super.call(this, actionManager) || this;
  52287. _this.value = value;
  52288. _this._target = target;
  52289. return _this;
  52290. }
  52291. /**
  52292. * @returns the validity of the state
  52293. */
  52294. StateCondition.prototype.isValid = function () {
  52295. return this._target.state === this.value;
  52296. };
  52297. /**
  52298. * Serialize the StateCondition into a JSON compatible object
  52299. * @returns serialization object
  52300. */
  52301. StateCondition.prototype.serialize = function () {
  52302. return this._serialize({
  52303. name: "StateCondition",
  52304. properties: [
  52305. BABYLON.Action._GetTargetProperty(this._target),
  52306. { name: "value", value: this.value }
  52307. ]
  52308. });
  52309. };
  52310. return StateCondition;
  52311. }(Condition));
  52312. BABYLON.StateCondition = StateCondition;
  52313. })(BABYLON || (BABYLON = {}));
  52314. //# sourceMappingURL=babylon.condition.js.map
  52315. var BABYLON;
  52316. (function (BABYLON) {
  52317. /**
  52318. * The action to be carried out following a trigger
  52319. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  52320. */
  52321. var Action = /** @class */ (function () {
  52322. /**
  52323. * Creates a new Action
  52324. * @param triggerOptions the trigger, with or without parameters, for the action
  52325. * @param condition an optional determinant of action
  52326. */
  52327. function Action(
  52328. /** the trigger, with or without parameters, for the action */
  52329. triggerOptions, condition) {
  52330. this.triggerOptions = triggerOptions;
  52331. /**
  52332. * An event triggered prior to action being executed.
  52333. */
  52334. this.onBeforeExecuteObservable = new BABYLON.Observable();
  52335. if (triggerOptions.parameter) {
  52336. this.trigger = triggerOptions.trigger;
  52337. this._triggerParameter = triggerOptions.parameter;
  52338. }
  52339. else if (triggerOptions.trigger) {
  52340. this.trigger = triggerOptions.trigger;
  52341. }
  52342. else {
  52343. this.trigger = triggerOptions;
  52344. }
  52345. this._nextActiveAction = this;
  52346. this._condition = condition;
  52347. }
  52348. /**
  52349. * Internal only
  52350. * @hidden
  52351. */
  52352. Action.prototype._prepare = function () {
  52353. };
  52354. /**
  52355. * Gets the trigger parameters
  52356. * @returns the trigger parameters
  52357. */
  52358. Action.prototype.getTriggerParameter = function () {
  52359. return this._triggerParameter;
  52360. };
  52361. /**
  52362. * Internal only - executes current action event
  52363. * @hidden
  52364. */
  52365. Action.prototype._executeCurrent = function (evt) {
  52366. if (this._nextActiveAction._condition) {
  52367. var condition = this._nextActiveAction._condition;
  52368. var currentRenderId = this._actionManager.getScene().getRenderId();
  52369. // We cache the current evaluation for the current frame
  52370. if (condition._evaluationId === currentRenderId) {
  52371. if (!condition._currentResult) {
  52372. return;
  52373. }
  52374. }
  52375. else {
  52376. condition._evaluationId = currentRenderId;
  52377. if (!condition.isValid()) {
  52378. condition._currentResult = false;
  52379. return;
  52380. }
  52381. condition._currentResult = true;
  52382. }
  52383. }
  52384. this.onBeforeExecuteObservable.notifyObservers(this);
  52385. this._nextActiveAction.execute(evt);
  52386. this.skipToNextActiveAction();
  52387. };
  52388. /**
  52389. * Execute placeholder for child classes
  52390. * @param evt optional action event
  52391. */
  52392. Action.prototype.execute = function (evt) {
  52393. };
  52394. /**
  52395. * Skips to next active action
  52396. */
  52397. Action.prototype.skipToNextActiveAction = function () {
  52398. if (this._nextActiveAction._child) {
  52399. if (!this._nextActiveAction._child._actionManager) {
  52400. this._nextActiveAction._child._actionManager = this._actionManager;
  52401. }
  52402. this._nextActiveAction = this._nextActiveAction._child;
  52403. }
  52404. else {
  52405. this._nextActiveAction = this;
  52406. }
  52407. };
  52408. /**
  52409. * Adds action to chain of actions, may be a DoNothingAction
  52410. * @param action defines the next action to execute
  52411. * @returns The action passed in
  52412. * @see https://www.babylonjs-playground.com/#1T30HR#0
  52413. */
  52414. Action.prototype.then = function (action) {
  52415. this._child = action;
  52416. action._actionManager = this._actionManager;
  52417. action._prepare();
  52418. return action;
  52419. };
  52420. /**
  52421. * Internal only
  52422. * @hidden
  52423. */
  52424. Action.prototype._getProperty = function (propertyPath) {
  52425. return this._actionManager._getProperty(propertyPath);
  52426. };
  52427. /**
  52428. * Internal only
  52429. * @hidden
  52430. */
  52431. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  52432. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52433. };
  52434. /**
  52435. * Serialize placeholder for child classes
  52436. * @param parent of child
  52437. * @returns the serialized object
  52438. */
  52439. Action.prototype.serialize = function (parent) {
  52440. };
  52441. /**
  52442. * Internal only called by serialize
  52443. * @hidden
  52444. */
  52445. Action.prototype._serialize = function (serializedAction, parent) {
  52446. var serializationObject = {
  52447. type: 1,
  52448. children: [],
  52449. name: serializedAction.name,
  52450. properties: serializedAction.properties || []
  52451. };
  52452. // Serialize child
  52453. if (this._child) {
  52454. this._child.serialize(serializationObject);
  52455. }
  52456. // Check if "this" has a condition
  52457. if (this._condition) {
  52458. var serializedCondition = this._condition.serialize();
  52459. serializedCondition.children.push(serializationObject);
  52460. if (parent) {
  52461. parent.children.push(serializedCondition);
  52462. }
  52463. return serializedCondition;
  52464. }
  52465. if (parent) {
  52466. parent.children.push(serializationObject);
  52467. }
  52468. return serializationObject;
  52469. };
  52470. /**
  52471. * Internal only
  52472. * @hidden
  52473. */
  52474. Action._SerializeValueAsString = function (value) {
  52475. if (typeof value === "number") {
  52476. return value.toString();
  52477. }
  52478. if (typeof value === "boolean") {
  52479. return value ? "true" : "false";
  52480. }
  52481. if (value instanceof BABYLON.Vector2) {
  52482. return value.x + ", " + value.y;
  52483. }
  52484. if (value instanceof BABYLON.Vector3) {
  52485. return value.x + ", " + value.y + ", " + value.z;
  52486. }
  52487. if (value instanceof BABYLON.Color3) {
  52488. return value.r + ", " + value.g + ", " + value.b;
  52489. }
  52490. if (value instanceof BABYLON.Color4) {
  52491. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  52492. }
  52493. return value; // string
  52494. };
  52495. /**
  52496. * Internal only
  52497. * @hidden
  52498. */
  52499. Action._GetTargetProperty = function (target) {
  52500. return {
  52501. name: "target",
  52502. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  52503. : target instanceof BABYLON.Light ? "LightProperties"
  52504. : target instanceof BABYLON.Camera ? "CameraProperties"
  52505. : "SceneProperties",
  52506. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  52507. };
  52508. };
  52509. return Action;
  52510. }());
  52511. BABYLON.Action = Action;
  52512. })(BABYLON || (BABYLON = {}));
  52513. //# sourceMappingURL=babylon.action.js.map
  52514. var BABYLON;
  52515. (function (BABYLON) {
  52516. /**
  52517. * ActionEvent is the event being sent when an action is triggered.
  52518. */
  52519. var ActionEvent = /** @class */ (function () {
  52520. /**
  52521. * Creates a new ActionEvent
  52522. * @param source The mesh or sprite that triggered the action
  52523. * @param pointerX The X mouse cursor position at the time of the event
  52524. * @param pointerY The Y mouse cursor position at the time of the event
  52525. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  52526. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  52527. * @param additionalData additional data for the event
  52528. */
  52529. function ActionEvent(
  52530. /** The mesh or sprite that triggered the action */
  52531. source,
  52532. /** The X mouse cursor position at the time of the event */
  52533. pointerX,
  52534. /** The Y mouse cursor position at the time of the event */
  52535. pointerY,
  52536. /** The mesh that is currently pointed at (can be null) */
  52537. meshUnderPointer,
  52538. /** the original (browser) event that triggered the ActionEvent */
  52539. sourceEvent,
  52540. /** additional data for the event */
  52541. additionalData) {
  52542. this.source = source;
  52543. this.pointerX = pointerX;
  52544. this.pointerY = pointerY;
  52545. this.meshUnderPointer = meshUnderPointer;
  52546. this.sourceEvent = sourceEvent;
  52547. this.additionalData = additionalData;
  52548. }
  52549. /**
  52550. * Helper function to auto-create an ActionEvent from a source mesh.
  52551. * @param source The source mesh that triggered the event
  52552. * @param evt The original (browser) event
  52553. * @param additionalData additional data for the event
  52554. * @returns the new ActionEvent
  52555. */
  52556. ActionEvent.CreateNew = function (source, evt, additionalData) {
  52557. var scene = source.getScene();
  52558. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52559. };
  52560. /**
  52561. * Helper function to auto-create an ActionEvent from a source sprite
  52562. * @param source The source sprite that triggered the event
  52563. * @param scene Scene associated with the sprite
  52564. * @param evt The original (browser) event
  52565. * @param additionalData additional data for the event
  52566. * @returns the new ActionEvent
  52567. */
  52568. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  52569. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52570. };
  52571. /**
  52572. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  52573. * @param scene the scene where the event occurred
  52574. * @param evt The original (browser) event
  52575. * @returns the new ActionEvent
  52576. */
  52577. ActionEvent.CreateNewFromScene = function (scene, evt) {
  52578. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  52579. };
  52580. /**
  52581. * Helper function to auto-create an ActionEvent from a primitive
  52582. * @param prim defines the target primitive
  52583. * @param pointerPos defines the pointer position
  52584. * @param evt The original (browser) event
  52585. * @param additionalData additional data for the event
  52586. * @returns the new ActionEvent
  52587. */
  52588. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  52589. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  52590. };
  52591. return ActionEvent;
  52592. }());
  52593. BABYLON.ActionEvent = ActionEvent;
  52594. /**
  52595. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  52596. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  52597. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  52598. */
  52599. var ActionManager = /** @class */ (function () {
  52600. /**
  52601. * Creates a new action manager
  52602. * @param scene defines the hosting scene
  52603. */
  52604. function ActionManager(scene) {
  52605. // Members
  52606. /** Gets the list of actions */
  52607. this.actions = new Array();
  52608. /** Gets the cursor to use when hovering items */
  52609. this.hoverCursor = '';
  52610. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52611. scene.actionManagers.push(this);
  52612. }
  52613. Object.defineProperty(ActionManager, "NothingTrigger", {
  52614. /**
  52615. * Nothing
  52616. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52617. */
  52618. get: function () {
  52619. return ActionManager._NothingTrigger;
  52620. },
  52621. enumerable: true,
  52622. configurable: true
  52623. });
  52624. Object.defineProperty(ActionManager, "OnPickTrigger", {
  52625. /**
  52626. * On pick
  52627. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52628. */
  52629. get: function () {
  52630. return ActionManager._OnPickTrigger;
  52631. },
  52632. enumerable: true,
  52633. configurable: true
  52634. });
  52635. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  52636. /**
  52637. * On left pick
  52638. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52639. */
  52640. get: function () {
  52641. return ActionManager._OnLeftPickTrigger;
  52642. },
  52643. enumerable: true,
  52644. configurable: true
  52645. });
  52646. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  52647. /**
  52648. * On right pick
  52649. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52650. */
  52651. get: function () {
  52652. return ActionManager._OnRightPickTrigger;
  52653. },
  52654. enumerable: true,
  52655. configurable: true
  52656. });
  52657. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  52658. /**
  52659. * On center pick
  52660. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52661. */
  52662. get: function () {
  52663. return ActionManager._OnCenterPickTrigger;
  52664. },
  52665. enumerable: true,
  52666. configurable: true
  52667. });
  52668. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  52669. /**
  52670. * On pick down
  52671. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52672. */
  52673. get: function () {
  52674. return ActionManager._OnPickDownTrigger;
  52675. },
  52676. enumerable: true,
  52677. configurable: true
  52678. });
  52679. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  52680. /**
  52681. * On double pick
  52682. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52683. */
  52684. get: function () {
  52685. return ActionManager._OnDoublePickTrigger;
  52686. },
  52687. enumerable: true,
  52688. configurable: true
  52689. });
  52690. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  52691. /**
  52692. * On pick up
  52693. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52694. */
  52695. get: function () {
  52696. return ActionManager._OnPickUpTrigger;
  52697. },
  52698. enumerable: true,
  52699. configurable: true
  52700. });
  52701. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  52702. /**
  52703. * On pick out.
  52704. * This trigger will only be raised if you also declared a OnPickDown
  52705. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52706. */
  52707. get: function () {
  52708. return ActionManager._OnPickOutTrigger;
  52709. },
  52710. enumerable: true,
  52711. configurable: true
  52712. });
  52713. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  52714. /**
  52715. * On long press
  52716. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52717. */
  52718. get: function () {
  52719. return ActionManager._OnLongPressTrigger;
  52720. },
  52721. enumerable: true,
  52722. configurable: true
  52723. });
  52724. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  52725. /**
  52726. * On pointer over
  52727. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52728. */
  52729. get: function () {
  52730. return ActionManager._OnPointerOverTrigger;
  52731. },
  52732. enumerable: true,
  52733. configurable: true
  52734. });
  52735. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  52736. /**
  52737. * On pointer out
  52738. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52739. */
  52740. get: function () {
  52741. return ActionManager._OnPointerOutTrigger;
  52742. },
  52743. enumerable: true,
  52744. configurable: true
  52745. });
  52746. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  52747. /**
  52748. * On every frame
  52749. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52750. */
  52751. get: function () {
  52752. return ActionManager._OnEveryFrameTrigger;
  52753. },
  52754. enumerable: true,
  52755. configurable: true
  52756. });
  52757. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  52758. /**
  52759. * On intersection enter
  52760. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52761. */
  52762. get: function () {
  52763. return ActionManager._OnIntersectionEnterTrigger;
  52764. },
  52765. enumerable: true,
  52766. configurable: true
  52767. });
  52768. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  52769. /**
  52770. * On intersection exit
  52771. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52772. */
  52773. get: function () {
  52774. return ActionManager._OnIntersectionExitTrigger;
  52775. },
  52776. enumerable: true,
  52777. configurable: true
  52778. });
  52779. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  52780. /**
  52781. * On key down
  52782. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52783. */
  52784. get: function () {
  52785. return ActionManager._OnKeyDownTrigger;
  52786. },
  52787. enumerable: true,
  52788. configurable: true
  52789. });
  52790. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  52791. /**
  52792. * On key up
  52793. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52794. */
  52795. get: function () {
  52796. return ActionManager._OnKeyUpTrigger;
  52797. },
  52798. enumerable: true,
  52799. configurable: true
  52800. });
  52801. // Methods
  52802. /**
  52803. * Releases all associated resources
  52804. */
  52805. ActionManager.prototype.dispose = function () {
  52806. var index = this._scene.actionManagers.indexOf(this);
  52807. for (var i = 0; i < this.actions.length; i++) {
  52808. var action = this.actions[i];
  52809. ActionManager.Triggers[action.trigger]--;
  52810. if (ActionManager.Triggers[action.trigger] === 0) {
  52811. delete ActionManager.Triggers[action.trigger];
  52812. }
  52813. }
  52814. if (index > -1) {
  52815. this._scene.actionManagers.splice(index, 1);
  52816. }
  52817. };
  52818. /**
  52819. * Gets hosting scene
  52820. * @returns the hosting scene
  52821. */
  52822. ActionManager.prototype.getScene = function () {
  52823. return this._scene;
  52824. };
  52825. /**
  52826. * Does this action manager handles actions of any of the given triggers
  52827. * @param triggers defines the triggers to be tested
  52828. * @return a boolean indicating whether one (or more) of the triggers is handled
  52829. */
  52830. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  52831. for (var index = 0; index < this.actions.length; index++) {
  52832. var action = this.actions[index];
  52833. if (triggers.indexOf(action.trigger) > -1) {
  52834. return true;
  52835. }
  52836. }
  52837. return false;
  52838. };
  52839. /**
  52840. * Does this action manager handles actions of any of the given triggers. This function takes two arguments for
  52841. * speed.
  52842. * @param triggerA defines the trigger to be tested
  52843. * @param triggerB defines the trigger to be tested
  52844. * @return a boolean indicating whether one (or more) of the triggers is handled
  52845. */
  52846. ActionManager.prototype.hasSpecificTriggers2 = function (triggerA, triggerB) {
  52847. for (var index = 0; index < this.actions.length; index++) {
  52848. var action = this.actions[index];
  52849. if (triggerA == action.trigger || triggerB == action.trigger) {
  52850. return true;
  52851. }
  52852. }
  52853. return false;
  52854. };
  52855. /**
  52856. * Does this action manager handles actions of a given trigger
  52857. * @param trigger defines the trigger to be tested
  52858. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  52859. * @return whether the trigger is handled
  52860. */
  52861. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  52862. for (var index = 0; index < this.actions.length; index++) {
  52863. var action = this.actions[index];
  52864. if (action.trigger === trigger) {
  52865. if (parameterPredicate) {
  52866. if (parameterPredicate(action.getTriggerParameter())) {
  52867. return true;
  52868. }
  52869. }
  52870. else {
  52871. return true;
  52872. }
  52873. }
  52874. }
  52875. return false;
  52876. };
  52877. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  52878. /**
  52879. * Does this action manager has pointer triggers
  52880. */
  52881. get: function () {
  52882. for (var index = 0; index < this.actions.length; index++) {
  52883. var action = this.actions[index];
  52884. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  52885. return true;
  52886. }
  52887. }
  52888. return false;
  52889. },
  52890. enumerable: true,
  52891. configurable: true
  52892. });
  52893. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  52894. /**
  52895. * Does this action manager has pick triggers
  52896. */
  52897. get: function () {
  52898. for (var index = 0; index < this.actions.length; index++) {
  52899. var action = this.actions[index];
  52900. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  52901. return true;
  52902. }
  52903. }
  52904. return false;
  52905. },
  52906. enumerable: true,
  52907. configurable: true
  52908. });
  52909. Object.defineProperty(ActionManager, "HasTriggers", {
  52910. /**
  52911. * Does exist one action manager with at least one trigger
  52912. **/
  52913. get: function () {
  52914. for (var t in ActionManager.Triggers) {
  52915. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52916. return true;
  52917. }
  52918. }
  52919. return false;
  52920. },
  52921. enumerable: true,
  52922. configurable: true
  52923. });
  52924. Object.defineProperty(ActionManager, "HasPickTriggers", {
  52925. /**
  52926. * Does exist one action manager with at least one pick trigger
  52927. **/
  52928. get: function () {
  52929. for (var t in ActionManager.Triggers) {
  52930. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52931. var t_int = parseInt(t);
  52932. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  52933. return true;
  52934. }
  52935. }
  52936. }
  52937. return false;
  52938. },
  52939. enumerable: true,
  52940. configurable: true
  52941. });
  52942. /**
  52943. * Does exist one action manager that handles actions of a given trigger
  52944. * @param trigger defines the trigger to be tested
  52945. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  52946. **/
  52947. ActionManager.HasSpecificTrigger = function (trigger) {
  52948. for (var t in ActionManager.Triggers) {
  52949. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52950. var t_int = parseInt(t);
  52951. if (t_int === trigger) {
  52952. return true;
  52953. }
  52954. }
  52955. }
  52956. return false;
  52957. };
  52958. /**
  52959. * Registers an action to this action manager
  52960. * @param action defines the action to be registered
  52961. * @return the action amended (prepared) after registration
  52962. */
  52963. ActionManager.prototype.registerAction = function (action) {
  52964. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  52965. if (this.getScene().actionManager !== this) {
  52966. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  52967. return null;
  52968. }
  52969. }
  52970. this.actions.push(action);
  52971. if (ActionManager.Triggers[action.trigger]) {
  52972. ActionManager.Triggers[action.trigger]++;
  52973. }
  52974. else {
  52975. ActionManager.Triggers[action.trigger] = 1;
  52976. }
  52977. action._actionManager = this;
  52978. action._prepare();
  52979. return action;
  52980. };
  52981. /**
  52982. * Unregisters an action to this action manager
  52983. * @param action defines the action to be unregistered
  52984. * @return a boolean indicating whether the action has been unregistered
  52985. */
  52986. ActionManager.prototype.unregisterAction = function (action) {
  52987. var index = this.actions.indexOf(action);
  52988. if (index !== -1) {
  52989. this.actions.splice(index, 1);
  52990. ActionManager.Triggers[action.trigger] -= 1;
  52991. if (ActionManager.Triggers[action.trigger] === 0) {
  52992. delete ActionManager.Triggers[action.trigger];
  52993. }
  52994. delete action._actionManager;
  52995. return true;
  52996. }
  52997. return false;
  52998. };
  52999. /**
  53000. * Process a specific trigger
  53001. * @param trigger defines the trigger to process
  53002. * @param evt defines the event details to be processed
  53003. */
  53004. ActionManager.prototype.processTrigger = function (trigger, evt) {
  53005. for (var index = 0; index < this.actions.length; index++) {
  53006. var action = this.actions[index];
  53007. if (action.trigger === trigger) {
  53008. if (evt) {
  53009. if (trigger === ActionManager.OnKeyUpTrigger
  53010. || trigger === ActionManager.OnKeyDownTrigger) {
  53011. var parameter = action.getTriggerParameter();
  53012. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  53013. if (!parameter.toLowerCase) {
  53014. continue;
  53015. }
  53016. var lowerCase = parameter.toLowerCase();
  53017. if (lowerCase !== evt.sourceEvent.key) {
  53018. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  53019. var actualkey = String.fromCharCode(unicode).toLowerCase();
  53020. if (actualkey !== lowerCase) {
  53021. continue;
  53022. }
  53023. }
  53024. }
  53025. }
  53026. }
  53027. action._executeCurrent(evt);
  53028. }
  53029. }
  53030. };
  53031. /** @hidden */
  53032. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  53033. var properties = propertyPath.split(".");
  53034. for (var index = 0; index < properties.length - 1; index++) {
  53035. target = target[properties[index]];
  53036. }
  53037. return target;
  53038. };
  53039. /** @hidden */
  53040. ActionManager.prototype._getProperty = function (propertyPath) {
  53041. var properties = propertyPath.split(".");
  53042. return properties[properties.length - 1];
  53043. };
  53044. /**
  53045. * Serialize this manager to a JSON object
  53046. * @param name defines the property name to store this manager
  53047. * @returns a JSON representation of this manager
  53048. */
  53049. ActionManager.prototype.serialize = function (name) {
  53050. var root = {
  53051. children: new Array(),
  53052. name: name,
  53053. type: 3,
  53054. properties: new Array() // Empty for root but required
  53055. };
  53056. for (var i = 0; i < this.actions.length; i++) {
  53057. var triggerObject = {
  53058. type: 0,
  53059. children: new Array(),
  53060. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  53061. properties: new Array()
  53062. };
  53063. var triggerOptions = this.actions[i].triggerOptions;
  53064. if (triggerOptions && typeof triggerOptions !== "number") {
  53065. if (triggerOptions.parameter instanceof BABYLON.Node) {
  53066. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  53067. }
  53068. else {
  53069. var parameter = {};
  53070. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  53071. if (triggerOptions.parameter.mesh) {
  53072. parameter._meshId = triggerOptions.parameter.mesh.id;
  53073. }
  53074. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  53075. }
  53076. }
  53077. // Serialize child action, recursively
  53078. this.actions[i].serialize(triggerObject);
  53079. // Add serialized trigger
  53080. root.children.push(triggerObject);
  53081. }
  53082. return root;
  53083. };
  53084. /**
  53085. * Creates a new ActionManager from a JSON data
  53086. * @param parsedActions defines the JSON data to read from
  53087. * @param object defines the hosting mesh
  53088. * @param scene defines the hosting scene
  53089. */
  53090. ActionManager.Parse = function (parsedActions, object, scene) {
  53091. var actionManager = new ActionManager(scene);
  53092. if (object === null)
  53093. scene.actionManager = actionManager;
  53094. else
  53095. object.actionManager = actionManager;
  53096. // instanciate a new object
  53097. var instanciate = function (name, params) {
  53098. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  53099. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  53100. newInstance.constructor.apply(newInstance, params);
  53101. return newInstance;
  53102. };
  53103. var parseParameter = function (name, value, target, propertyPath) {
  53104. if (propertyPath === null) {
  53105. // String, boolean or float
  53106. var floatValue = parseFloat(value);
  53107. if (value === "true" || value === "false")
  53108. return value === "true";
  53109. else
  53110. return isNaN(floatValue) ? value : floatValue;
  53111. }
  53112. var effectiveTarget = propertyPath.split(".");
  53113. var values = value.split(",");
  53114. // Get effective Target
  53115. for (var i = 0; i < effectiveTarget.length; i++) {
  53116. target = target[effectiveTarget[i]];
  53117. }
  53118. // Return appropriate value with its type
  53119. if (typeof (target) === "boolean")
  53120. return values[0] === "true";
  53121. if (typeof (target) === "string")
  53122. return values[0];
  53123. // Parameters with multiple values such as Vector3 etc.
  53124. var split = new Array();
  53125. for (var i = 0; i < values.length; i++)
  53126. split.push(parseFloat(values[i]));
  53127. if (target instanceof BABYLON.Vector3)
  53128. return BABYLON.Vector3.FromArray(split);
  53129. if (target instanceof BABYLON.Vector4)
  53130. return BABYLON.Vector4.FromArray(split);
  53131. if (target instanceof BABYLON.Color3)
  53132. return BABYLON.Color3.FromArray(split);
  53133. if (target instanceof BABYLON.Color4)
  53134. return BABYLON.Color4.FromArray(split);
  53135. return parseFloat(values[0]);
  53136. };
  53137. // traverse graph per trigger
  53138. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  53139. if (combineArray === void 0) { combineArray = null; }
  53140. if (parsedAction.detached)
  53141. return;
  53142. var parameters = new Array();
  53143. var target = null;
  53144. var propertyPath = null;
  53145. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  53146. // Parameters
  53147. if (parsedAction.type === 2)
  53148. parameters.push(actionManager);
  53149. else
  53150. parameters.push(trigger);
  53151. if (combine) {
  53152. var actions = new Array();
  53153. for (var j = 0; j < parsedAction.combine.length; j++) {
  53154. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  53155. }
  53156. parameters.push(actions);
  53157. }
  53158. else {
  53159. for (var i = 0; i < parsedAction.properties.length; i++) {
  53160. var value = parsedAction.properties[i].value;
  53161. var name = parsedAction.properties[i].name;
  53162. var targetType = parsedAction.properties[i].targetType;
  53163. if (name === "target")
  53164. if (targetType !== null && targetType === "SceneProperties")
  53165. value = target = scene;
  53166. else
  53167. value = target = scene.getNodeByName(value);
  53168. else if (name === "parent")
  53169. value = scene.getNodeByName(value);
  53170. else if (name === "sound")
  53171. value = scene.getSoundByName(value);
  53172. else if (name !== "propertyPath") {
  53173. if (parsedAction.type === 2 && name === "operator")
  53174. value = BABYLON.ValueCondition[value];
  53175. else
  53176. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  53177. }
  53178. else {
  53179. propertyPath = value;
  53180. }
  53181. parameters.push(value);
  53182. }
  53183. }
  53184. if (combineArray === null) {
  53185. parameters.push(condition);
  53186. }
  53187. else {
  53188. parameters.push(null);
  53189. }
  53190. // If interpolate value action
  53191. if (parsedAction.name === "InterpolateValueAction") {
  53192. var param = parameters[parameters.length - 2];
  53193. parameters[parameters.length - 1] = param;
  53194. parameters[parameters.length - 2] = condition;
  53195. }
  53196. // Action or condition(s) and not CombineAction
  53197. var newAction = instanciate(parsedAction.name, parameters);
  53198. if (newAction instanceof BABYLON.Condition && condition !== null) {
  53199. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  53200. if (action)
  53201. action.then(nothing);
  53202. else
  53203. actionManager.registerAction(nothing);
  53204. action = nothing;
  53205. }
  53206. if (combineArray === null) {
  53207. if (newAction instanceof BABYLON.Condition) {
  53208. condition = newAction;
  53209. newAction = action;
  53210. }
  53211. else {
  53212. condition = null;
  53213. if (action)
  53214. action.then(newAction);
  53215. else
  53216. actionManager.registerAction(newAction);
  53217. }
  53218. }
  53219. else {
  53220. combineArray.push(newAction);
  53221. }
  53222. for (var i = 0; i < parsedAction.children.length; i++)
  53223. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  53224. };
  53225. // triggers
  53226. for (var i = 0; i < parsedActions.children.length; i++) {
  53227. var triggerParams;
  53228. var trigger = parsedActions.children[i];
  53229. if (trigger.properties.length > 0) {
  53230. var param = trigger.properties[0].value;
  53231. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  53232. if (value._meshId) {
  53233. value.mesh = scene.getMeshByID(value._meshId);
  53234. }
  53235. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  53236. }
  53237. else
  53238. triggerParams = ActionManager[trigger.name];
  53239. for (var j = 0; j < trigger.children.length; j++) {
  53240. if (!trigger.detached)
  53241. traverse(trigger.children[j], triggerParams, null, null);
  53242. }
  53243. }
  53244. };
  53245. /**
  53246. * Get a trigger name by index
  53247. * @param trigger defines the trigger index
  53248. * @returns a trigger name
  53249. */
  53250. ActionManager.GetTriggerName = function (trigger) {
  53251. switch (trigger) {
  53252. case 0: return "NothingTrigger";
  53253. case 1: return "OnPickTrigger";
  53254. case 2: return "OnLeftPickTrigger";
  53255. case 3: return "OnRightPickTrigger";
  53256. case 4: return "OnCenterPickTrigger";
  53257. case 5: return "OnPickDownTrigger";
  53258. case 6: return "OnPickUpTrigger";
  53259. case 7: return "OnLongPressTrigger";
  53260. case 8: return "OnPointerOverTrigger";
  53261. case 9: return "OnPointerOutTrigger";
  53262. case 10: return "OnEveryFrameTrigger";
  53263. case 11: return "OnIntersectionEnterTrigger";
  53264. case 12: return "OnIntersectionExitTrigger";
  53265. case 13: return "OnKeyDownTrigger";
  53266. case 14: return "OnKeyUpTrigger";
  53267. case 15: return "OnPickOutTrigger";
  53268. default: return "";
  53269. }
  53270. };
  53271. // Statics
  53272. ActionManager._NothingTrigger = 0;
  53273. ActionManager._OnPickTrigger = 1;
  53274. ActionManager._OnLeftPickTrigger = 2;
  53275. ActionManager._OnRightPickTrigger = 3;
  53276. ActionManager._OnCenterPickTrigger = 4;
  53277. ActionManager._OnPickDownTrigger = 5;
  53278. ActionManager._OnDoublePickTrigger = 6;
  53279. ActionManager._OnPickUpTrigger = 7;
  53280. ActionManager._OnLongPressTrigger = 8;
  53281. ActionManager._OnPointerOverTrigger = 9;
  53282. ActionManager._OnPointerOutTrigger = 10;
  53283. ActionManager._OnEveryFrameTrigger = 11;
  53284. ActionManager._OnIntersectionEnterTrigger = 12;
  53285. ActionManager._OnIntersectionExitTrigger = 13;
  53286. ActionManager._OnKeyDownTrigger = 14;
  53287. ActionManager._OnKeyUpTrigger = 15;
  53288. ActionManager._OnPickOutTrigger = 16;
  53289. /** Gets the list of active triggers */
  53290. ActionManager.Triggers = {};
  53291. return ActionManager;
  53292. }());
  53293. BABYLON.ActionManager = ActionManager;
  53294. })(BABYLON || (BABYLON = {}));
  53295. //# sourceMappingURL=babylon.actionManager.js.map
  53296. var BABYLON;
  53297. (function (BABYLON) {
  53298. var InterpolateValueAction = /** @class */ (function (_super) {
  53299. __extends(InterpolateValueAction, _super);
  53300. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  53301. if (duration === void 0) { duration = 1000; }
  53302. var _this = _super.call(this, triggerOptions, condition) || this;
  53303. _this.propertyPath = propertyPath;
  53304. _this.value = value;
  53305. _this.duration = duration;
  53306. _this.stopOtherAnimations = stopOtherAnimations;
  53307. _this.onInterpolationDone = onInterpolationDone;
  53308. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  53309. _this._target = _this._effectiveTarget = target;
  53310. return _this;
  53311. }
  53312. /** @hidden */
  53313. InterpolateValueAction.prototype._prepare = function () {
  53314. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53315. this._property = this._getProperty(this.propertyPath);
  53316. };
  53317. InterpolateValueAction.prototype.execute = function () {
  53318. var _this = this;
  53319. var scene = this._actionManager.getScene();
  53320. var keys = [
  53321. {
  53322. frame: 0,
  53323. value: this._effectiveTarget[this._property]
  53324. }, {
  53325. frame: 100,
  53326. value: this.value
  53327. }
  53328. ];
  53329. var dataType;
  53330. if (typeof this.value === "number") {
  53331. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  53332. }
  53333. else if (this.value instanceof BABYLON.Color3) {
  53334. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  53335. }
  53336. else if (this.value instanceof BABYLON.Vector3) {
  53337. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  53338. }
  53339. else if (this.value instanceof BABYLON.Matrix) {
  53340. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  53341. }
  53342. else if (this.value instanceof BABYLON.Quaternion) {
  53343. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  53344. }
  53345. else {
  53346. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  53347. return;
  53348. }
  53349. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  53350. animation.setKeys(keys);
  53351. if (this.stopOtherAnimations) {
  53352. scene.stopAnimation(this._effectiveTarget);
  53353. }
  53354. var wrapper = function () {
  53355. _this.onInterpolationDoneObservable.notifyObservers(_this);
  53356. if (_this.onInterpolationDone) {
  53357. _this.onInterpolationDone();
  53358. }
  53359. };
  53360. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  53361. };
  53362. InterpolateValueAction.prototype.serialize = function (parent) {
  53363. return _super.prototype._serialize.call(this, {
  53364. name: "InterpolateValueAction",
  53365. properties: [
  53366. BABYLON.Action._GetTargetProperty(this._target),
  53367. { name: "propertyPath", value: this.propertyPath },
  53368. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  53369. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  53370. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  53371. ]
  53372. }, parent);
  53373. };
  53374. return InterpolateValueAction;
  53375. }(BABYLON.Action));
  53376. BABYLON.InterpolateValueAction = InterpolateValueAction;
  53377. })(BABYLON || (BABYLON = {}));
  53378. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  53379. var BABYLON;
  53380. (function (BABYLON) {
  53381. var SwitchBooleanAction = /** @class */ (function (_super) {
  53382. __extends(SwitchBooleanAction, _super);
  53383. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  53384. var _this = _super.call(this, triggerOptions, condition) || this;
  53385. _this.propertyPath = propertyPath;
  53386. _this._target = _this._effectiveTarget = target;
  53387. return _this;
  53388. }
  53389. /** @hidden */
  53390. SwitchBooleanAction.prototype._prepare = function () {
  53391. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53392. this._property = this._getProperty(this.propertyPath);
  53393. };
  53394. SwitchBooleanAction.prototype.execute = function () {
  53395. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  53396. };
  53397. SwitchBooleanAction.prototype.serialize = function (parent) {
  53398. return _super.prototype._serialize.call(this, {
  53399. name: "SwitchBooleanAction",
  53400. properties: [
  53401. BABYLON.Action._GetTargetProperty(this._target),
  53402. { name: "propertyPath", value: this.propertyPath }
  53403. ]
  53404. }, parent);
  53405. };
  53406. return SwitchBooleanAction;
  53407. }(BABYLON.Action));
  53408. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  53409. var SetStateAction = /** @class */ (function (_super) {
  53410. __extends(SetStateAction, _super);
  53411. function SetStateAction(triggerOptions, target, value, condition) {
  53412. var _this = _super.call(this, triggerOptions, condition) || this;
  53413. _this.value = value;
  53414. _this._target = target;
  53415. return _this;
  53416. }
  53417. SetStateAction.prototype.execute = function () {
  53418. this._target.state = this.value;
  53419. };
  53420. SetStateAction.prototype.serialize = function (parent) {
  53421. return _super.prototype._serialize.call(this, {
  53422. name: "SetStateAction",
  53423. properties: [
  53424. BABYLON.Action._GetTargetProperty(this._target),
  53425. { name: "value", value: this.value }
  53426. ]
  53427. }, parent);
  53428. };
  53429. return SetStateAction;
  53430. }(BABYLON.Action));
  53431. BABYLON.SetStateAction = SetStateAction;
  53432. var SetValueAction = /** @class */ (function (_super) {
  53433. __extends(SetValueAction, _super);
  53434. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  53435. var _this = _super.call(this, triggerOptions, condition) || this;
  53436. _this.propertyPath = propertyPath;
  53437. _this.value = value;
  53438. _this._target = _this._effectiveTarget = target;
  53439. return _this;
  53440. }
  53441. /** @hidden */
  53442. SetValueAction.prototype._prepare = function () {
  53443. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53444. this._property = this._getProperty(this.propertyPath);
  53445. };
  53446. SetValueAction.prototype.execute = function () {
  53447. this._effectiveTarget[this._property] = this.value;
  53448. if (this._target.markAsDirty) {
  53449. this._target.markAsDirty(this._property);
  53450. }
  53451. };
  53452. SetValueAction.prototype.serialize = function (parent) {
  53453. return _super.prototype._serialize.call(this, {
  53454. name: "SetValueAction",
  53455. properties: [
  53456. BABYLON.Action._GetTargetProperty(this._target),
  53457. { name: "propertyPath", value: this.propertyPath },
  53458. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53459. ]
  53460. }, parent);
  53461. };
  53462. return SetValueAction;
  53463. }(BABYLON.Action));
  53464. BABYLON.SetValueAction = SetValueAction;
  53465. var IncrementValueAction = /** @class */ (function (_super) {
  53466. __extends(IncrementValueAction, _super);
  53467. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  53468. var _this = _super.call(this, triggerOptions, condition) || this;
  53469. _this.propertyPath = propertyPath;
  53470. _this.value = value;
  53471. _this._target = _this._effectiveTarget = target;
  53472. return _this;
  53473. }
  53474. /** @hidden */
  53475. IncrementValueAction.prototype._prepare = function () {
  53476. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53477. this._property = this._getProperty(this.propertyPath);
  53478. if (typeof this._effectiveTarget[this._property] !== "number") {
  53479. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  53480. }
  53481. };
  53482. IncrementValueAction.prototype.execute = function () {
  53483. this._effectiveTarget[this._property] += this.value;
  53484. if (this._target.markAsDirty) {
  53485. this._target.markAsDirty(this._property);
  53486. }
  53487. };
  53488. IncrementValueAction.prototype.serialize = function (parent) {
  53489. return _super.prototype._serialize.call(this, {
  53490. name: "IncrementValueAction",
  53491. properties: [
  53492. BABYLON.Action._GetTargetProperty(this._target),
  53493. { name: "propertyPath", value: this.propertyPath },
  53494. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53495. ]
  53496. }, parent);
  53497. };
  53498. return IncrementValueAction;
  53499. }(BABYLON.Action));
  53500. BABYLON.IncrementValueAction = IncrementValueAction;
  53501. var PlayAnimationAction = /** @class */ (function (_super) {
  53502. __extends(PlayAnimationAction, _super);
  53503. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  53504. var _this = _super.call(this, triggerOptions, condition) || this;
  53505. _this.from = from;
  53506. _this.to = to;
  53507. _this.loop = loop;
  53508. _this._target = target;
  53509. return _this;
  53510. }
  53511. /** @hidden */
  53512. PlayAnimationAction.prototype._prepare = function () {
  53513. };
  53514. PlayAnimationAction.prototype.execute = function () {
  53515. var scene = this._actionManager.getScene();
  53516. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  53517. };
  53518. PlayAnimationAction.prototype.serialize = function (parent) {
  53519. return _super.prototype._serialize.call(this, {
  53520. name: "PlayAnimationAction",
  53521. properties: [
  53522. BABYLON.Action._GetTargetProperty(this._target),
  53523. { name: "from", value: String(this.from) },
  53524. { name: "to", value: String(this.to) },
  53525. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  53526. ]
  53527. }, parent);
  53528. };
  53529. return PlayAnimationAction;
  53530. }(BABYLON.Action));
  53531. BABYLON.PlayAnimationAction = PlayAnimationAction;
  53532. var StopAnimationAction = /** @class */ (function (_super) {
  53533. __extends(StopAnimationAction, _super);
  53534. function StopAnimationAction(triggerOptions, target, condition) {
  53535. var _this = _super.call(this, triggerOptions, condition) || this;
  53536. _this._target = target;
  53537. return _this;
  53538. }
  53539. /** @hidden */
  53540. StopAnimationAction.prototype._prepare = function () {
  53541. };
  53542. StopAnimationAction.prototype.execute = function () {
  53543. var scene = this._actionManager.getScene();
  53544. scene.stopAnimation(this._target);
  53545. };
  53546. StopAnimationAction.prototype.serialize = function (parent) {
  53547. return _super.prototype._serialize.call(this, {
  53548. name: "StopAnimationAction",
  53549. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  53550. }, parent);
  53551. };
  53552. return StopAnimationAction;
  53553. }(BABYLON.Action));
  53554. BABYLON.StopAnimationAction = StopAnimationAction;
  53555. var DoNothingAction = /** @class */ (function (_super) {
  53556. __extends(DoNothingAction, _super);
  53557. function DoNothingAction(triggerOptions, condition) {
  53558. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  53559. return _super.call(this, triggerOptions, condition) || this;
  53560. }
  53561. DoNothingAction.prototype.execute = function () {
  53562. };
  53563. DoNothingAction.prototype.serialize = function (parent) {
  53564. return _super.prototype._serialize.call(this, {
  53565. name: "DoNothingAction",
  53566. properties: []
  53567. }, parent);
  53568. };
  53569. return DoNothingAction;
  53570. }(BABYLON.Action));
  53571. BABYLON.DoNothingAction = DoNothingAction;
  53572. var CombineAction = /** @class */ (function (_super) {
  53573. __extends(CombineAction, _super);
  53574. function CombineAction(triggerOptions, children, condition) {
  53575. var _this = _super.call(this, triggerOptions, condition) || this;
  53576. _this.children = children;
  53577. return _this;
  53578. }
  53579. /** @hidden */
  53580. CombineAction.prototype._prepare = function () {
  53581. for (var index = 0; index < this.children.length; index++) {
  53582. this.children[index]._actionManager = this._actionManager;
  53583. this.children[index]._prepare();
  53584. }
  53585. };
  53586. CombineAction.prototype.execute = function (evt) {
  53587. for (var index = 0; index < this.children.length; index++) {
  53588. this.children[index].execute(evt);
  53589. }
  53590. };
  53591. CombineAction.prototype.serialize = function (parent) {
  53592. var serializationObject = _super.prototype._serialize.call(this, {
  53593. name: "CombineAction",
  53594. properties: [],
  53595. combine: []
  53596. }, parent);
  53597. for (var i = 0; i < this.children.length; i++) {
  53598. serializationObject.combine.push(this.children[i].serialize(null));
  53599. }
  53600. return serializationObject;
  53601. };
  53602. return CombineAction;
  53603. }(BABYLON.Action));
  53604. BABYLON.CombineAction = CombineAction;
  53605. var ExecuteCodeAction = /** @class */ (function (_super) {
  53606. __extends(ExecuteCodeAction, _super);
  53607. function ExecuteCodeAction(triggerOptions, func, condition) {
  53608. var _this = _super.call(this, triggerOptions, condition) || this;
  53609. _this.func = func;
  53610. return _this;
  53611. }
  53612. ExecuteCodeAction.prototype.execute = function (evt) {
  53613. this.func(evt);
  53614. };
  53615. return ExecuteCodeAction;
  53616. }(BABYLON.Action));
  53617. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  53618. var SetParentAction = /** @class */ (function (_super) {
  53619. __extends(SetParentAction, _super);
  53620. function SetParentAction(triggerOptions, target, parent, condition) {
  53621. var _this = _super.call(this, triggerOptions, condition) || this;
  53622. _this._target = target;
  53623. _this._parent = parent;
  53624. return _this;
  53625. }
  53626. /** @hidden */
  53627. SetParentAction.prototype._prepare = function () {
  53628. };
  53629. SetParentAction.prototype.execute = function () {
  53630. if (this._target.parent === this._parent) {
  53631. return;
  53632. }
  53633. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  53634. invertParentWorldMatrix.invert();
  53635. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  53636. this._target.parent = this._parent;
  53637. };
  53638. SetParentAction.prototype.serialize = function (parent) {
  53639. return _super.prototype._serialize.call(this, {
  53640. name: "SetParentAction",
  53641. properties: [
  53642. BABYLON.Action._GetTargetProperty(this._target),
  53643. BABYLON.Action._GetTargetProperty(this._parent),
  53644. ]
  53645. }, parent);
  53646. };
  53647. return SetParentAction;
  53648. }(BABYLON.Action));
  53649. BABYLON.SetParentAction = SetParentAction;
  53650. var PlaySoundAction = /** @class */ (function (_super) {
  53651. __extends(PlaySoundAction, _super);
  53652. function PlaySoundAction(triggerOptions, sound, condition) {
  53653. var _this = _super.call(this, triggerOptions, condition) || this;
  53654. _this._sound = sound;
  53655. return _this;
  53656. }
  53657. /** @hidden */
  53658. PlaySoundAction.prototype._prepare = function () {
  53659. };
  53660. PlaySoundAction.prototype.execute = function () {
  53661. if (this._sound !== undefined)
  53662. this._sound.play();
  53663. };
  53664. PlaySoundAction.prototype.serialize = function (parent) {
  53665. return _super.prototype._serialize.call(this, {
  53666. name: "PlaySoundAction",
  53667. properties: [{ name: "sound", value: this._sound.name }]
  53668. }, parent);
  53669. };
  53670. return PlaySoundAction;
  53671. }(BABYLON.Action));
  53672. BABYLON.PlaySoundAction = PlaySoundAction;
  53673. var StopSoundAction = /** @class */ (function (_super) {
  53674. __extends(StopSoundAction, _super);
  53675. function StopSoundAction(triggerOptions, sound, condition) {
  53676. var _this = _super.call(this, triggerOptions, condition) || this;
  53677. _this._sound = sound;
  53678. return _this;
  53679. }
  53680. /** @hidden */
  53681. StopSoundAction.prototype._prepare = function () {
  53682. };
  53683. StopSoundAction.prototype.execute = function () {
  53684. if (this._sound !== undefined)
  53685. this._sound.stop();
  53686. };
  53687. StopSoundAction.prototype.serialize = function (parent) {
  53688. return _super.prototype._serialize.call(this, {
  53689. name: "StopSoundAction",
  53690. properties: [{ name: "sound", value: this._sound.name }]
  53691. }, parent);
  53692. };
  53693. return StopSoundAction;
  53694. }(BABYLON.Action));
  53695. BABYLON.StopSoundAction = StopSoundAction;
  53696. })(BABYLON || (BABYLON = {}));
  53697. //# sourceMappingURL=babylon.directActions.js.map
  53698. var BABYLON;
  53699. (function (BABYLON) {
  53700. var SpriteManager = /** @class */ (function () {
  53701. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  53702. if (epsilon === void 0) { epsilon = 0.01; }
  53703. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53704. this.name = name;
  53705. this.sprites = new Array();
  53706. this.renderingGroupId = 0;
  53707. this.layerMask = 0x0FFFFFFF;
  53708. this.fogEnabled = true;
  53709. this.isPickable = false;
  53710. /**
  53711. * An event triggered when the manager is disposed.
  53712. */
  53713. this.onDisposeObservable = new BABYLON.Observable();
  53714. this._vertexBuffers = {};
  53715. if (!scene._getComponent(BABYLON.SceneComponentConstants.NAME_SPRITE)) {
  53716. scene._addComponent(new BABYLON.SpriteSceneComponent(scene));
  53717. }
  53718. this._capacity = capacity;
  53719. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  53720. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53721. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53722. if (cellSize.width && cellSize.height) {
  53723. this.cellWidth = cellSize.width;
  53724. this.cellHeight = cellSize.height;
  53725. }
  53726. else if (cellSize !== undefined) {
  53727. this.cellWidth = cellSize;
  53728. this.cellHeight = cellSize;
  53729. }
  53730. else {
  53731. return;
  53732. }
  53733. this._epsilon = epsilon;
  53734. this._scene = scene;
  53735. this._scene.spriteManagers.push(this);
  53736. var indices = [];
  53737. var index = 0;
  53738. for (var count = 0; count < capacity; count++) {
  53739. indices.push(index);
  53740. indices.push(index + 1);
  53741. indices.push(index + 2);
  53742. indices.push(index);
  53743. indices.push(index + 2);
  53744. indices.push(index + 3);
  53745. index += 4;
  53746. }
  53747. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  53748. // VBO
  53749. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  53750. this._vertexData = new Float32Array(capacity * 16 * 4);
  53751. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  53752. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  53753. var options = this._buffer.createVertexBuffer("options", 4, 4);
  53754. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  53755. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  53756. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  53757. this._vertexBuffers["options"] = options;
  53758. this._vertexBuffers["cellInfo"] = cellInfo;
  53759. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  53760. // Effects
  53761. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  53762. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  53763. }
  53764. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  53765. set: function (callback) {
  53766. if (this._onDisposeObserver) {
  53767. this.onDisposeObservable.remove(this._onDisposeObserver);
  53768. }
  53769. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  53770. },
  53771. enumerable: true,
  53772. configurable: true
  53773. });
  53774. Object.defineProperty(SpriteManager.prototype, "texture", {
  53775. get: function () {
  53776. return this._spriteTexture;
  53777. },
  53778. set: function (value) {
  53779. this._spriteTexture = value;
  53780. },
  53781. enumerable: true,
  53782. configurable: true
  53783. });
  53784. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  53785. var arrayOffset = index * 16;
  53786. if (offsetX === 0)
  53787. offsetX = this._epsilon;
  53788. else if (offsetX === 1)
  53789. offsetX = 1 - this._epsilon;
  53790. if (offsetY === 0)
  53791. offsetY = this._epsilon;
  53792. else if (offsetY === 1)
  53793. offsetY = 1 - this._epsilon;
  53794. this._vertexData[arrayOffset] = sprite.position.x;
  53795. this._vertexData[arrayOffset + 1] = sprite.position.y;
  53796. this._vertexData[arrayOffset + 2] = sprite.position.z;
  53797. this._vertexData[arrayOffset + 3] = sprite.angle;
  53798. this._vertexData[arrayOffset + 4] = sprite.width;
  53799. this._vertexData[arrayOffset + 5] = sprite.height;
  53800. this._vertexData[arrayOffset + 6] = offsetX;
  53801. this._vertexData[arrayOffset + 7] = offsetY;
  53802. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  53803. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  53804. var offset = (sprite.cellIndex / rowSize) >> 0;
  53805. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  53806. this._vertexData[arrayOffset + 11] = offset;
  53807. // Color
  53808. this._vertexData[arrayOffset + 12] = sprite.color.r;
  53809. this._vertexData[arrayOffset + 13] = sprite.color.g;
  53810. this._vertexData[arrayOffset + 14] = sprite.color.b;
  53811. this._vertexData[arrayOffset + 15] = sprite.color.a;
  53812. };
  53813. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  53814. var count = Math.min(this._capacity, this.sprites.length);
  53815. var min = BABYLON.Vector3.Zero();
  53816. var max = BABYLON.Vector3.Zero();
  53817. var distance = Number.MAX_VALUE;
  53818. var currentSprite = null;
  53819. var cameraSpacePosition = BABYLON.Vector3.Zero();
  53820. var cameraView = camera.getViewMatrix();
  53821. for (var index = 0; index < count; index++) {
  53822. var sprite = this.sprites[index];
  53823. if (!sprite) {
  53824. continue;
  53825. }
  53826. if (predicate) {
  53827. if (!predicate(sprite)) {
  53828. continue;
  53829. }
  53830. }
  53831. else if (!sprite.isPickable) {
  53832. continue;
  53833. }
  53834. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  53835. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  53836. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  53837. if (ray.intersectsBoxMinMax(min, max)) {
  53838. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  53839. if (distance > currentDistance) {
  53840. distance = currentDistance;
  53841. currentSprite = sprite;
  53842. if (fastCheck) {
  53843. break;
  53844. }
  53845. }
  53846. }
  53847. }
  53848. if (currentSprite) {
  53849. var result = new BABYLON.PickingInfo();
  53850. result.hit = true;
  53851. result.pickedSprite = currentSprite;
  53852. result.distance = distance;
  53853. return result;
  53854. }
  53855. return null;
  53856. };
  53857. SpriteManager.prototype.render = function () {
  53858. // Check
  53859. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  53860. return;
  53861. var engine = this._scene.getEngine();
  53862. var baseSize = this._spriteTexture.getBaseSize();
  53863. // Sprites
  53864. var deltaTime = engine.getDeltaTime();
  53865. var max = Math.min(this._capacity, this.sprites.length);
  53866. var rowSize = baseSize.width / this.cellWidth;
  53867. var offset = 0;
  53868. for (var index = 0; index < max; index++) {
  53869. var sprite = this.sprites[index];
  53870. if (!sprite || !sprite.isVisible) {
  53871. continue;
  53872. }
  53873. sprite._animate(deltaTime);
  53874. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  53875. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  53876. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  53877. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  53878. }
  53879. this._buffer.update(this._vertexData);
  53880. // Render
  53881. var effect = this._effectBase;
  53882. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53883. effect = this._effectFog;
  53884. }
  53885. engine.enableEffect(effect);
  53886. var viewMatrix = this._scene.getViewMatrix();
  53887. effect.setTexture("diffuseSampler", this._spriteTexture);
  53888. effect.setMatrix("view", viewMatrix);
  53889. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  53890. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  53891. // Fog
  53892. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53893. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  53894. effect.setColor3("vFogColor", this._scene.fogColor);
  53895. }
  53896. // VBOs
  53897. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  53898. // Draw order
  53899. engine.setDepthFunctionToLessOrEqual();
  53900. effect.setBool("alphaTest", true);
  53901. engine.setColorWrite(false);
  53902. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  53903. engine.setColorWrite(true);
  53904. effect.setBool("alphaTest", false);
  53905. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  53906. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  53907. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  53908. };
  53909. SpriteManager.prototype.dispose = function () {
  53910. if (this._buffer) {
  53911. this._buffer.dispose();
  53912. this._buffer = null;
  53913. }
  53914. if (this._indexBuffer) {
  53915. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  53916. this._indexBuffer = null;
  53917. }
  53918. if (this._spriteTexture) {
  53919. this._spriteTexture.dispose();
  53920. this._spriteTexture = null;
  53921. }
  53922. // Remove from scene
  53923. var index = this._scene.spriteManagers.indexOf(this);
  53924. this._scene.spriteManagers.splice(index, 1);
  53925. // Callback
  53926. this.onDisposeObservable.notifyObservers(this);
  53927. this.onDisposeObservable.clear();
  53928. };
  53929. return SpriteManager;
  53930. }());
  53931. BABYLON.SpriteManager = SpriteManager;
  53932. })(BABYLON || (BABYLON = {}));
  53933. //# sourceMappingURL=babylon.spriteManager.js.map
  53934. var BABYLON;
  53935. (function (BABYLON) {
  53936. var Sprite = /** @class */ (function () {
  53937. function Sprite(name, manager) {
  53938. this.name = name;
  53939. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53940. this.width = 1.0;
  53941. this.height = 1.0;
  53942. this.angle = 0;
  53943. this.cellIndex = 0;
  53944. this.invertU = 0;
  53945. this.invertV = 0;
  53946. this.animations = new Array();
  53947. this.isPickable = false;
  53948. this._animationStarted = false;
  53949. this._loopAnimation = false;
  53950. this._fromIndex = 0;
  53951. this._toIndex = 0;
  53952. this._delay = 0;
  53953. this._direction = 1;
  53954. this._time = 0;
  53955. /**
  53956. * Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true
  53957. */
  53958. this.isVisible = true;
  53959. this._manager = manager;
  53960. this._manager.sprites.push(this);
  53961. this.position = BABYLON.Vector3.Zero();
  53962. }
  53963. Object.defineProperty(Sprite.prototype, "size", {
  53964. get: function () {
  53965. return this.width;
  53966. },
  53967. set: function (value) {
  53968. this.width = value;
  53969. this.height = value;
  53970. },
  53971. enumerable: true,
  53972. configurable: true
  53973. });
  53974. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  53975. this._fromIndex = from;
  53976. this._toIndex = to;
  53977. this._loopAnimation = loop;
  53978. this._delay = delay;
  53979. this._animationStarted = true;
  53980. this._direction = from < to ? 1 : -1;
  53981. this.cellIndex = from;
  53982. this._time = 0;
  53983. this._onAnimationEnd = onAnimationEnd;
  53984. };
  53985. Sprite.prototype.stopAnimation = function () {
  53986. this._animationStarted = false;
  53987. };
  53988. /** @hidden */
  53989. Sprite.prototype._animate = function (deltaTime) {
  53990. if (!this._animationStarted)
  53991. return;
  53992. this._time += deltaTime;
  53993. if (this._time > this._delay) {
  53994. this._time = this._time % this._delay;
  53995. this.cellIndex += this._direction;
  53996. if (this.cellIndex > this._toIndex) {
  53997. if (this._loopAnimation) {
  53998. this.cellIndex = this._fromIndex;
  53999. }
  54000. else {
  54001. this.cellIndex = this._toIndex;
  54002. this._animationStarted = false;
  54003. if (this._onAnimationEnd) {
  54004. this._onAnimationEnd();
  54005. }
  54006. if (this.disposeWhenFinishedAnimating) {
  54007. this.dispose();
  54008. }
  54009. }
  54010. }
  54011. }
  54012. };
  54013. Sprite.prototype.dispose = function () {
  54014. for (var i = 0; i < this._manager.sprites.length; i++) {
  54015. if (this._manager.sprites[i] == this) {
  54016. this._manager.sprites.splice(i, 1);
  54017. }
  54018. }
  54019. };
  54020. return Sprite;
  54021. }());
  54022. BABYLON.Sprite = Sprite;
  54023. })(BABYLON || (BABYLON = {}));
  54024. //# sourceMappingURL=babylon.sprite.js.map
  54025. var BABYLON;
  54026. (function (BABYLON) {
  54027. BABYLON.Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  54028. if (!BABYLON.PickingInfo) {
  54029. return null;
  54030. }
  54031. var pickingInfo = null;
  54032. if (!camera) {
  54033. if (!this.activeCamera) {
  54034. return null;
  54035. }
  54036. camera = this.activeCamera;
  54037. }
  54038. if (this.spriteManagers.length > 0) {
  54039. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  54040. var spriteManager = this.spriteManagers[spriteIndex];
  54041. if (!spriteManager.isPickable) {
  54042. continue;
  54043. }
  54044. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  54045. if (!result || !result.hit)
  54046. continue;
  54047. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  54048. continue;
  54049. pickingInfo = result;
  54050. if (fastCheck) {
  54051. break;
  54052. }
  54053. }
  54054. }
  54055. return pickingInfo || new BABYLON.PickingInfo();
  54056. };
  54057. BABYLON.Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  54058. this.createPickingRayInCameraSpaceToRef(x, y, this._tempSpritePickingRay, camera);
  54059. return this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera);
  54060. };
  54061. BABYLON.Scene.prototype.pickSpriteWithRay = function (ray, predicate, fastCheck, camera) {
  54062. if (!this._tempSpritePickingRay) {
  54063. return null;
  54064. }
  54065. if (!camera) {
  54066. if (!this.activeCamera) {
  54067. return null;
  54068. }
  54069. camera = this.activeCamera;
  54070. }
  54071. BABYLON.Ray.TransformToRef(ray, camera.getViewMatrix(), this._tempSpritePickingRay);
  54072. return this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera);
  54073. };
  54074. BABYLON.Scene.prototype.setPointerOverSprite = function (sprite) {
  54075. if (this._pointerOverSprite === sprite) {
  54076. return;
  54077. }
  54078. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  54079. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  54080. }
  54081. this._pointerOverSprite = sprite;
  54082. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  54083. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  54084. }
  54085. };
  54086. BABYLON.Scene.prototype.getPointerOverSprite = function () {
  54087. return this._pointerOverSprite;
  54088. };
  54089. /**
  54090. * Defines the sprite scene component responsible to manage sprites
  54091. * in a given scene.
  54092. */
  54093. var SpriteSceneComponent = /** @class */ (function () {
  54094. /**
  54095. * Creates a new instance of the component for the given scene
  54096. * @param scene Defines the scene to register the component in
  54097. */
  54098. function SpriteSceneComponent(scene) {
  54099. /**
  54100. * The component name helpfull to identify the component in the list of scene components.
  54101. */
  54102. this.name = BABYLON.SceneComponentConstants.NAME_SPRITE;
  54103. this.scene = scene;
  54104. this.scene.spriteManagers = new Array();
  54105. this.scene._tempSpritePickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  54106. this.scene.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  54107. this.scene.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  54108. this._spritePredicate = function (sprite) {
  54109. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  54110. };
  54111. }
  54112. /**
  54113. * Registers the component in a given scene
  54114. */
  54115. SpriteSceneComponent.prototype.register = function () {
  54116. this.scene._pointerMoveStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERMOVE_SPRITE, this, this._pointerMove);
  54117. this.scene._pointerDownStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERDOWN_SPRITE, this, this._pointerDown);
  54118. this.scene._pointerUpStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERUP_SPRITE, this, this._pointerUp);
  54119. };
  54120. /**
  54121. * Rebuilds the elements related to this component in case of
  54122. * context lost for instance.
  54123. */
  54124. SpriteSceneComponent.prototype.rebuild = function () {
  54125. /** Nothing to do for sprites */
  54126. };
  54127. /**
  54128. * Disposes the component and the associated ressources.
  54129. */
  54130. SpriteSceneComponent.prototype.dispose = function () {
  54131. this.scene.onBeforeSpritesRenderingObservable.clear();
  54132. this.scene.onAfterSpritesRenderingObservable.clear();
  54133. var spriteManagers = this.scene.spriteManagers;
  54134. while (spriteManagers.length) {
  54135. spriteManagers[0].dispose();
  54136. }
  54137. };
  54138. SpriteSceneComponent.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, fastCheck, camera) {
  54139. var result = this.scene.pickSprite(x, y, this._spritePredicate, fastCheck, camera);
  54140. if (result) {
  54141. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  54142. }
  54143. return result;
  54144. };
  54145. SpriteSceneComponent.prototype._pointerMove = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, isMeshPicked, canvas) {
  54146. var scene = this.scene;
  54147. if (isMeshPicked) {
  54148. scene.setPointerOverSprite(null);
  54149. }
  54150. else {
  54151. pickResult = this._pickSpriteButKeepRay(pickResult, unTranslatedPointerX, unTranslatedPointerY, false, scene.cameraToUseForPointers || undefined);
  54152. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  54153. scene.setPointerOverSprite(pickResult.pickedSprite);
  54154. if (scene._pointerOverSprite && scene._pointerOverSprite.actionManager && scene._pointerOverSprite.actionManager.hoverCursor) {
  54155. canvas.style.cursor = scene._pointerOverSprite.actionManager.hoverCursor;
  54156. }
  54157. else {
  54158. canvas.style.cursor = scene.hoverCursor;
  54159. }
  54160. }
  54161. else {
  54162. scene.setPointerOverSprite(null);
  54163. }
  54164. }
  54165. return pickResult;
  54166. };
  54167. SpriteSceneComponent.prototype._pointerDown = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, evt) {
  54168. var scene = this.scene;
  54169. scene._pickedDownSprite = null;
  54170. if (scene.spriteManagers.length > 0) {
  54171. pickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined);
  54172. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  54173. if (pickResult.pickedSprite.actionManager) {
  54174. scene._pickedDownSprite = pickResult.pickedSprite;
  54175. switch (evt.button) {
  54176. case 0:
  54177. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  54178. break;
  54179. case 1:
  54180. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  54181. break;
  54182. case 2:
  54183. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  54184. break;
  54185. }
  54186. if (pickResult.pickedSprite.actionManager) {
  54187. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  54188. }
  54189. }
  54190. }
  54191. }
  54192. return pickResult;
  54193. };
  54194. SpriteSceneComponent.prototype._pointerUp = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, evt) {
  54195. var scene = this.scene;
  54196. if (scene.spriteManagers.length > 0) {
  54197. var spritePickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined);
  54198. if (spritePickResult) {
  54199. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  54200. if (spritePickResult.pickedSprite.actionManager) {
  54201. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));
  54202. if (spritePickResult.pickedSprite.actionManager) {
  54203. if (!this.scene._isPointerSwiping()) {
  54204. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));
  54205. }
  54206. }
  54207. }
  54208. }
  54209. if (scene._pickedDownSprite && scene._pickedDownSprite.actionManager && scene._pickedDownSprite !== spritePickResult.pickedSprite) {
  54210. scene._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(scene._pickedDownSprite, scene, evt));
  54211. }
  54212. }
  54213. }
  54214. return pickResult;
  54215. };
  54216. return SpriteSceneComponent;
  54217. }());
  54218. BABYLON.SpriteSceneComponent = SpriteSceneComponent;
  54219. })(BABYLON || (BABYLON = {}));
  54220. //# sourceMappingURL=babylon.spriteSceneComponent.js.map
  54221. var BABYLON;
  54222. (function (BABYLON) {
  54223. var IntersectionInfo = /** @class */ (function () {
  54224. function IntersectionInfo(bu, bv, distance) {
  54225. this.bu = bu;
  54226. this.bv = bv;
  54227. this.distance = distance;
  54228. this.faceId = 0;
  54229. this.subMeshId = 0;
  54230. }
  54231. return IntersectionInfo;
  54232. }());
  54233. BABYLON.IntersectionInfo = IntersectionInfo;
  54234. /**
  54235. * Information about the result of picking within a scene
  54236. * See https://doc.babylonjs.com/babylon101/picking_collisions
  54237. */
  54238. var PickingInfo = /** @class */ (function () {
  54239. function PickingInfo() {
  54240. /**
  54241. * If the pick collided with an object
  54242. */
  54243. this.hit = false;
  54244. /**
  54245. * Distance away where the pick collided
  54246. */
  54247. this.distance = 0;
  54248. /**
  54249. * The location of pick collision
  54250. */
  54251. this.pickedPoint = null;
  54252. /**
  54253. * The mesh corresponding the the pick collision
  54254. */
  54255. this.pickedMesh = null;
  54256. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  54257. this.bu = 0;
  54258. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  54259. this.bv = 0;
  54260. /** The id of the face on the mesh that was picked */
  54261. this.faceId = -1;
  54262. /** Id of the the submesh that was picked */
  54263. this.subMeshId = 0;
  54264. /** If a sprite was picked, this will be the sprite the pick collided with */
  54265. this.pickedSprite = null;
  54266. /**
  54267. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  54268. */
  54269. this.originMesh = null;
  54270. /**
  54271. * The ray that was used to perform the picking.
  54272. */
  54273. this.ray = null;
  54274. }
  54275. /**
  54276. * Gets the normal correspodning to the face the pick collided with
  54277. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  54278. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  54279. * @returns The normal correspodning to the face the pick collided with
  54280. */
  54281. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  54282. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  54283. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  54284. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  54285. return null;
  54286. }
  54287. var indices = this.pickedMesh.getIndices();
  54288. if (!indices) {
  54289. return null;
  54290. }
  54291. var result;
  54292. if (useVerticesNormals) {
  54293. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54294. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  54295. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  54296. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  54297. normal0 = normal0.scale(this.bu);
  54298. normal1 = normal1.scale(this.bv);
  54299. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  54300. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  54301. }
  54302. else {
  54303. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54304. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  54305. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  54306. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  54307. var p1p2 = vertex1.subtract(vertex2);
  54308. var p3p2 = vertex3.subtract(vertex2);
  54309. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  54310. }
  54311. if (useWorldCoordinates) {
  54312. var wm = this.pickedMesh.getWorldMatrix();
  54313. if (this.pickedMesh.nonUniformScaling) {
  54314. BABYLON.Tmp.Matrix[0].copyFrom(wm);
  54315. wm = BABYLON.Tmp.Matrix[0];
  54316. wm.setTranslationFromFloats(0, 0, 0);
  54317. wm.invert();
  54318. wm.transposeToRef(BABYLON.Tmp.Matrix[1]);
  54319. wm = BABYLON.Tmp.Matrix[1];
  54320. }
  54321. result = BABYLON.Vector3.TransformNormal(result, wm);
  54322. }
  54323. result.normalize();
  54324. return result;
  54325. };
  54326. /**
  54327. * Gets the texture coordinates of where the pick occured
  54328. * @returns the vector containing the coordnates of the texture
  54329. */
  54330. PickingInfo.prototype.getTextureCoordinates = function () {
  54331. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  54332. return null;
  54333. }
  54334. var indices = this.pickedMesh.getIndices();
  54335. if (!indices) {
  54336. return null;
  54337. }
  54338. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54339. if (!uvs) {
  54340. return null;
  54341. }
  54342. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  54343. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  54344. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  54345. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  54346. uv1 = uv1.scale(this.bu);
  54347. uv2 = uv2.scale(this.bv);
  54348. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  54349. };
  54350. return PickingInfo;
  54351. }());
  54352. BABYLON.PickingInfo = PickingInfo;
  54353. })(BABYLON || (BABYLON = {}));
  54354. //# sourceMappingURL=babylon.pickingInfo.js.map
  54355. var BABYLON;
  54356. (function (BABYLON) {
  54357. var Ray = /** @class */ (function () {
  54358. function Ray(origin, direction, length) {
  54359. if (length === void 0) { length = Number.MAX_VALUE; }
  54360. this.origin = origin;
  54361. this.direction = direction;
  54362. this.length = length;
  54363. }
  54364. // Methods
  54365. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  54366. var d = 0.0;
  54367. var maxValue = Number.MAX_VALUE;
  54368. var inv;
  54369. var min;
  54370. var max;
  54371. var temp;
  54372. if (Math.abs(this.direction.x) < 0.0000001) {
  54373. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  54374. return false;
  54375. }
  54376. }
  54377. else {
  54378. inv = 1.0 / this.direction.x;
  54379. min = (minimum.x - this.origin.x) * inv;
  54380. max = (maximum.x - this.origin.x) * inv;
  54381. if (max === -Infinity) {
  54382. max = Infinity;
  54383. }
  54384. if (min > max) {
  54385. temp = min;
  54386. min = max;
  54387. max = temp;
  54388. }
  54389. d = Math.max(min, d);
  54390. maxValue = Math.min(max, maxValue);
  54391. if (d > maxValue) {
  54392. return false;
  54393. }
  54394. }
  54395. if (Math.abs(this.direction.y) < 0.0000001) {
  54396. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  54397. return false;
  54398. }
  54399. }
  54400. else {
  54401. inv = 1.0 / this.direction.y;
  54402. min = (minimum.y - this.origin.y) * inv;
  54403. max = (maximum.y - this.origin.y) * inv;
  54404. if (max === -Infinity) {
  54405. max = Infinity;
  54406. }
  54407. if (min > max) {
  54408. temp = min;
  54409. min = max;
  54410. max = temp;
  54411. }
  54412. d = Math.max(min, d);
  54413. maxValue = Math.min(max, maxValue);
  54414. if (d > maxValue) {
  54415. return false;
  54416. }
  54417. }
  54418. if (Math.abs(this.direction.z) < 0.0000001) {
  54419. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  54420. return false;
  54421. }
  54422. }
  54423. else {
  54424. inv = 1.0 / this.direction.z;
  54425. min = (minimum.z - this.origin.z) * inv;
  54426. max = (maximum.z - this.origin.z) * inv;
  54427. if (max === -Infinity) {
  54428. max = Infinity;
  54429. }
  54430. if (min > max) {
  54431. temp = min;
  54432. min = max;
  54433. max = temp;
  54434. }
  54435. d = Math.max(min, d);
  54436. maxValue = Math.min(max, maxValue);
  54437. if (d > maxValue) {
  54438. return false;
  54439. }
  54440. }
  54441. return true;
  54442. };
  54443. Ray.prototype.intersectsBox = function (box) {
  54444. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  54445. };
  54446. Ray.prototype.intersectsSphere = function (sphere) {
  54447. var x = sphere.center.x - this.origin.x;
  54448. var y = sphere.center.y - this.origin.y;
  54449. var z = sphere.center.z - this.origin.z;
  54450. var pyth = (x * x) + (y * y) + (z * z);
  54451. var rr = sphere.radius * sphere.radius;
  54452. if (pyth <= rr) {
  54453. return true;
  54454. }
  54455. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  54456. if (dot < 0.0) {
  54457. return false;
  54458. }
  54459. var temp = pyth - (dot * dot);
  54460. return temp <= rr;
  54461. };
  54462. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  54463. if (!this._edge1) {
  54464. this._edge1 = BABYLON.Vector3.Zero();
  54465. this._edge2 = BABYLON.Vector3.Zero();
  54466. this._pvec = BABYLON.Vector3.Zero();
  54467. this._tvec = BABYLON.Vector3.Zero();
  54468. this._qvec = BABYLON.Vector3.Zero();
  54469. }
  54470. vertex1.subtractToRef(vertex0, this._edge1);
  54471. vertex2.subtractToRef(vertex0, this._edge2);
  54472. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  54473. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  54474. if (det === 0) {
  54475. return null;
  54476. }
  54477. var invdet = 1 / det;
  54478. this.origin.subtractToRef(vertex0, this._tvec);
  54479. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  54480. if (bu < 0 || bu > 1.0) {
  54481. return null;
  54482. }
  54483. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  54484. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  54485. if (bv < 0 || bu + bv > 1.0) {
  54486. return null;
  54487. }
  54488. //check if the distance is longer than the predefined length.
  54489. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  54490. if (distance > this.length) {
  54491. return null;
  54492. }
  54493. return new BABYLON.IntersectionInfo(bu, bv, distance);
  54494. };
  54495. Ray.prototype.intersectsPlane = function (plane) {
  54496. var distance;
  54497. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  54498. if (Math.abs(result1) < 9.99999997475243E-07) {
  54499. return null;
  54500. }
  54501. else {
  54502. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  54503. distance = (-plane.d - result2) / result1;
  54504. if (distance < 0.0) {
  54505. if (distance < -9.99999997475243E-07) {
  54506. return null;
  54507. }
  54508. else {
  54509. return 0;
  54510. }
  54511. }
  54512. return distance;
  54513. }
  54514. };
  54515. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  54516. var tm = BABYLON.Tmp.Matrix[0];
  54517. mesh.getWorldMatrix().invertToRef(tm);
  54518. if (this._tmpRay) {
  54519. Ray.TransformToRef(this, tm, this._tmpRay);
  54520. }
  54521. else {
  54522. this._tmpRay = Ray.Transform(this, tm);
  54523. }
  54524. return mesh.intersects(this._tmpRay, fastCheck);
  54525. };
  54526. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  54527. if (results) {
  54528. results.length = 0;
  54529. }
  54530. else {
  54531. results = [];
  54532. }
  54533. for (var i = 0; i < meshes.length; i++) {
  54534. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  54535. if (pickInfo.hit) {
  54536. results.push(pickInfo);
  54537. }
  54538. }
  54539. results.sort(this._comparePickingInfo);
  54540. return results;
  54541. };
  54542. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  54543. if (pickingInfoA.distance < pickingInfoB.distance) {
  54544. return -1;
  54545. }
  54546. else if (pickingInfoA.distance > pickingInfoB.distance) {
  54547. return 1;
  54548. }
  54549. else {
  54550. return 0;
  54551. }
  54552. };
  54553. /**
  54554. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  54555. * @param sega the first point of the segment to test the intersection against
  54556. * @param segb the second point of the segment to test the intersection against
  54557. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  54558. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  54559. */
  54560. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  54561. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  54562. var u = segb.subtract(sega);
  54563. var v = rsegb.subtract(this.origin);
  54564. var w = sega.subtract(this.origin);
  54565. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  54566. var b = BABYLON.Vector3.Dot(u, v);
  54567. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  54568. var d = BABYLON.Vector3.Dot(u, w);
  54569. var e = BABYLON.Vector3.Dot(v, w);
  54570. var D = a * c - b * b; // always >= 0
  54571. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  54572. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  54573. // compute the line parameters of the two closest points
  54574. if (D < Ray.smallnum) { // the lines are almost parallel
  54575. sN = 0.0; // force using point P0 on segment S1
  54576. sD = 1.0; // to prevent possible division by 0.0 later
  54577. tN = e;
  54578. tD = c;
  54579. }
  54580. else { // get the closest points on the infinite lines
  54581. sN = (b * e - c * d);
  54582. tN = (a * e - b * d);
  54583. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  54584. sN = 0.0;
  54585. tN = e;
  54586. tD = c;
  54587. }
  54588. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  54589. sN = sD;
  54590. tN = e + b;
  54591. tD = c;
  54592. }
  54593. }
  54594. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  54595. tN = 0.0;
  54596. // recompute sc for this edge
  54597. if (-d < 0.0) {
  54598. sN = 0.0;
  54599. }
  54600. else if (-d > a)
  54601. sN = sD;
  54602. else {
  54603. sN = -d;
  54604. sD = a;
  54605. }
  54606. }
  54607. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  54608. tN = tD;
  54609. // recompute sc for this edge
  54610. if ((-d + b) < 0.0) {
  54611. sN = 0;
  54612. }
  54613. else if ((-d + b) > a) {
  54614. sN = sD;
  54615. }
  54616. else {
  54617. sN = (-d + b);
  54618. sD = a;
  54619. }
  54620. }
  54621. // finally do the division to get sc and tc
  54622. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  54623. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  54624. // get the difference of the two closest points
  54625. var qtc = v.multiplyByFloats(tc, tc, tc);
  54626. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  54627. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  54628. if (isIntersected) {
  54629. return qtc.length();
  54630. }
  54631. return -1;
  54632. };
  54633. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54634. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  54635. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  54636. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  54637. this.direction.normalize();
  54638. return this;
  54639. };
  54640. // Statics
  54641. Ray.Zero = function () {
  54642. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  54643. };
  54644. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54645. var result = Ray.Zero();
  54646. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  54647. };
  54648. /**
  54649. * 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
  54650. * transformed to the given world matrix.
  54651. * @param origin The origin point
  54652. * @param end The end point
  54653. * @param world a matrix to transform the ray to. Default is the identity matrix.
  54654. */
  54655. Ray.CreateNewFromTo = function (origin, end, world) {
  54656. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  54657. var direction = end.subtract(origin);
  54658. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  54659. direction.normalize();
  54660. return Ray.Transform(new Ray(origin, direction, length), world);
  54661. };
  54662. Ray.Transform = function (ray, matrix) {
  54663. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  54664. Ray.TransformToRef(ray, matrix, result);
  54665. return result;
  54666. };
  54667. Ray.TransformToRef = function (ray, matrix, result) {
  54668. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  54669. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  54670. result.length = ray.length;
  54671. var dir = result.direction;
  54672. var len = dir.length();
  54673. if (!(len === 0 || len === 1)) {
  54674. var num = 1.0 / len;
  54675. dir.x *= num;
  54676. dir.y *= num;
  54677. dir.z *= num;
  54678. result.length *= len;
  54679. }
  54680. };
  54681. Ray.smallnum = 0.00000001;
  54682. Ray.rayl = 10e8;
  54683. return Ray;
  54684. }());
  54685. BABYLON.Ray = Ray;
  54686. })(BABYLON || (BABYLON = {}));
  54687. //# sourceMappingURL=babylon.ray.js.map
  54688. var BABYLON;
  54689. (function (BABYLON) {
  54690. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  54691. if (boxMin.x > sphereCenter.x + sphereRadius)
  54692. return false;
  54693. if (sphereCenter.x - sphereRadius > boxMax.x)
  54694. return false;
  54695. if (boxMin.y > sphereCenter.y + sphereRadius)
  54696. return false;
  54697. if (sphereCenter.y - sphereRadius > boxMax.y)
  54698. return false;
  54699. if (boxMin.z > sphereCenter.z + sphereRadius)
  54700. return false;
  54701. if (sphereCenter.z - sphereRadius > boxMax.z)
  54702. return false;
  54703. return true;
  54704. };
  54705. var getLowestRoot = (function () {
  54706. var result = { root: 0, found: false };
  54707. return function (a, b, c, maxR) {
  54708. result.root = 0;
  54709. result.found = false;
  54710. var determinant = b * b - 4.0 * a * c;
  54711. if (determinant < 0)
  54712. return result;
  54713. var sqrtD = Math.sqrt(determinant);
  54714. var r1 = (-b - sqrtD) / (2.0 * a);
  54715. var r2 = (-b + sqrtD) / (2.0 * a);
  54716. if (r1 > r2) {
  54717. var temp = r2;
  54718. r2 = r1;
  54719. r1 = temp;
  54720. }
  54721. if (r1 > 0 && r1 < maxR) {
  54722. result.root = r1;
  54723. result.found = true;
  54724. return result;
  54725. }
  54726. if (r2 > 0 && r2 < maxR) {
  54727. result.root = r2;
  54728. result.found = true;
  54729. return result;
  54730. }
  54731. return result;
  54732. };
  54733. })();
  54734. var Collider = /** @class */ (function () {
  54735. function Collider() {
  54736. this._collisionPoint = BABYLON.Vector3.Zero();
  54737. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  54738. this._tempVector = BABYLON.Vector3.Zero();
  54739. this._tempVector2 = BABYLON.Vector3.Zero();
  54740. this._tempVector3 = BABYLON.Vector3.Zero();
  54741. this._tempVector4 = BABYLON.Vector3.Zero();
  54742. this._edge = BABYLON.Vector3.Zero();
  54743. this._baseToVertex = BABYLON.Vector3.Zero();
  54744. this._destinationPoint = BABYLON.Vector3.Zero();
  54745. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  54746. this._displacementVector = BABYLON.Vector3.Zero();
  54747. /** @hidden */
  54748. this._radius = BABYLON.Vector3.One();
  54749. /** @hidden */
  54750. this._retry = 0;
  54751. /** @hidden */
  54752. this._basePointWorld = BABYLON.Vector3.Zero();
  54753. this._velocityWorld = BABYLON.Vector3.Zero();
  54754. this._normalizedVelocity = BABYLON.Vector3.Zero();
  54755. this._collisionMask = -1;
  54756. }
  54757. Object.defineProperty(Collider.prototype, "collisionMask", {
  54758. get: function () {
  54759. return this._collisionMask;
  54760. },
  54761. set: function (mask) {
  54762. this._collisionMask = !isNaN(mask) ? mask : -1;
  54763. },
  54764. enumerable: true,
  54765. configurable: true
  54766. });
  54767. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  54768. /**
  54769. * Gets the plane normal used to compute the sliding response (in local space)
  54770. */
  54771. get: function () {
  54772. return this._slidePlaneNormal;
  54773. },
  54774. enumerable: true,
  54775. configurable: true
  54776. });
  54777. // Methods
  54778. /** @hidden */
  54779. Collider.prototype._initialize = function (source, dir, e) {
  54780. this._velocity = dir;
  54781. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  54782. this._basePoint = source;
  54783. source.multiplyToRef(this._radius, this._basePointWorld);
  54784. dir.multiplyToRef(this._radius, this._velocityWorld);
  54785. this._velocityWorldLength = this._velocityWorld.length();
  54786. this._epsilon = e;
  54787. this.collisionFound = false;
  54788. };
  54789. /** @hidden */
  54790. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  54791. pa.subtractToRef(point, this._tempVector);
  54792. pb.subtractToRef(point, this._tempVector2);
  54793. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  54794. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54795. if (d < 0)
  54796. return false;
  54797. pc.subtractToRef(point, this._tempVector3);
  54798. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  54799. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54800. if (d < 0)
  54801. return false;
  54802. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  54803. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54804. return d >= 0;
  54805. };
  54806. /** @hidden */
  54807. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  54808. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  54809. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  54810. if (distance > this._velocityWorldLength + max + sphereRadius) {
  54811. return false;
  54812. }
  54813. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  54814. return false;
  54815. return true;
  54816. };
  54817. /** @hidden */
  54818. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  54819. var t0;
  54820. var embeddedInPlane = false;
  54821. //defensive programming, actually not needed.
  54822. if (!trianglePlaneArray) {
  54823. trianglePlaneArray = [];
  54824. }
  54825. if (!trianglePlaneArray[faceIndex]) {
  54826. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  54827. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  54828. }
  54829. var trianglePlane = trianglePlaneArray[faceIndex];
  54830. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  54831. return;
  54832. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  54833. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  54834. if (normalDotVelocity == 0) {
  54835. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  54836. return;
  54837. embeddedInPlane = true;
  54838. t0 = 0;
  54839. }
  54840. else {
  54841. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54842. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54843. if (t0 > t1) {
  54844. var temp = t1;
  54845. t1 = t0;
  54846. t0 = temp;
  54847. }
  54848. if (t0 > 1.0 || t1 < 0.0)
  54849. return;
  54850. if (t0 < 0)
  54851. t0 = 0;
  54852. if (t0 > 1.0)
  54853. t0 = 1.0;
  54854. }
  54855. this._collisionPoint.copyFromFloats(0, 0, 0);
  54856. var found = false;
  54857. var t = 1.0;
  54858. if (!embeddedInPlane) {
  54859. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  54860. this._velocity.scaleToRef(t0, this._tempVector);
  54861. this._planeIntersectionPoint.addInPlace(this._tempVector);
  54862. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  54863. found = true;
  54864. t = t0;
  54865. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  54866. }
  54867. }
  54868. if (!found) {
  54869. var velocitySquaredLength = this._velocity.lengthSquared();
  54870. var a = velocitySquaredLength;
  54871. this._basePoint.subtractToRef(p1, this._tempVector);
  54872. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54873. var c = this._tempVector.lengthSquared() - 1.0;
  54874. var lowestRoot = getLowestRoot(a, b, c, t);
  54875. if (lowestRoot.found) {
  54876. t = lowestRoot.root;
  54877. found = true;
  54878. this._collisionPoint.copyFrom(p1);
  54879. }
  54880. this._basePoint.subtractToRef(p2, this._tempVector);
  54881. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54882. c = this._tempVector.lengthSquared() - 1.0;
  54883. lowestRoot = getLowestRoot(a, b, c, t);
  54884. if (lowestRoot.found) {
  54885. t = lowestRoot.root;
  54886. found = true;
  54887. this._collisionPoint.copyFrom(p2);
  54888. }
  54889. this._basePoint.subtractToRef(p3, this._tempVector);
  54890. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54891. c = this._tempVector.lengthSquared() - 1.0;
  54892. lowestRoot = getLowestRoot(a, b, c, t);
  54893. if (lowestRoot.found) {
  54894. t = lowestRoot.root;
  54895. found = true;
  54896. this._collisionPoint.copyFrom(p3);
  54897. }
  54898. p2.subtractToRef(p1, this._edge);
  54899. p1.subtractToRef(this._basePoint, this._baseToVertex);
  54900. var edgeSquaredLength = this._edge.lengthSquared();
  54901. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54902. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54903. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54904. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54905. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54906. lowestRoot = getLowestRoot(a, b, c, t);
  54907. if (lowestRoot.found) {
  54908. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54909. if (f >= 0.0 && f <= 1.0) {
  54910. t = lowestRoot.root;
  54911. found = true;
  54912. this._edge.scaleInPlace(f);
  54913. p1.addToRef(this._edge, this._collisionPoint);
  54914. }
  54915. }
  54916. p3.subtractToRef(p2, this._edge);
  54917. p2.subtractToRef(this._basePoint, this._baseToVertex);
  54918. edgeSquaredLength = this._edge.lengthSquared();
  54919. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54920. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54921. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54922. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54923. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54924. lowestRoot = getLowestRoot(a, b, c, t);
  54925. if (lowestRoot.found) {
  54926. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54927. if (f >= 0.0 && f <= 1.0) {
  54928. t = lowestRoot.root;
  54929. found = true;
  54930. this._edge.scaleInPlace(f);
  54931. p2.addToRef(this._edge, this._collisionPoint);
  54932. }
  54933. }
  54934. p1.subtractToRef(p3, this._edge);
  54935. p3.subtractToRef(this._basePoint, this._baseToVertex);
  54936. edgeSquaredLength = this._edge.lengthSquared();
  54937. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54938. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54939. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54940. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54941. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54942. lowestRoot = getLowestRoot(a, b, c, t);
  54943. if (lowestRoot.found) {
  54944. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54945. if (f >= 0.0 && f <= 1.0) {
  54946. t = lowestRoot.root;
  54947. found = true;
  54948. this._edge.scaleInPlace(f);
  54949. p3.addToRef(this._edge, this._collisionPoint);
  54950. }
  54951. }
  54952. }
  54953. if (found) {
  54954. var distToCollision = t * this._velocity.length();
  54955. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  54956. if (!this.intersectionPoint) {
  54957. this.intersectionPoint = this._collisionPoint.clone();
  54958. }
  54959. else {
  54960. this.intersectionPoint.copyFrom(this._collisionPoint);
  54961. }
  54962. this._nearestDistance = distToCollision;
  54963. this.collisionFound = true;
  54964. }
  54965. }
  54966. };
  54967. /** @hidden */
  54968. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  54969. for (var i = indexStart; i < indexEnd; i += 3) {
  54970. var p1 = pts[indices[i] - decal];
  54971. var p2 = pts[indices[i + 1] - decal];
  54972. var p3 = pts[indices[i + 2] - decal];
  54973. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  54974. }
  54975. };
  54976. /** @hidden */
  54977. Collider.prototype._getResponse = function (pos, vel) {
  54978. pos.addToRef(vel, this._destinationPoint);
  54979. vel.scaleInPlace((this._nearestDistance / vel.length()));
  54980. this._basePoint.addToRef(vel, pos);
  54981. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  54982. this._slidePlaneNormal.normalize();
  54983. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  54984. pos.addInPlace(this._displacementVector);
  54985. this.intersectionPoint.addInPlace(this._displacementVector);
  54986. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  54987. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  54988. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  54989. };
  54990. return Collider;
  54991. }());
  54992. BABYLON.Collider = Collider;
  54993. })(BABYLON || (BABYLON = {}));
  54994. //# sourceMappingURL=babylon.collider.js.map
  54995. var BABYLON;
  54996. (function (BABYLON) {
  54997. //WebWorker code will be inserted to this variable.
  54998. BABYLON.CollisionWorker = "";
  54999. /** Defines supported task for worker process */
  55000. var WorkerTaskType;
  55001. (function (WorkerTaskType) {
  55002. /** Initialization */
  55003. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  55004. /** Update of geometry */
  55005. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  55006. /** Evaluate collision */
  55007. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  55008. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  55009. /** Defines kind of replies returned by worker */
  55010. var WorkerReplyType;
  55011. (function (WorkerReplyType) {
  55012. /** Success */
  55013. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  55014. /** Unkown error */
  55015. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  55016. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  55017. var CollisionCoordinatorWorker = /** @class */ (function () {
  55018. function CollisionCoordinatorWorker() {
  55019. var _this = this;
  55020. this._scaledPosition = BABYLON.Vector3.Zero();
  55021. this._scaledVelocity = BABYLON.Vector3.Zero();
  55022. this.onMeshUpdated = function (transformNode) {
  55023. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  55024. };
  55025. this.onGeometryUpdated = function (geometry) {
  55026. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  55027. };
  55028. this._afterRender = function () {
  55029. if (!_this._init)
  55030. return;
  55031. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  55032. return;
  55033. }
  55034. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  55035. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  55036. if (_this._runningUpdated > 4) {
  55037. return;
  55038. }
  55039. ++_this._runningUpdated;
  55040. var payload = {
  55041. updatedMeshes: _this._addUpdateMeshesList,
  55042. updatedGeometries: _this._addUpdateGeometriesList,
  55043. removedGeometries: _this._toRemoveGeometryArray,
  55044. removedMeshes: _this._toRemoveMeshesArray
  55045. };
  55046. var message = {
  55047. payload: payload,
  55048. taskType: WorkerTaskType.UPDATE
  55049. };
  55050. var serializable = [];
  55051. for (var id in payload.updatedGeometries) {
  55052. if (payload.updatedGeometries.hasOwnProperty(id)) {
  55053. //prepare transferables
  55054. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  55055. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  55056. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  55057. }
  55058. }
  55059. _this._worker.postMessage(message, serializable);
  55060. _this._addUpdateMeshesList = {};
  55061. _this._addUpdateGeometriesList = {};
  55062. _this._toRemoveGeometryArray = [];
  55063. _this._toRemoveMeshesArray = [];
  55064. };
  55065. this._onMessageFromWorker = function (e) {
  55066. var returnData = e.data;
  55067. if (returnData.error != WorkerReplyType.SUCCESS) {
  55068. //TODO what errors can be returned from the worker?
  55069. BABYLON.Tools.Warn("error returned from worker!");
  55070. return;
  55071. }
  55072. switch (returnData.taskType) {
  55073. case WorkerTaskType.INIT:
  55074. _this._init = true;
  55075. //Update the worked with ALL of the scene's current state
  55076. _this._scene.meshes.forEach(function (mesh) {
  55077. _this.onMeshAdded(mesh);
  55078. });
  55079. _this._scene.getGeometries().forEach(function (geometry) {
  55080. _this.onGeometryAdded(geometry);
  55081. });
  55082. break;
  55083. case WorkerTaskType.UPDATE:
  55084. _this._runningUpdated--;
  55085. break;
  55086. case WorkerTaskType.COLLIDE:
  55087. var returnPayload = returnData.payload;
  55088. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  55089. return;
  55090. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  55091. if (callback) {
  55092. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  55093. if (mesh) {
  55094. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  55095. }
  55096. }
  55097. //cleanup
  55098. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  55099. break;
  55100. }
  55101. };
  55102. this._collisionsCallbackArray = [];
  55103. this._init = false;
  55104. this._runningUpdated = 0;
  55105. this._addUpdateMeshesList = {};
  55106. this._addUpdateGeometriesList = {};
  55107. this._toRemoveGeometryArray = [];
  55108. this._toRemoveMeshesArray = [];
  55109. }
  55110. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55111. if (!this._init)
  55112. return;
  55113. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  55114. return;
  55115. position.divideToRef(collider._radius, this._scaledPosition);
  55116. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55117. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  55118. var payload = {
  55119. collider: {
  55120. position: this._scaledPosition.asArray(),
  55121. velocity: this._scaledVelocity.asArray(),
  55122. radius: collider._radius.asArray()
  55123. },
  55124. collisionId: collisionIndex,
  55125. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  55126. maximumRetry: maximumRetry
  55127. };
  55128. var message = {
  55129. payload: payload,
  55130. taskType: WorkerTaskType.COLLIDE
  55131. };
  55132. this._worker.postMessage(message);
  55133. };
  55134. CollisionCoordinatorWorker.prototype.init = function (scene) {
  55135. this._scene = scene;
  55136. this._scene.registerAfterRender(this._afterRender);
  55137. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  55138. this._worker = new Worker(workerUrl);
  55139. this._worker.onmessage = this._onMessageFromWorker;
  55140. var message = {
  55141. payload: {},
  55142. taskType: WorkerTaskType.INIT
  55143. };
  55144. this._worker.postMessage(message);
  55145. };
  55146. CollisionCoordinatorWorker.prototype.destroy = function () {
  55147. this._scene.unregisterAfterRender(this._afterRender);
  55148. this._worker.terminate();
  55149. };
  55150. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  55151. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  55152. this.onMeshUpdated(mesh);
  55153. };
  55154. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  55155. this._toRemoveMeshesArray.push(mesh.uniqueId);
  55156. };
  55157. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  55158. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  55159. geometry.onGeometryUpdated = this.onGeometryUpdated;
  55160. this.onGeometryUpdated(geometry);
  55161. };
  55162. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  55163. this._toRemoveGeometryArray.push(geometry.id);
  55164. };
  55165. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  55166. var submeshes = [];
  55167. if (mesh.subMeshes) {
  55168. submeshes = mesh.subMeshes.map(function (sm, idx) {
  55169. var boundingInfo = sm.getBoundingInfo();
  55170. return {
  55171. position: idx,
  55172. verticesStart: sm.verticesStart,
  55173. verticesCount: sm.verticesCount,
  55174. indexStart: sm.indexStart,
  55175. indexCount: sm.indexCount,
  55176. hasMaterial: !!sm.getMaterial(),
  55177. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55178. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55179. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55180. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  55181. };
  55182. });
  55183. }
  55184. var geometryId = null;
  55185. if (mesh instanceof BABYLON.Mesh) {
  55186. var geometry = mesh.geometry;
  55187. geometryId = geometry ? geometry.id : null;
  55188. }
  55189. else if (mesh instanceof BABYLON.InstancedMesh) {
  55190. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  55191. geometryId = geometry ? geometry.id : null;
  55192. }
  55193. var boundingInfo = mesh.getBoundingInfo();
  55194. return {
  55195. uniqueId: mesh.uniqueId,
  55196. id: mesh.id,
  55197. name: mesh.name,
  55198. geometryId: geometryId,
  55199. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55200. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55201. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55202. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  55203. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  55204. subMeshes: submeshes,
  55205. checkCollisions: mesh.checkCollisions
  55206. };
  55207. };
  55208. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  55209. return {
  55210. id: geometry.id,
  55211. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  55212. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  55213. indices: new Uint32Array(geometry.getIndices() || []),
  55214. };
  55215. };
  55216. return CollisionCoordinatorWorker;
  55217. }());
  55218. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  55219. var CollisionCoordinatorLegacy = /** @class */ (function () {
  55220. function CollisionCoordinatorLegacy() {
  55221. this._scaledPosition = BABYLON.Vector3.Zero();
  55222. this._scaledVelocity = BABYLON.Vector3.Zero();
  55223. this._finalPosition = BABYLON.Vector3.Zero();
  55224. }
  55225. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55226. position.divideToRef(collider._radius, this._scaledPosition);
  55227. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55228. collider.collidedMesh = null;
  55229. collider._retry = 0;
  55230. collider._initialVelocity = this._scaledVelocity;
  55231. collider._initialPosition = this._scaledPosition;
  55232. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  55233. this._finalPosition.multiplyInPlace(collider._radius);
  55234. //run the callback
  55235. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  55236. };
  55237. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  55238. this._scene = scene;
  55239. };
  55240. CollisionCoordinatorLegacy.prototype.destroy = function () {
  55241. //Legacy need no destruction method.
  55242. };
  55243. //No update in legacy mode
  55244. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  55245. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  55246. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  55247. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  55248. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  55249. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  55250. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  55251. if (excludedMesh === void 0) { excludedMesh = null; }
  55252. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  55253. if (collider._retry >= maximumRetry) {
  55254. finalPosition.copyFrom(position);
  55255. return;
  55256. }
  55257. // Check if this is a mesh else camera or -1
  55258. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  55259. collider._initialize(position, velocity, closeDistance);
  55260. // Check all meshes
  55261. for (var index = 0; index < this._scene.meshes.length; index++) {
  55262. var mesh = this._scene.meshes[index];
  55263. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  55264. mesh._checkCollision(collider);
  55265. }
  55266. }
  55267. if (!collider.collisionFound) {
  55268. position.addToRef(velocity, finalPosition);
  55269. return;
  55270. }
  55271. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  55272. collider._getResponse(position, velocity);
  55273. }
  55274. if (velocity.length() <= closeDistance) {
  55275. finalPosition.copyFrom(position);
  55276. return;
  55277. }
  55278. collider._retry++;
  55279. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  55280. };
  55281. return CollisionCoordinatorLegacy;
  55282. }());
  55283. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  55284. })(BABYLON || (BABYLON = {}));
  55285. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  55286. var BABYLON;
  55287. (function (BABYLON) {
  55288. /**
  55289. * A particle represents one of the element emitted by a particle system.
  55290. * This is mainly define by its coordinates, direction, velocity and age.
  55291. */
  55292. var Particle = /** @class */ (function () {
  55293. /**
  55294. * Creates a new instance Particle
  55295. * @param particleSystem the particle system the particle belongs to
  55296. */
  55297. function Particle(
  55298. /**
  55299. * The particle system the particle belongs to.
  55300. */
  55301. particleSystem) {
  55302. this.particleSystem = particleSystem;
  55303. /**
  55304. * The world position of the particle in the scene.
  55305. */
  55306. this.position = BABYLON.Vector3.Zero();
  55307. /**
  55308. * The world direction of the particle in the scene.
  55309. */
  55310. this.direction = BABYLON.Vector3.Zero();
  55311. /**
  55312. * The color of the particle.
  55313. */
  55314. this.color = new BABYLON.Color4(0, 0, 0, 0);
  55315. /**
  55316. * The color change of the particle per step.
  55317. */
  55318. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  55319. /**
  55320. * Defines how long will the life of the particle be.
  55321. */
  55322. this.lifeTime = 1.0;
  55323. /**
  55324. * The current age of the particle.
  55325. */
  55326. this.age = 0;
  55327. /**
  55328. * The current size of the particle.
  55329. */
  55330. this.size = 0;
  55331. /**
  55332. * The current scale of the particle.
  55333. */
  55334. this.scale = new BABYLON.Vector2(1, 1);
  55335. /**
  55336. * The current angle of the particle.
  55337. */
  55338. this.angle = 0;
  55339. /**
  55340. * Defines how fast is the angle changing.
  55341. */
  55342. this.angularSpeed = 0;
  55343. /**
  55344. * Defines the cell index used by the particle to be rendered from a sprite.
  55345. */
  55346. this.cellIndex = 0;
  55347. /** @hidden */
  55348. this._attachedSubEmitters = null;
  55349. /** @hidden */
  55350. this._currentColor1 = new BABYLON.Color4(0, 0, 0, 0);
  55351. /** @hidden */
  55352. this._currentColor2 = new BABYLON.Color4(0, 0, 0, 0);
  55353. /** @hidden */
  55354. this._currentSize1 = 0;
  55355. /** @hidden */
  55356. this._currentSize2 = 0;
  55357. /** @hidden */
  55358. this._currentAngularSpeed1 = 0;
  55359. /** @hidden */
  55360. this._currentAngularSpeed2 = 0;
  55361. /** @hidden */
  55362. this._currentVelocity1 = 0;
  55363. /** @hidden */
  55364. this._currentVelocity2 = 0;
  55365. /** @hidden */
  55366. this._currentLimitVelocity1 = 0;
  55367. /** @hidden */
  55368. this._currentLimitVelocity2 = 0;
  55369. /** @hidden */
  55370. this._currentDrag1 = 0;
  55371. /** @hidden */
  55372. this._currentDrag2 = 0;
  55373. this.id = Particle._Count++;
  55374. if (!this.particleSystem.isAnimationSheetEnabled) {
  55375. return;
  55376. }
  55377. this.updateCellInfoFromSystem();
  55378. }
  55379. Particle.prototype.updateCellInfoFromSystem = function () {
  55380. this.cellIndex = this.particleSystem.startSpriteCellID;
  55381. };
  55382. /**
  55383. * Defines how the sprite cell index is updated for the particle
  55384. */
  55385. Particle.prototype.updateCellIndex = function () {
  55386. var offsetAge = this.age;
  55387. if (this.particleSystem.spriteRandomStartCell) {
  55388. if (this._randomCellOffset === undefined) {
  55389. this._randomCellOffset = Math.random() * this.lifeTime;
  55390. }
  55391. offsetAge += this._randomCellOffset;
  55392. }
  55393. var dist = (this._initialEndSpriteCellID - this._initialStartSpriteCellID);
  55394. var ratio = BABYLON.Scalar.Clamp(((offsetAge * this.particleSystem.spriteCellChangeSpeed) % this.lifeTime) / this.lifeTime);
  55395. this.cellIndex = this._initialStartSpriteCellID + (ratio * dist) | 0;
  55396. };
  55397. /** @hidden */
  55398. Particle.prototype._reset = function () {
  55399. this.age = 0;
  55400. this._currentColorGradient = null;
  55401. this._currentSizeGradient = null;
  55402. this._currentAngularSpeedGradient = null;
  55403. this._currentVelocityGradient = null;
  55404. this._currentLimitVelocityGradient = null;
  55405. this._currentDragGradient = null;
  55406. this.cellIndex = this.particleSystem.startSpriteCellID;
  55407. this._randomCellOffset = undefined;
  55408. };
  55409. /**
  55410. * Copy the properties of particle to another one.
  55411. * @param other the particle to copy the information to.
  55412. */
  55413. Particle.prototype.copyTo = function (other) {
  55414. other.position.copyFrom(this.position);
  55415. if (this._initialDirection) {
  55416. if (other._initialDirection) {
  55417. other._initialDirection.copyFrom(this._initialDirection);
  55418. }
  55419. else {
  55420. other._initialDirection = this._initialDirection.clone();
  55421. }
  55422. }
  55423. else {
  55424. other._initialDirection = null;
  55425. }
  55426. other.direction.copyFrom(this.direction);
  55427. other.color.copyFrom(this.color);
  55428. other.colorStep.copyFrom(this.colorStep);
  55429. other.lifeTime = this.lifeTime;
  55430. other.age = this.age;
  55431. other._randomCellOffset = undefined;
  55432. other.size = this.size;
  55433. other.scale.copyFrom(this.scale);
  55434. other.angle = this.angle;
  55435. other.angularSpeed = this.angularSpeed;
  55436. other.particleSystem = this.particleSystem;
  55437. other.cellIndex = this.cellIndex;
  55438. other.id = this.id;
  55439. other._attachedSubEmitters = this._attachedSubEmitters;
  55440. if (this._currentColorGradient) {
  55441. other._currentColorGradient = this._currentColorGradient;
  55442. other._currentColor1.copyFrom(this._currentColor1);
  55443. other._currentColor2.copyFrom(this._currentColor2);
  55444. }
  55445. if (this._currentSizeGradient) {
  55446. other._currentSizeGradient = this._currentSizeGradient;
  55447. other._currentSize1 = this._currentSize1;
  55448. other._currentSize2 = this._currentSize2;
  55449. }
  55450. if (this._currentAngularSpeedGradient) {
  55451. other._currentAngularSpeedGradient = this._currentAngularSpeedGradient;
  55452. other._currentAngularSpeed1 = this._currentAngularSpeed1;
  55453. other._currentAngularSpeed2 = this._currentAngularSpeed2;
  55454. }
  55455. if (this._currentVelocityGradient) {
  55456. other._currentVelocityGradient = this._currentVelocityGradient;
  55457. other._currentVelocity1 = this._currentVelocity1;
  55458. other._currentVelocity2 = this._currentVelocity2;
  55459. }
  55460. if (this._currentLimitVelocityGradient) {
  55461. other._currentLimitVelocityGradient = this._currentLimitVelocityGradient;
  55462. other._currentLimitVelocity1 = this._currentLimitVelocity1;
  55463. other._currentLimitVelocity2 = this._currentLimitVelocity2;
  55464. }
  55465. if (this._currentDragGradient) {
  55466. other._currentDragGradient = this._currentDragGradient;
  55467. other._currentDrag1 = this._currentDrag1;
  55468. other._currentDrag2 = this._currentDrag2;
  55469. }
  55470. if (this.particleSystem.isAnimationSheetEnabled) {
  55471. other._initialStartSpriteCellID = this._initialStartSpriteCellID;
  55472. other._initialEndSpriteCellID = this._initialEndSpriteCellID;
  55473. }
  55474. if (this.particleSystem.useRampGradients) {
  55475. other.remapData.copyFrom(this.remapData);
  55476. }
  55477. };
  55478. Particle._Count = 0;
  55479. return Particle;
  55480. }());
  55481. BABYLON.Particle = Particle;
  55482. })(BABYLON || (BABYLON = {}));
  55483. //# sourceMappingURL=babylon.particle.js.map
  55484. var BABYLON;
  55485. (function (BABYLON) {
  55486. /**
  55487. * This represents the base class for particle system in Babylon.
  55488. * 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.
  55489. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  55490. * @example https://doc.babylonjs.com/babylon101/particles
  55491. */
  55492. var BaseParticleSystem = /** @class */ (function () {
  55493. /**
  55494. * Instantiates a particle system.
  55495. * 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.
  55496. * @param name The name of the particle system
  55497. */
  55498. function BaseParticleSystem(name) {
  55499. /**
  55500. * List of animations used by the particle system.
  55501. */
  55502. this.animations = [];
  55503. /**
  55504. * The rendering group used by the Particle system to chose when to render.
  55505. */
  55506. this.renderingGroupId = 0;
  55507. /**
  55508. * The emitter represents the Mesh or position we are attaching the particle system to.
  55509. */
  55510. this.emitter = null;
  55511. /**
  55512. * The maximum number of particles to emit per frame
  55513. */
  55514. this.emitRate = 10;
  55515. /**
  55516. * If you want to launch only a few particles at once, that can be done, as well.
  55517. */
  55518. this.manualEmitCount = -1;
  55519. /**
  55520. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  55521. */
  55522. this.updateSpeed = 0.01;
  55523. /**
  55524. * The amount of time the particle system is running (depends of the overall update speed).
  55525. */
  55526. this.targetStopDuration = 0;
  55527. /**
  55528. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  55529. */
  55530. this.disposeOnStop = false;
  55531. /**
  55532. * Minimum power of emitting particles.
  55533. */
  55534. this.minEmitPower = 1;
  55535. /**
  55536. * Maximum power of emitting particles.
  55537. */
  55538. this.maxEmitPower = 1;
  55539. /**
  55540. * Minimum life time of emitting particles.
  55541. */
  55542. this.minLifeTime = 1;
  55543. /**
  55544. * Maximum life time of emitting particles.
  55545. */
  55546. this.maxLifeTime = 1;
  55547. /**
  55548. * Minimum Size of emitting particles.
  55549. */
  55550. this.minSize = 1;
  55551. /**
  55552. * Maximum Size of emitting particles.
  55553. */
  55554. this.maxSize = 1;
  55555. /**
  55556. * Minimum scale of emitting particles on X axis.
  55557. */
  55558. this.minScaleX = 1;
  55559. /**
  55560. * Maximum scale of emitting particles on X axis.
  55561. */
  55562. this.maxScaleX = 1;
  55563. /**
  55564. * Minimum scale of emitting particles on Y axis.
  55565. */
  55566. this.minScaleY = 1;
  55567. /**
  55568. * Maximum scale of emitting particles on Y axis.
  55569. */
  55570. this.maxScaleY = 1;
  55571. /**
  55572. * Gets or sets the minimal initial rotation in radians.
  55573. */
  55574. this.minInitialRotation = 0;
  55575. /**
  55576. * Gets or sets the maximal initial rotation in radians.
  55577. */
  55578. this.maxInitialRotation = 0;
  55579. /**
  55580. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  55581. */
  55582. this.minAngularSpeed = 0;
  55583. /**
  55584. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  55585. */
  55586. this.maxAngularSpeed = 0;
  55587. /**
  55588. * The layer mask we are rendering the particles through.
  55589. */
  55590. this.layerMask = 0x0FFFFFFF;
  55591. /**
  55592. * This can help using your own shader to render the particle system.
  55593. * The according effect will be created
  55594. */
  55595. this.customShader = null;
  55596. /**
  55597. * By default particle system starts as soon as they are created. This prevents the
  55598. * automatic start to happen and let you decide when to start emitting particles.
  55599. */
  55600. this.preventAutoStart = false;
  55601. /** Gets or sets the strength to apply to the noise value (default is (10, 10, 10)) */
  55602. this.noiseStrength = new BABYLON.Vector3(10, 10, 10);
  55603. /**
  55604. * Callback triggered when the particle animation is ending.
  55605. */
  55606. this.onAnimationEnd = null;
  55607. /**
  55608. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  55609. */
  55610. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  55611. /**
  55612. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  55613. * to override the particles.
  55614. */
  55615. this.forceDepthWrite = false;
  55616. /** 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 */
  55617. this.preWarmCycles = 0;
  55618. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  55619. this.preWarmStepOffset = 1;
  55620. /**
  55621. * 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)
  55622. */
  55623. this.spriteCellChangeSpeed = 1;
  55624. /**
  55625. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  55626. */
  55627. this.startSpriteCellID = 0;
  55628. /**
  55629. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  55630. */
  55631. this.endSpriteCellID = 0;
  55632. /**
  55633. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  55634. */
  55635. this.spriteCellWidth = 0;
  55636. /**
  55637. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  55638. */
  55639. this.spriteCellHeight = 0;
  55640. /**
  55641. * This allows the system to random pick the start cell ID between startSpriteCellID and endSpriteCellID
  55642. */
  55643. this.spriteRandomStartCell = false;
  55644. /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */
  55645. this.translationPivot = new BABYLON.Vector2(0, 0);
  55646. /**
  55647. * You can use gravity if you want to give an orientation to your particles.
  55648. */
  55649. this.gravity = BABYLON.Vector3.Zero();
  55650. this._colorGradients = null;
  55651. this._sizeGradients = null;
  55652. this._lifeTimeGradients = null;
  55653. this._angularSpeedGradients = null;
  55654. this._velocityGradients = null;
  55655. this._limitVelocityGradients = null;
  55656. this._dragGradients = null;
  55657. this._emitRateGradients = null;
  55658. this._startSizeGradients = null;
  55659. this._rampGradients = null;
  55660. this._colorRemapGradients = null;
  55661. this._alphaRemapGradients = null;
  55662. /** Gets or sets a value indicating the damping to apply if the limit velocity factor is reached */
  55663. this.limitVelocityDamping = 0.4;
  55664. /**
  55665. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  55666. */
  55667. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55668. /**
  55669. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  55670. */
  55671. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55672. /**
  55673. * Color the particle will have at the end of its lifetime
  55674. */
  55675. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  55676. /**
  55677. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel
  55678. */
  55679. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55680. /**
  55681. * Gets or sets the billboard mode to use when isBillboardBased = true.
  55682. * Only BABYLON.AbstractMesh.BILLBOARDMODE_ALL and AbstractMesh.BILLBOARDMODE_Y are supported so far
  55683. */
  55684. this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  55685. this._isBillboardBased = true;
  55686. /**
  55687. * Local cache of defines for image processing.
  55688. */
  55689. this._imageProcessingConfigurationDefines = new BABYLON.ImageProcessingConfigurationDefines();
  55690. this.id = name;
  55691. this.name = name;
  55692. }
  55693. Object.defineProperty(BaseParticleSystem.prototype, "isAnimationSheetEnabled", {
  55694. /**
  55695. * Gets or sets whether an animation sprite sheet is enabled or not on the particle system
  55696. */
  55697. get: function () {
  55698. return this._isAnimationSheetEnabled;
  55699. },
  55700. set: function (value) {
  55701. if (this._isAnimationSheetEnabled == value) {
  55702. return;
  55703. }
  55704. this._isAnimationSheetEnabled = value;
  55705. this._reset();
  55706. },
  55707. enumerable: true,
  55708. configurable: true
  55709. });
  55710. /**
  55711. * Get hosting scene
  55712. * @returns the scene
  55713. */
  55714. BaseParticleSystem.prototype.getScene = function () {
  55715. return this._scene;
  55716. };
  55717. /**
  55718. * Gets the current list of drag gradients.
  55719. * You must use addDragGradient and removeDragGradient to udpate this list
  55720. * @returns the list of drag gradients
  55721. */
  55722. BaseParticleSystem.prototype.getDragGradients = function () {
  55723. return this._dragGradients;
  55724. };
  55725. /**
  55726. * Gets the current list of limit velocity gradients.
  55727. * You must use addLimitVelocityGradient and removeLimitVelocityGradient to udpate this list
  55728. * @returns the list of limit velocity gradients
  55729. */
  55730. BaseParticleSystem.prototype.getLimitVelocityGradients = function () {
  55731. return this._limitVelocityGradients;
  55732. };
  55733. /**
  55734. * Gets the current list of color gradients.
  55735. * You must use addColorGradient and removeColorGradient to udpate this list
  55736. * @returns the list of color gradients
  55737. */
  55738. BaseParticleSystem.prototype.getColorGradients = function () {
  55739. return this._colorGradients;
  55740. };
  55741. /**
  55742. * Gets the current list of size gradients.
  55743. * You must use addSizeGradient and removeSizeGradient to udpate this list
  55744. * @returns the list of size gradients
  55745. */
  55746. BaseParticleSystem.prototype.getSizeGradients = function () {
  55747. return this._sizeGradients;
  55748. };
  55749. /**
  55750. * Gets the current list of color remap gradients.
  55751. * You must use addColorRemapGradient and removeColorRemapGradient to udpate this list
  55752. * @returns the list of color remap gradients
  55753. */
  55754. BaseParticleSystem.prototype.getColorRemapGradients = function () {
  55755. return this._colorRemapGradients;
  55756. };
  55757. /**
  55758. * Gets the current list of alpha remap gradients.
  55759. * You must use addAlphaRemapGradient and removeAlphaRemapGradient to udpate this list
  55760. * @returns the list of alpha remap gradients
  55761. */
  55762. BaseParticleSystem.prototype.getAlphaRemapGradients = function () {
  55763. return this._alphaRemapGradients;
  55764. };
  55765. /**
  55766. * Gets the current list of life time gradients.
  55767. * You must use addLifeTimeGradient and removeLifeTimeGradient to udpate this list
  55768. * @returns the list of life time gradients
  55769. */
  55770. BaseParticleSystem.prototype.getLifeTimeGradients = function () {
  55771. return this._lifeTimeGradients;
  55772. };
  55773. /**
  55774. * Gets the current list of angular speed gradients.
  55775. * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list
  55776. * @returns the list of angular speed gradients
  55777. */
  55778. BaseParticleSystem.prototype.getAngularSpeedGradients = function () {
  55779. return this._angularSpeedGradients;
  55780. };
  55781. /**
  55782. * Gets the current list of velocity gradients.
  55783. * You must use addVelocityGradient and removeVelocityGradient to udpate this list
  55784. * @returns the list of velocity gradients
  55785. */
  55786. BaseParticleSystem.prototype.getVelocityGradients = function () {
  55787. return this._velocityGradients;
  55788. };
  55789. /**
  55790. * Gets the current list of start size gradients.
  55791. * You must use addStartSizeGradient and removeStartSizeGradient to udpate this list
  55792. * @returns the list of start size gradients
  55793. */
  55794. BaseParticleSystem.prototype.getStartSizeGradients = function () {
  55795. return this._startSizeGradients;
  55796. };
  55797. /**
  55798. * Gets the current list of emit rate gradients.
  55799. * You must use addEmitRateGradient and removeEmitRateGradient to udpate this list
  55800. * @returns the list of emit rate gradients
  55801. */
  55802. BaseParticleSystem.prototype.getEmitRateGradients = function () {
  55803. return this._emitRateGradients;
  55804. };
  55805. Object.defineProperty(BaseParticleSystem.prototype, "direction1", {
  55806. /**
  55807. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55808. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55809. */
  55810. get: function () {
  55811. if (this.particleEmitterType.direction1) {
  55812. return this.particleEmitterType.direction1;
  55813. }
  55814. return BABYLON.Vector3.Zero();
  55815. },
  55816. set: function (value) {
  55817. if (this.particleEmitterType.direction1) {
  55818. this.particleEmitterType.direction1 = value;
  55819. }
  55820. },
  55821. enumerable: true,
  55822. configurable: true
  55823. });
  55824. Object.defineProperty(BaseParticleSystem.prototype, "direction2", {
  55825. /**
  55826. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55827. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55828. */
  55829. get: function () {
  55830. if (this.particleEmitterType.direction2) {
  55831. return this.particleEmitterType.direction2;
  55832. }
  55833. return BABYLON.Vector3.Zero();
  55834. },
  55835. set: function (value) {
  55836. if (this.particleEmitterType.direction2) {
  55837. this.particleEmitterType.direction2 = value;
  55838. }
  55839. },
  55840. enumerable: true,
  55841. configurable: true
  55842. });
  55843. Object.defineProperty(BaseParticleSystem.prototype, "minEmitBox", {
  55844. /**
  55845. * Minimum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  55846. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55847. */
  55848. get: function () {
  55849. if (this.particleEmitterType.minEmitBox) {
  55850. return this.particleEmitterType.minEmitBox;
  55851. }
  55852. return BABYLON.Vector3.Zero();
  55853. },
  55854. set: function (value) {
  55855. if (this.particleEmitterType.minEmitBox) {
  55856. this.particleEmitterType.minEmitBox = value;
  55857. }
  55858. },
  55859. enumerable: true,
  55860. configurable: true
  55861. });
  55862. Object.defineProperty(BaseParticleSystem.prototype, "maxEmitBox", {
  55863. /**
  55864. * Maximum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  55865. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55866. */
  55867. get: function () {
  55868. if (this.particleEmitterType.maxEmitBox) {
  55869. return this.particleEmitterType.maxEmitBox;
  55870. }
  55871. return BABYLON.Vector3.Zero();
  55872. },
  55873. set: function (value) {
  55874. if (this.particleEmitterType.maxEmitBox) {
  55875. this.particleEmitterType.maxEmitBox = value;
  55876. }
  55877. },
  55878. enumerable: true,
  55879. configurable: true
  55880. });
  55881. Object.defineProperty(BaseParticleSystem.prototype, "isBillboardBased", {
  55882. /**
  55883. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  55884. */
  55885. get: function () {
  55886. return this._isBillboardBased;
  55887. },
  55888. set: function (value) {
  55889. if (this._isBillboardBased === value) {
  55890. return;
  55891. }
  55892. this._isBillboardBased = value;
  55893. this._reset();
  55894. },
  55895. enumerable: true,
  55896. configurable: true
  55897. });
  55898. Object.defineProperty(BaseParticleSystem.prototype, "imageProcessingConfiguration", {
  55899. /**
  55900. * Gets the image processing configuration used either in this material.
  55901. */
  55902. get: function () {
  55903. return this._imageProcessingConfiguration;
  55904. },
  55905. /**
  55906. * Sets the Default image processing configuration used either in the this material.
  55907. *
  55908. * If sets to null, the scene one is in use.
  55909. */
  55910. set: function (value) {
  55911. this._attachImageProcessingConfiguration(value);
  55912. },
  55913. enumerable: true,
  55914. configurable: true
  55915. });
  55916. /**
  55917. * Attaches a new image processing configuration to the Standard Material.
  55918. * @param configuration
  55919. */
  55920. BaseParticleSystem.prototype._attachImageProcessingConfiguration = function (configuration) {
  55921. if (configuration === this._imageProcessingConfiguration) {
  55922. return;
  55923. }
  55924. // Pick the scene configuration if needed.
  55925. if (!configuration) {
  55926. this._imageProcessingConfiguration = this._scene.imageProcessingConfiguration;
  55927. }
  55928. else {
  55929. this._imageProcessingConfiguration = configuration;
  55930. }
  55931. };
  55932. /** @hidden */
  55933. BaseParticleSystem.prototype._reset = function () {
  55934. };
  55935. /** @hidden */
  55936. BaseParticleSystem.prototype._removeGradientAndTexture = function (gradient, gradients, texture) {
  55937. if (!gradients) {
  55938. return this;
  55939. }
  55940. var index = 0;
  55941. for (var _i = 0, gradients_1 = gradients; _i < gradients_1.length; _i++) {
  55942. var valueGradient = gradients_1[_i];
  55943. if (valueGradient.gradient === gradient) {
  55944. gradients.splice(index, 1);
  55945. break;
  55946. }
  55947. index++;
  55948. }
  55949. if (texture) {
  55950. texture.dispose();
  55951. }
  55952. return this;
  55953. };
  55954. /**
  55955. * Creates a Point Emitter for the particle system (emits directly from the emitter position)
  55956. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  55957. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  55958. * @returns the emitter
  55959. */
  55960. BaseParticleSystem.prototype.createPointEmitter = function (direction1, direction2) {
  55961. var particleEmitter = new BABYLON.PointParticleEmitter();
  55962. particleEmitter.direction1 = direction1;
  55963. particleEmitter.direction2 = direction2;
  55964. this.particleEmitterType = particleEmitter;
  55965. return particleEmitter;
  55966. };
  55967. /**
  55968. * Creates a Hemisphere Emitter for the particle system (emits along the hemisphere radius)
  55969. * @param radius The radius of the hemisphere to emit from
  55970. * @param radiusRange The range of the hemisphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  55971. * @returns the emitter
  55972. */
  55973. BaseParticleSystem.prototype.createHemisphericEmitter = function (radius, radiusRange) {
  55974. if (radius === void 0) { radius = 1; }
  55975. if (radiusRange === void 0) { radiusRange = 1; }
  55976. var particleEmitter = new BABYLON.HemisphericParticleEmitter(radius, radiusRange);
  55977. this.particleEmitterType = particleEmitter;
  55978. return particleEmitter;
  55979. };
  55980. /**
  55981. * Creates a Sphere Emitter for the particle system (emits along the sphere radius)
  55982. * @param radius The radius of the sphere to emit from
  55983. * @param radiusRange The range of the sphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  55984. * @returns the emitter
  55985. */
  55986. BaseParticleSystem.prototype.createSphereEmitter = function (radius, radiusRange) {
  55987. if (radius === void 0) { radius = 1; }
  55988. if (radiusRange === void 0) { radiusRange = 1; }
  55989. var particleEmitter = new BABYLON.SphereParticleEmitter(radius, radiusRange);
  55990. this.particleEmitterType = particleEmitter;
  55991. return particleEmitter;
  55992. };
  55993. /**
  55994. * Creates a Directed Sphere Emitter for the particle system (emits between direction1 and direction2)
  55995. * @param radius The radius of the sphere to emit from
  55996. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  55997. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  55998. * @returns the emitter
  55999. */
  56000. BaseParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  56001. if (radius === void 0) { radius = 1; }
  56002. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  56003. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  56004. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  56005. this.particleEmitterType = particleEmitter;
  56006. return particleEmitter;
  56007. };
  56008. /**
  56009. * Creates a Cylinder Emitter for the particle system (emits from the cylinder to the particle position)
  56010. * @param radius The radius of the emission cylinder
  56011. * @param height The height of the emission cylinder
  56012. * @param radiusRange The range of emission [0-1] 0 Surface only, 1 Entire Radius
  56013. * @param directionRandomizer How much to randomize the particle direction [0-1]
  56014. * @returns the emitter
  56015. */
  56016. BaseParticleSystem.prototype.createCylinderEmitter = function (radius, height, radiusRange, directionRandomizer) {
  56017. if (radius === void 0) { radius = 1; }
  56018. if (height === void 0) { height = 1; }
  56019. if (radiusRange === void 0) { radiusRange = 1; }
  56020. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56021. var particleEmitter = new BABYLON.CylinderParticleEmitter(radius, height, radiusRange, directionRandomizer);
  56022. this.particleEmitterType = particleEmitter;
  56023. return particleEmitter;
  56024. };
  56025. /**
  56026. * Creates a Directed Cylinder Emitter for the particle system (emits between direction1 and direction2)
  56027. * @param radius The radius of the cylinder to emit from
  56028. * @param height The height of the emission cylinder
  56029. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  56030. * @param direction1 Particles are emitted between the direction1 and direction2 from within the cylinder
  56031. * @param direction2 Particles are emitted between the direction1 and direction2 from within the cylinder
  56032. * @returns the emitter
  56033. */
  56034. BaseParticleSystem.prototype.createDirectedCylinderEmitter = function (radius, height, radiusRange, direction1, direction2) {
  56035. if (radius === void 0) { radius = 1; }
  56036. if (height === void 0) { height = 1; }
  56037. if (radiusRange === void 0) { radiusRange = 1; }
  56038. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  56039. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  56040. var particleEmitter = new BABYLON.CylinderDirectedParticleEmitter(radius, height, radiusRange, direction1, direction2);
  56041. this.particleEmitterType = particleEmitter;
  56042. return particleEmitter;
  56043. };
  56044. /**
  56045. * Creates a Cone Emitter for the particle system (emits from the cone to the particle position)
  56046. * @param radius The radius of the cone to emit from
  56047. * @param angle The base angle of the cone
  56048. * @returns the emitter
  56049. */
  56050. BaseParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  56051. if (radius === void 0) { radius = 1; }
  56052. if (angle === void 0) { angle = Math.PI / 4; }
  56053. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  56054. this.particleEmitterType = particleEmitter;
  56055. return particleEmitter;
  56056. };
  56057. /**
  56058. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  56059. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  56060. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  56061. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56062. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56063. * @returns the emitter
  56064. */
  56065. BaseParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  56066. var particleEmitter = new BABYLON.BoxParticleEmitter();
  56067. this.particleEmitterType = particleEmitter;
  56068. this.direction1 = direction1;
  56069. this.direction2 = direction2;
  56070. this.minEmitBox = minEmitBox;
  56071. this.maxEmitBox = maxEmitBox;
  56072. return particleEmitter;
  56073. };
  56074. /**
  56075. * Source color is added to the destination color without alpha affecting the result.
  56076. */
  56077. BaseParticleSystem.BLENDMODE_ONEONE = 0;
  56078. /**
  56079. * Blend current color and particle color using particle’s alpha.
  56080. */
  56081. BaseParticleSystem.BLENDMODE_STANDARD = 1;
  56082. /**
  56083. * Add current color and particle color multiplied by particle’s alpha.
  56084. */
  56085. BaseParticleSystem.BLENDMODE_ADD = 2;
  56086. /**
  56087. * Multiply current color with particle color
  56088. */
  56089. BaseParticleSystem.BLENDMODE_MULTIPLY = 3;
  56090. return BaseParticleSystem;
  56091. }());
  56092. BABYLON.BaseParticleSystem = BaseParticleSystem;
  56093. })(BABYLON || (BABYLON = {}));
  56094. //# sourceMappingURL=babylon.baseParticleSystem.js.map
  56095. var BABYLON;
  56096. (function (BABYLON) {
  56097. /**
  56098. * This represents a particle system in Babylon.
  56099. * 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.
  56100. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  56101. * @example https://doc.babylonjs.com/babylon101/particles
  56102. */
  56103. var ParticleSystem = /** @class */ (function (_super) {
  56104. __extends(ParticleSystem, _super);
  56105. /**
  56106. * Instantiates a particle system.
  56107. * 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.
  56108. * @param name The name of the particle system
  56109. * @param capacity The max number of particles alive at the same time
  56110. * @param scene The scene the particle system belongs to
  56111. * @param customEffect a custom effect used to change the way particles are rendered by default
  56112. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  56113. * @param epsilon Offset used to render the particles
  56114. */
  56115. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  56116. if (customEffect === void 0) { customEffect = null; }
  56117. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  56118. if (epsilon === void 0) { epsilon = 0.01; }
  56119. var _this = _super.call(this, name) || this;
  56120. /**
  56121. * @hidden
  56122. */
  56123. _this._inheritedVelocityOffset = new BABYLON.Vector3();
  56124. /**
  56125. * An event triggered when the system is disposed
  56126. */
  56127. _this.onDisposeObservable = new BABYLON.Observable();
  56128. _this._particles = new Array();
  56129. _this._stockParticles = new Array();
  56130. _this._newPartsExcess = 0;
  56131. _this._vertexBuffers = {};
  56132. _this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  56133. _this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  56134. _this._scaledDirection = BABYLON.Vector3.Zero();
  56135. _this._scaledGravity = BABYLON.Vector3.Zero();
  56136. _this._currentRenderId = -1;
  56137. _this._useInstancing = false;
  56138. _this._started = false;
  56139. _this._stopped = false;
  56140. _this._actualFrame = 0;
  56141. /** @hidden */
  56142. _this._currentEmitRate1 = 0;
  56143. /** @hidden */
  56144. _this._currentEmitRate2 = 0;
  56145. /** @hidden */
  56146. _this._currentStartSize1 = 0;
  56147. /** @hidden */
  56148. _this._currentStartSize2 = 0;
  56149. _this._rawTextureWidth = 256;
  56150. _this._useRampGradients = false;
  56151. /**
  56152. * @hidden
  56153. * If the particle systems emitter should be disposed when the particle system is disposed
  56154. */
  56155. _this._disposeEmitterOnDispose = false;
  56156. // start of sub system methods
  56157. /**
  56158. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  56159. * Its lifetime will start back at 0.
  56160. */
  56161. _this.recycleParticle = function (particle) {
  56162. // move particle from activeParticle list to stock particles
  56163. var lastParticle = _this._particles.pop();
  56164. if (lastParticle !== particle) {
  56165. lastParticle.copyTo(particle);
  56166. }
  56167. _this._stockParticles.push(lastParticle);
  56168. };
  56169. _this._createParticle = function () {
  56170. var particle;
  56171. if (_this._stockParticles.length !== 0) {
  56172. particle = _this._stockParticles.pop();
  56173. particle._reset();
  56174. }
  56175. else {
  56176. particle = new BABYLON.Particle(_this);
  56177. }
  56178. // Attach emitters
  56179. if (_this._subEmitters && _this._subEmitters.length > 0) {
  56180. var subEmitters = _this._subEmitters[Math.floor(Math.random() * _this._subEmitters.length)];
  56181. particle._attachedSubEmitters = [];
  56182. subEmitters.forEach(function (subEmitter) {
  56183. if (subEmitter.type === BABYLON.SubEmitterType.ATTACHED) {
  56184. var newEmitter = subEmitter.clone();
  56185. particle._attachedSubEmitters.push(newEmitter);
  56186. newEmitter.particleSystem.start();
  56187. }
  56188. });
  56189. }
  56190. return particle;
  56191. };
  56192. _this._emitFromParticle = function (particle) {
  56193. if (!_this._subEmitters || _this._subEmitters.length === 0) {
  56194. return;
  56195. }
  56196. var templateIndex = Math.floor(Math.random() * _this._subEmitters.length);
  56197. _this._subEmitters[templateIndex].forEach(function (subEmitter) {
  56198. if (subEmitter.type === BABYLON.SubEmitterType.END) {
  56199. var subSystem = subEmitter.clone();
  56200. ParticleSystem._InheritParticleInfoToSubEmitter(subSystem, particle);
  56201. subSystem.particleSystem._rootParticleSystem = _this;
  56202. _this.activeSubSystems.push(subSystem.particleSystem);
  56203. subSystem.particleSystem.start();
  56204. }
  56205. });
  56206. };
  56207. _this._capacity = capacity;
  56208. _this._epsilon = epsilon;
  56209. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  56210. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  56211. // Setup the default processing configuration to the scene.
  56212. _this._attachImageProcessingConfiguration(null);
  56213. _this._customEffect = customEffect;
  56214. _this._scene.particleSystems.push(_this);
  56215. _this._useInstancing = _this._scene.getEngine().getCaps().instancedArrays;
  56216. _this._createIndexBuffer();
  56217. _this._createVertexBuffers();
  56218. // Default emitter type
  56219. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  56220. _this.updateFunction = function (particles) {
  56221. var noiseTextureData = null;
  56222. var noiseTextureSize = null;
  56223. if (_this.noiseTexture) { // We need to get texture data back to CPU
  56224. noiseTextureData = (_this.noiseTexture.readPixels());
  56225. noiseTextureSize = _this.noiseTexture.getSize();
  56226. }
  56227. var _loop_1 = function () {
  56228. particle = particles[index];
  56229. particle.age += _this._scaledUpdateSpeed;
  56230. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  56231. _this._emitFromParticle(particle);
  56232. if (particle._attachedSubEmitters) {
  56233. particle._attachedSubEmitters.forEach(function (subEmitter) {
  56234. subEmitter.particleSystem.disposeOnStop = true;
  56235. subEmitter.particleSystem.stop();
  56236. });
  56237. particle._attachedSubEmitters = null;
  56238. }
  56239. _this.recycleParticle(particle);
  56240. index--;
  56241. return "continue";
  56242. }
  56243. else {
  56244. var ratio = particle.age / particle.lifeTime;
  56245. // Color
  56246. if (_this._colorGradients && _this._colorGradients.length > 0) {
  56247. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorGradients, function (currentGradient, nextGradient, scale) {
  56248. if (currentGradient !== particle._currentColorGradient) {
  56249. particle._currentColor1.copyFrom(particle._currentColor2);
  56250. nextGradient.getColorToRef(particle._currentColor2);
  56251. particle._currentColorGradient = currentGradient;
  56252. }
  56253. BABYLON.Color4.LerpToRef(particle._currentColor1, particle._currentColor2, scale, particle.color);
  56254. });
  56255. }
  56256. else {
  56257. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  56258. particle.color.addInPlace(_this._scaledColorStep);
  56259. if (particle.color.a < 0) {
  56260. particle.color.a = 0;
  56261. }
  56262. }
  56263. // Angular speed
  56264. if (_this._angularSpeedGradients && _this._angularSpeedGradients.length > 0) {
  56265. BABYLON.Tools.GetCurrentGradient(ratio, _this._angularSpeedGradients, function (currentGradient, nextGradient, scale) {
  56266. if (currentGradient !== particle._currentAngularSpeedGradient) {
  56267. particle._currentAngularSpeed1 = particle._currentAngularSpeed2;
  56268. particle._currentAngularSpeed2 = nextGradient.getFactor();
  56269. particle._currentAngularSpeedGradient = currentGradient;
  56270. }
  56271. particle.angularSpeed = BABYLON.Scalar.Lerp(particle._currentAngularSpeed1, particle._currentAngularSpeed2, scale);
  56272. });
  56273. }
  56274. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  56275. // Direction
  56276. var directionScale_1 = _this._scaledUpdateSpeed;
  56277. /// Velocity
  56278. if (_this._velocityGradients && _this._velocityGradients.length > 0) {
  56279. BABYLON.Tools.GetCurrentGradient(ratio, _this._velocityGradients, function (currentGradient, nextGradient, scale) {
  56280. if (currentGradient !== particle._currentVelocityGradient) {
  56281. particle._currentVelocity1 = particle._currentVelocity2;
  56282. particle._currentVelocity2 = nextGradient.getFactor();
  56283. particle._currentVelocityGradient = currentGradient;
  56284. }
  56285. directionScale_1 *= BABYLON.Scalar.Lerp(particle._currentVelocity1, particle._currentVelocity2, scale);
  56286. });
  56287. }
  56288. particle.direction.scaleToRef(directionScale_1, _this._scaledDirection);
  56289. /// Limit velocity
  56290. if (_this._limitVelocityGradients && _this._limitVelocityGradients.length > 0) {
  56291. BABYLON.Tools.GetCurrentGradient(ratio, _this._limitVelocityGradients, function (currentGradient, nextGradient, scale) {
  56292. if (currentGradient !== particle._currentLimitVelocityGradient) {
  56293. particle._currentLimitVelocity1 = particle._currentLimitVelocity2;
  56294. particle._currentLimitVelocity2 = nextGradient.getFactor();
  56295. particle._currentLimitVelocityGradient = currentGradient;
  56296. }
  56297. var limitVelocity = BABYLON.Scalar.Lerp(particle._currentLimitVelocity1, particle._currentLimitVelocity2, scale);
  56298. var currentVelocity = particle.direction.length();
  56299. if (currentVelocity > limitVelocity) {
  56300. particle.direction.scaleInPlace(_this.limitVelocityDamping);
  56301. }
  56302. });
  56303. }
  56304. /// Drag
  56305. if (_this._dragGradients && _this._dragGradients.length > 0) {
  56306. BABYLON.Tools.GetCurrentGradient(ratio, _this._dragGradients, function (currentGradient, nextGradient, scale) {
  56307. if (currentGradient !== particle._currentDragGradient) {
  56308. particle._currentDrag1 = particle._currentDrag2;
  56309. particle._currentDrag2 = nextGradient.getFactor();
  56310. particle._currentDragGradient = currentGradient;
  56311. }
  56312. var drag = BABYLON.Scalar.Lerp(particle._currentDrag1, particle._currentDrag2, scale);
  56313. _this._scaledDirection.scaleInPlace(1.0 - drag);
  56314. });
  56315. }
  56316. particle.position.addInPlace(_this._scaledDirection);
  56317. // Noise
  56318. if (noiseTextureData && noiseTextureSize) {
  56319. var localPosition = BABYLON.Tmp.Vector3[0];
  56320. var emitterPosition = BABYLON.Tmp.Vector3[1];
  56321. _this._emitterWorldMatrix.getTranslationToRef(emitterPosition);
  56322. particle.position.subtractToRef(emitterPosition, localPosition);
  56323. var fetchedColorR = _this._fetchR(localPosition.y, localPosition.z, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  56324. var fetchedColorG = _this._fetchR(localPosition.x + 0.33, localPosition.z + 0.33, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  56325. var fetchedColorB = _this._fetchR(localPosition.x - 0.33, localPosition.y - 0.33, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  56326. var force = BABYLON.Tmp.Vector3[0];
  56327. var scaledForce = BABYLON.Tmp.Vector3[1];
  56328. force.copyFromFloats((2 * fetchedColorR - 1) * _this.noiseStrength.x, (2 * fetchedColorG - 1) * _this.noiseStrength.y, (2 * fetchedColorB - 1) * _this.noiseStrength.z);
  56329. force.scaleToRef(_this._scaledUpdateSpeed, scaledForce);
  56330. particle.direction.addInPlace(scaledForce);
  56331. }
  56332. // Gravity
  56333. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  56334. particle.direction.addInPlace(_this._scaledGravity);
  56335. // Size
  56336. if (_this._sizeGradients && _this._sizeGradients.length > 0) {
  56337. BABYLON.Tools.GetCurrentGradient(ratio, _this._sizeGradients, function (currentGradient, nextGradient, scale) {
  56338. if (currentGradient !== particle._currentSizeGradient) {
  56339. particle._currentSize1 = particle._currentSize2;
  56340. particle._currentSize2 = nextGradient.getFactor();
  56341. particle._currentSizeGradient = currentGradient;
  56342. }
  56343. particle.size = BABYLON.Scalar.Lerp(particle._currentSize1, particle._currentSize2, scale);
  56344. });
  56345. }
  56346. // Remap data
  56347. if (_this._useRampGradients) {
  56348. if (_this._colorRemapGradients && _this._colorRemapGradients.length > 0) {
  56349. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorRemapGradients, function (currentGradient, nextGradient, scale) {
  56350. var min = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  56351. var max = BABYLON.Scalar.Lerp(currentGradient.factor2, nextGradient.factor2, scale);
  56352. particle.remapData.x = min;
  56353. particle.remapData.y = max - min;
  56354. });
  56355. }
  56356. if (_this._alphaRemapGradients && _this._alphaRemapGradients.length > 0) {
  56357. BABYLON.Tools.GetCurrentGradient(ratio, _this._alphaRemapGradients, function (currentGradient, nextGradient, scale) {
  56358. var min = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  56359. var max = BABYLON.Scalar.Lerp(currentGradient.factor2, nextGradient.factor2, scale);
  56360. particle.remapData.z = min;
  56361. particle.remapData.w = max - min;
  56362. });
  56363. }
  56364. }
  56365. if (_this._isAnimationSheetEnabled) {
  56366. particle.updateCellIndex();
  56367. }
  56368. // Update the position of the attached sub-emitters to match their attached particle
  56369. if (particle._attachedSubEmitters && particle._attachedSubEmitters.length > 0) {
  56370. particle._attachedSubEmitters.forEach(function (subEmitter) {
  56371. ParticleSystem._InheritParticleInfoToSubEmitter(subEmitter, particle);
  56372. });
  56373. }
  56374. }
  56375. };
  56376. var particle;
  56377. for (var index = 0; index < particles.length; index++) {
  56378. _loop_1();
  56379. }
  56380. };
  56381. return _this;
  56382. }
  56383. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  56384. /**
  56385. * Sets a callback that will be triggered when the system is disposed
  56386. */
  56387. set: function (callback) {
  56388. if (this._onDisposeObserver) {
  56389. this.onDisposeObservable.remove(this._onDisposeObserver);
  56390. }
  56391. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  56392. },
  56393. enumerable: true,
  56394. configurable: true
  56395. });
  56396. Object.defineProperty(ParticleSystem.prototype, "useRampGradients", {
  56397. /** Gets or sets a boolean indicating that ramp gradients must be used
  56398. * @see http://doc.babylonjs.com/babylon101/particles#ramp-gradients
  56399. */
  56400. get: function () {
  56401. return this._useRampGradients;
  56402. },
  56403. set: function (value) {
  56404. if (this._useRampGradients === value) {
  56405. return;
  56406. }
  56407. this._useRampGradients = value;
  56408. this._resetEffect();
  56409. },
  56410. enumerable: true,
  56411. configurable: true
  56412. });
  56413. Object.defineProperty(ParticleSystem.prototype, "particles", {
  56414. //end of Sub-emitter
  56415. /**
  56416. * Gets the current list of active particles
  56417. */
  56418. get: function () {
  56419. return this._particles;
  56420. },
  56421. enumerable: true,
  56422. configurable: true
  56423. });
  56424. /**
  56425. * Returns the string "ParticleSystem"
  56426. * @returns a string containing the class name
  56427. */
  56428. ParticleSystem.prototype.getClassName = function () {
  56429. return "ParticleSystem";
  56430. };
  56431. ParticleSystem._InheritParticleInfoToSubEmitter = function (subEmitter, particle) {
  56432. if (subEmitter.particleSystem.emitter.position) {
  56433. var emitterMesh = subEmitter.particleSystem.emitter;
  56434. emitterMesh.position.copyFrom(particle.position);
  56435. if (subEmitter.inheritDirection) {
  56436. emitterMesh.position.subtractToRef(particle.direction, BABYLON.Tmp.Vector3[0]);
  56437. // Look at using Y as forward
  56438. emitterMesh.lookAt(BABYLON.Tmp.Vector3[0], 0, Math.PI / 2);
  56439. }
  56440. }
  56441. else {
  56442. var emitterPosition = subEmitter.particleSystem.emitter;
  56443. emitterPosition.copyFrom(particle.position);
  56444. if (subEmitter.inheritDirection) {
  56445. BABYLON.Tools.Warn("subEmitter.inheritDirection is not supported with non-mesh emitter type");
  56446. }
  56447. }
  56448. // Set inheritedVelocityOffset to be used when new particles are created
  56449. particle.direction.scaleToRef(subEmitter.inheritedVelocityAmount / 2, BABYLON.Tmp.Vector3[0]);
  56450. subEmitter.particleSystem._inheritedVelocityOffset.copyFrom(BABYLON.Tmp.Vector3[0]);
  56451. };
  56452. ParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor, factor2) {
  56453. var newGradient = new BABYLON.FactorGradient();
  56454. newGradient.gradient = gradient;
  56455. newGradient.factor1 = factor;
  56456. newGradient.factor2 = factor2;
  56457. factorGradients.push(newGradient);
  56458. factorGradients.sort(function (a, b) {
  56459. if (a.gradient < b.gradient) {
  56460. return -1;
  56461. }
  56462. else if (a.gradient > b.gradient) {
  56463. return 1;
  56464. }
  56465. return 0;
  56466. });
  56467. };
  56468. ParticleSystem.prototype._removeFactorGradient = function (factorGradients, gradient) {
  56469. if (!factorGradients) {
  56470. return;
  56471. }
  56472. var index = 0;
  56473. for (var _i = 0, factorGradients_1 = factorGradients; _i < factorGradients_1.length; _i++) {
  56474. var factorGradient = factorGradients_1[_i];
  56475. if (factorGradient.gradient === gradient) {
  56476. factorGradients.splice(index, 1);
  56477. break;
  56478. }
  56479. index++;
  56480. }
  56481. };
  56482. /**
  56483. * Adds a new life time gradient
  56484. * @param gradient defines the gradient to use (between 0 and 1)
  56485. * @param factor defines the life time factor to affect to the specified gradient
  56486. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56487. * @returns the current particle system
  56488. */
  56489. ParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  56490. if (!this._lifeTimeGradients) {
  56491. this._lifeTimeGradients = [];
  56492. }
  56493. this._addFactorGradient(this._lifeTimeGradients, gradient, factor, factor2);
  56494. return this;
  56495. };
  56496. /**
  56497. * Remove a specific life time gradient
  56498. * @param gradient defines the gradient to remove
  56499. * @returns the current particle system
  56500. */
  56501. ParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  56502. this._removeFactorGradient(this._lifeTimeGradients, gradient);
  56503. return this;
  56504. };
  56505. /**
  56506. * Adds a new size gradient
  56507. * @param gradient defines the gradient to use (between 0 and 1)
  56508. * @param factor defines the size factor to affect to the specified gradient
  56509. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56510. * @returns the current particle system
  56511. */
  56512. ParticleSystem.prototype.addSizeGradient = function (gradient, factor, factor2) {
  56513. if (!this._sizeGradients) {
  56514. this._sizeGradients = [];
  56515. }
  56516. this._addFactorGradient(this._sizeGradients, gradient, factor, factor2);
  56517. return this;
  56518. };
  56519. /**
  56520. * Remove a specific size gradient
  56521. * @param gradient defines the gradient to remove
  56522. * @returns the current particle system
  56523. */
  56524. ParticleSystem.prototype.removeSizeGradient = function (gradient) {
  56525. this._removeFactorGradient(this._sizeGradients, gradient);
  56526. return this;
  56527. };
  56528. /**
  56529. * Adds a new color remap gradient
  56530. * @param gradient defines the gradient to use (between 0 and 1)
  56531. * @param min defines the color remap minimal range
  56532. * @param max defines the color remap maximal range
  56533. * @returns the current particle system
  56534. */
  56535. ParticleSystem.prototype.addColorRemapGradient = function (gradient, min, max) {
  56536. if (!this._colorRemapGradients) {
  56537. this._colorRemapGradients = [];
  56538. }
  56539. this._addFactorGradient(this._colorRemapGradients, gradient, min, max);
  56540. return this;
  56541. };
  56542. /**
  56543. * Remove a specific color remap gradient
  56544. * @param gradient defines the gradient to remove
  56545. * @returns the current particle system
  56546. */
  56547. ParticleSystem.prototype.removeColorRemapGradient = function (gradient) {
  56548. this._removeFactorGradient(this._colorRemapGradients, gradient);
  56549. return this;
  56550. };
  56551. /**
  56552. * Adds a new alpha remap gradient
  56553. * @param gradient defines the gradient to use (between 0 and 1)
  56554. * @param min defines the alpha remap minimal range
  56555. * @param max defines the alpha remap maximal range
  56556. * @returns the current particle system
  56557. */
  56558. ParticleSystem.prototype.addAlphaRemapGradient = function (gradient, min, max) {
  56559. if (!this._alphaRemapGradients) {
  56560. this._alphaRemapGradients = [];
  56561. }
  56562. this._addFactorGradient(this._alphaRemapGradients, gradient, min, max);
  56563. return this;
  56564. };
  56565. /**
  56566. * Remove a specific alpha remap gradient
  56567. * @param gradient defines the gradient to remove
  56568. * @returns the current particle system
  56569. */
  56570. ParticleSystem.prototype.removeAlphaRemapGradient = function (gradient) {
  56571. this._removeFactorGradient(this._alphaRemapGradients, gradient);
  56572. return this;
  56573. };
  56574. /**
  56575. * Adds a new angular speed gradient
  56576. * @param gradient defines the gradient to use (between 0 and 1)
  56577. * @param factor defines the angular speed to affect to the specified gradient
  56578. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56579. * @returns the current particle system
  56580. */
  56581. ParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor, factor2) {
  56582. if (!this._angularSpeedGradients) {
  56583. this._angularSpeedGradients = [];
  56584. }
  56585. this._addFactorGradient(this._angularSpeedGradients, gradient, factor, factor2);
  56586. return this;
  56587. };
  56588. /**
  56589. * Remove a specific angular speed gradient
  56590. * @param gradient defines the gradient to remove
  56591. * @returns the current particle system
  56592. */
  56593. ParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  56594. this._removeFactorGradient(this._angularSpeedGradients, gradient);
  56595. return this;
  56596. };
  56597. /**
  56598. * Adds a new velocity gradient
  56599. * @param gradient defines the gradient to use (between 0 and 1)
  56600. * @param factor defines the velocity to affect to the specified gradient
  56601. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56602. * @returns the current particle system
  56603. */
  56604. ParticleSystem.prototype.addVelocityGradient = function (gradient, factor, factor2) {
  56605. if (!this._velocityGradients) {
  56606. this._velocityGradients = [];
  56607. }
  56608. this._addFactorGradient(this._velocityGradients, gradient, factor, factor2);
  56609. return this;
  56610. };
  56611. /**
  56612. * Remove a specific velocity gradient
  56613. * @param gradient defines the gradient to remove
  56614. * @returns the current particle system
  56615. */
  56616. ParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  56617. this._removeFactorGradient(this._velocityGradients, gradient);
  56618. return this;
  56619. };
  56620. /**
  56621. * Adds a new limit velocity gradient
  56622. * @param gradient defines the gradient to use (between 0 and 1)
  56623. * @param factor defines the limit velocity value to affect to the specified gradient
  56624. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56625. * @returns the current particle system
  56626. */
  56627. ParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor, factor2) {
  56628. if (!this._limitVelocityGradients) {
  56629. this._limitVelocityGradients = [];
  56630. }
  56631. this._addFactorGradient(this._limitVelocityGradients, gradient, factor, factor2);
  56632. return this;
  56633. };
  56634. /**
  56635. * Remove a specific limit velocity gradient
  56636. * @param gradient defines the gradient to remove
  56637. * @returns the current particle system
  56638. */
  56639. ParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  56640. this._removeFactorGradient(this._limitVelocityGradients, gradient);
  56641. return this;
  56642. };
  56643. /**
  56644. * Adds a new drag gradient
  56645. * @param gradient defines the gradient to use (between 0 and 1)
  56646. * @param factor defines the drag value to affect to the specified gradient
  56647. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56648. * @returns the current particle system
  56649. */
  56650. ParticleSystem.prototype.addDragGradient = function (gradient, factor, factor2) {
  56651. if (!this._dragGradients) {
  56652. this._dragGradients = [];
  56653. }
  56654. this._addFactorGradient(this._dragGradients, gradient, factor, factor2);
  56655. return this;
  56656. };
  56657. /**
  56658. * Remove a specific drag gradient
  56659. * @param gradient defines the gradient to remove
  56660. * @returns the current particle system
  56661. */
  56662. ParticleSystem.prototype.removeDragGradient = function (gradient) {
  56663. this._removeFactorGradient(this._dragGradients, gradient);
  56664. return this;
  56665. };
  56666. /**
  56667. * Adds a new emit rate gradient (please note that this will only work if you set the targetStopDuration property)
  56668. * @param gradient defines the gradient to use (between 0 and 1)
  56669. * @param factor defines the emit rate value to affect to the specified gradient
  56670. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56671. * @returns the current particle system
  56672. */
  56673. ParticleSystem.prototype.addEmitRateGradient = function (gradient, factor, factor2) {
  56674. if (!this._emitRateGradients) {
  56675. this._emitRateGradients = [];
  56676. }
  56677. this._addFactorGradient(this._emitRateGradients, gradient, factor, factor2);
  56678. if (!this._currentEmitRateGradient) {
  56679. this._currentEmitRateGradient = this._emitRateGradients[0];
  56680. this._currentEmitRate1 = this._currentEmitRateGradient.getFactor();
  56681. this._currentEmitRate2 = this._currentEmitRate1;
  56682. }
  56683. if (this._emitRateGradients.length === 2) {
  56684. this._currentEmitRate2 = this._emitRateGradients[1].getFactor();
  56685. }
  56686. return this;
  56687. };
  56688. /**
  56689. * Remove a specific emit rate gradient
  56690. * @param gradient defines the gradient to remove
  56691. * @returns the current particle system
  56692. */
  56693. ParticleSystem.prototype.removeEmitRateGradient = function (gradient) {
  56694. this._removeFactorGradient(this._emitRateGradients, gradient);
  56695. return this;
  56696. };
  56697. /**
  56698. * Adds a new start size gradient (please note that this will only work if you set the targetStopDuration property)
  56699. * @param gradient defines the gradient to use (between 0 and 1)
  56700. * @param factor defines the start size value to affect to the specified gradient
  56701. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56702. * @returns the current particle system
  56703. */
  56704. ParticleSystem.prototype.addStartSizeGradient = function (gradient, factor, factor2) {
  56705. if (!this._startSizeGradients) {
  56706. this._startSizeGradients = [];
  56707. }
  56708. this._addFactorGradient(this._startSizeGradients, gradient, factor, factor2);
  56709. if (!this._currentStartSizeGradient) {
  56710. this._currentStartSizeGradient = this._startSizeGradients[0];
  56711. this._currentStartSize1 = this._currentStartSizeGradient.getFactor();
  56712. this._currentStartSize2 = this._currentStartSize1;
  56713. }
  56714. if (this._startSizeGradients.length === 2) {
  56715. this._currentStartSize2 = this._startSizeGradients[1].getFactor();
  56716. }
  56717. return this;
  56718. };
  56719. /**
  56720. * Remove a specific start size gradient
  56721. * @param gradient defines the gradient to remove
  56722. * @returns the current particle system
  56723. */
  56724. ParticleSystem.prototype.removeStartSizeGradient = function (gradient) {
  56725. this._removeFactorGradient(this._emitRateGradients, gradient);
  56726. return this;
  56727. };
  56728. ParticleSystem.prototype._createRampGradientTexture = function () {
  56729. if (!this._rampGradients || !this._rampGradients.length || this._rampGradientsTexture) {
  56730. return;
  56731. }
  56732. var data = new Uint8Array(this._rawTextureWidth * 4);
  56733. var tmpColor = BABYLON.Tmp.Color4[0];
  56734. for (var x = 0; x < this._rawTextureWidth; x++) {
  56735. var ratio = x / this._rawTextureWidth;
  56736. BABYLON.Tools.GetCurrentGradient(ratio, this._rampGradients, function (currentGradient, nextGradient, scale) {
  56737. BABYLON.Color4.LerpToRef(currentGradient.color1, nextGradient.color1, scale, tmpColor);
  56738. data[x * 4] = tmpColor.r * 255;
  56739. data[x * 4 + 1] = tmpColor.g * 255;
  56740. data[x * 4 + 2] = tmpColor.b * 255;
  56741. data[x * 4 + 3] = tmpColor.a * 255;
  56742. });
  56743. }
  56744. this._rampGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  56745. };
  56746. /**
  56747. * Gets the current list of ramp gradients.
  56748. * You must use addRampGradient and removeRampGradient to udpate this list
  56749. * @returns the list of ramp gradients
  56750. */
  56751. ParticleSystem.prototype.getRampGradients = function () {
  56752. return this._rampGradients;
  56753. };
  56754. /**
  56755. * Adds a new ramp gradient used to remap particle colors
  56756. * @param gradient defines the gradient to use (between 0 and 1)
  56757. * @param color defines the color to affect to the specified gradient
  56758. * @returns the current particle system
  56759. */
  56760. ParticleSystem.prototype.addRampGradient = function (gradient, color) {
  56761. if (!this._rampGradients) {
  56762. this._rampGradients = [];
  56763. }
  56764. var rampGradient = new BABYLON.ColorGradient();
  56765. rampGradient.gradient = gradient;
  56766. rampGradient.color1 = color;
  56767. this._rampGradients.push(rampGradient);
  56768. this._rampGradients.sort(function (a, b) {
  56769. if (a.gradient < b.gradient) {
  56770. return -1;
  56771. }
  56772. else if (a.gradient > b.gradient) {
  56773. return 1;
  56774. }
  56775. return 0;
  56776. });
  56777. if (this._rampGradientsTexture) {
  56778. this._rampGradientsTexture.dispose();
  56779. this._rampGradientsTexture = null;
  56780. }
  56781. this._createRampGradientTexture();
  56782. return this;
  56783. };
  56784. /**
  56785. * Remove a specific ramp gradient
  56786. * @param gradient defines the gradient to remove
  56787. * @returns the current particle system
  56788. */
  56789. ParticleSystem.prototype.removeRampGradient = function (gradient) {
  56790. this._removeGradientAndTexture(gradient, this._rampGradients, this._rampGradientsTexture);
  56791. this._rampGradientsTexture = null;
  56792. if (this._rampGradients && this._rampGradients.length > 0) {
  56793. this._createRampGradientTexture();
  56794. }
  56795. return this;
  56796. };
  56797. /**
  56798. * Adds a new color gradient
  56799. * @param gradient defines the gradient to use (between 0 and 1)
  56800. * @param color defines the color to affect to the specified gradient
  56801. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  56802. */
  56803. ParticleSystem.prototype.addColorGradient = function (gradient, color, color2) {
  56804. if (!this._colorGradients) {
  56805. this._colorGradients = [];
  56806. }
  56807. var colorGradient = new BABYLON.ColorGradient();
  56808. colorGradient.gradient = gradient;
  56809. colorGradient.color1 = color;
  56810. colorGradient.color2 = color2;
  56811. this._colorGradients.push(colorGradient);
  56812. this._colorGradients.sort(function (a, b) {
  56813. if (a.gradient < b.gradient) {
  56814. return -1;
  56815. }
  56816. else if (a.gradient > b.gradient) {
  56817. return 1;
  56818. }
  56819. return 0;
  56820. });
  56821. return this;
  56822. };
  56823. /**
  56824. * Remove a specific color gradient
  56825. * @param gradient defines the gradient to remove
  56826. */
  56827. ParticleSystem.prototype.removeColorGradient = function (gradient) {
  56828. if (!this._colorGradients) {
  56829. return this;
  56830. }
  56831. var index = 0;
  56832. for (var _i = 0, _a = this._colorGradients; _i < _a.length; _i++) {
  56833. var colorGradient = _a[_i];
  56834. if (colorGradient.gradient === gradient) {
  56835. this._colorGradients.splice(index, 1);
  56836. break;
  56837. }
  56838. index++;
  56839. }
  56840. return this;
  56841. };
  56842. ParticleSystem.prototype._fetchR = function (u, v, width, height, pixels) {
  56843. u = Math.abs(u) * 0.5 + 0.5;
  56844. v = Math.abs(v) * 0.5 + 0.5;
  56845. var wrappedU = ((u * width) % width) | 0;
  56846. var wrappedV = ((v * height) % height) | 0;
  56847. var position = (wrappedU + wrappedV * width) * 4;
  56848. return pixels[position] / 255;
  56849. };
  56850. ParticleSystem.prototype._reset = function () {
  56851. this._resetEffect();
  56852. };
  56853. ParticleSystem.prototype._resetEffect = function () {
  56854. if (this._vertexBuffer) {
  56855. this._vertexBuffer.dispose();
  56856. this._vertexBuffer = null;
  56857. }
  56858. if (this._spriteBuffer) {
  56859. this._spriteBuffer.dispose();
  56860. this._spriteBuffer = null;
  56861. }
  56862. this._createVertexBuffers();
  56863. };
  56864. ParticleSystem.prototype._createVertexBuffers = function () {
  56865. this._vertexBufferSize = this._useInstancing ? 10 : 12;
  56866. if (this._isAnimationSheetEnabled) {
  56867. this._vertexBufferSize += 1;
  56868. }
  56869. if (!this._isBillboardBased) {
  56870. this._vertexBufferSize += 3;
  56871. }
  56872. if (this._useRampGradients) {
  56873. this._vertexBufferSize += 4;
  56874. }
  56875. var engine = this._scene.getEngine();
  56876. this._vertexData = new Float32Array(this._capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));
  56877. this._vertexBuffer = new BABYLON.Buffer(engine, this._vertexData, true, this._vertexBufferSize);
  56878. var dataOffset = 0;
  56879. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  56880. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  56881. dataOffset += 3;
  56882. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  56883. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  56884. dataOffset += 4;
  56885. var options = this._vertexBuffer.createVertexBuffer("angle", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  56886. this._vertexBuffers["angle"] = options;
  56887. dataOffset += 1;
  56888. var size = this._vertexBuffer.createVertexBuffer("size", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  56889. this._vertexBuffers["size"] = size;
  56890. dataOffset += 2;
  56891. if (this._isAnimationSheetEnabled) {
  56892. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  56893. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  56894. dataOffset += 1;
  56895. }
  56896. if (!this._isBillboardBased) {
  56897. var directionBuffer = this._vertexBuffer.createVertexBuffer("direction", dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  56898. this._vertexBuffers["direction"] = directionBuffer;
  56899. dataOffset += 3;
  56900. }
  56901. if (this._useRampGradients) {
  56902. var rampDataBuffer = this._vertexBuffer.createVertexBuffer("remapData", dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  56903. this._vertexBuffers["remapData"] = rampDataBuffer;
  56904. dataOffset += 4;
  56905. }
  56906. var offsets;
  56907. if (this._useInstancing) {
  56908. var spriteData = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);
  56909. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 2);
  56910. offsets = this._spriteBuffer.createVertexBuffer("offset", 0, 2);
  56911. }
  56912. else {
  56913. offsets = this._vertexBuffer.createVertexBuffer("offset", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  56914. dataOffset += 2;
  56915. }
  56916. this._vertexBuffers["offset"] = offsets;
  56917. };
  56918. ParticleSystem.prototype._createIndexBuffer = function () {
  56919. if (this._useInstancing) {
  56920. return;
  56921. }
  56922. var indices = [];
  56923. var index = 0;
  56924. for (var count = 0; count < this._capacity; count++) {
  56925. indices.push(index);
  56926. indices.push(index + 1);
  56927. indices.push(index + 2);
  56928. indices.push(index);
  56929. indices.push(index + 2);
  56930. indices.push(index + 3);
  56931. index += 4;
  56932. }
  56933. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  56934. };
  56935. /**
  56936. * Gets the maximum number of particles active at the same time.
  56937. * @returns The max number of active particles.
  56938. */
  56939. ParticleSystem.prototype.getCapacity = function () {
  56940. return this._capacity;
  56941. };
  56942. /**
  56943. * Gets whether there are still active particles in the system.
  56944. * @returns True if it is alive, otherwise false.
  56945. */
  56946. ParticleSystem.prototype.isAlive = function () {
  56947. return this._alive;
  56948. };
  56949. /**
  56950. * Gets if the system has been started. (Note: this will still be true after stop is called)
  56951. * @returns True if it has been started, otherwise false.
  56952. */
  56953. ParticleSystem.prototype.isStarted = function () {
  56954. return this._started;
  56955. };
  56956. /**
  56957. * Starts the particle system and begins to emit
  56958. * @param delay defines the delay in milliseconds before starting the system (0 by default)
  56959. */
  56960. ParticleSystem.prototype.start = function (delay) {
  56961. var _this = this;
  56962. if (delay === void 0) { delay = 0; }
  56963. if (delay) {
  56964. setTimeout(function () {
  56965. _this.start(0);
  56966. }, delay);
  56967. return;
  56968. }
  56969. // Convert the subEmitters field to the constant type field _subEmitters
  56970. this._subEmitters = new Array();
  56971. if (this.subEmitters) {
  56972. this.subEmitters.forEach(function (subEmitter) {
  56973. if (subEmitter instanceof ParticleSystem) {
  56974. _this._subEmitters.push([new BABYLON.SubEmitter(subEmitter)]);
  56975. }
  56976. else if (subEmitter instanceof BABYLON.SubEmitter) {
  56977. _this._subEmitters.push([subEmitter]);
  56978. }
  56979. else if (subEmitter instanceof Array) {
  56980. _this._subEmitters.push(subEmitter);
  56981. }
  56982. });
  56983. }
  56984. this._started = true;
  56985. this._stopped = false;
  56986. this._actualFrame = 0;
  56987. if (this._subEmitters && this._subEmitters.length != 0) {
  56988. this.activeSubSystems = new Array();
  56989. }
  56990. if (this.preWarmCycles) {
  56991. for (var index = 0; index < this.preWarmCycles; index++) {
  56992. this.animate(true);
  56993. }
  56994. }
  56995. };
  56996. /**
  56997. * Stops the particle system.
  56998. * @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.
  56999. */
  57000. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  57001. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  57002. this._stopped = true;
  57003. if (stopSubEmitters) {
  57004. this._stopSubEmitters();
  57005. }
  57006. };
  57007. // animation sheet
  57008. /**
  57009. * Remove all active particles
  57010. */
  57011. ParticleSystem.prototype.reset = function () {
  57012. this._stockParticles = [];
  57013. this._particles = [];
  57014. };
  57015. /**
  57016. * @hidden (for internal use only)
  57017. */
  57018. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  57019. var offset = index * this._vertexBufferSize;
  57020. this._vertexData[offset++] = particle.position.x;
  57021. this._vertexData[offset++] = particle.position.y;
  57022. this._vertexData[offset++] = particle.position.z;
  57023. this._vertexData[offset++] = particle.color.r;
  57024. this._vertexData[offset++] = particle.color.g;
  57025. this._vertexData[offset++] = particle.color.b;
  57026. this._vertexData[offset++] = particle.color.a;
  57027. this._vertexData[offset++] = particle.angle;
  57028. this._vertexData[offset++] = particle.scale.x * particle.size;
  57029. this._vertexData[offset++] = particle.scale.y * particle.size;
  57030. if (this._isAnimationSheetEnabled) {
  57031. this._vertexData[offset++] = particle.cellIndex;
  57032. }
  57033. if (!this._isBillboardBased) {
  57034. if (particle._initialDirection) {
  57035. this._vertexData[offset++] = particle._initialDirection.x;
  57036. this._vertexData[offset++] = particle._initialDirection.y;
  57037. this._vertexData[offset++] = particle._initialDirection.z;
  57038. }
  57039. else {
  57040. this._vertexData[offset++] = particle.direction.x;
  57041. this._vertexData[offset++] = particle.direction.y;
  57042. this._vertexData[offset++] = particle.direction.z;
  57043. }
  57044. }
  57045. if (!this._useInstancing) {
  57046. if (this._isAnimationSheetEnabled) {
  57047. if (offsetX === 0)
  57048. offsetX = this._epsilon;
  57049. else if (offsetX === 1)
  57050. offsetX = 1 - this._epsilon;
  57051. if (offsetY === 0)
  57052. offsetY = this._epsilon;
  57053. else if (offsetY === 1)
  57054. offsetY = 1 - this._epsilon;
  57055. }
  57056. this._vertexData[offset++] = offsetX;
  57057. this._vertexData[offset++] = offsetY;
  57058. }
  57059. if (this._useRampGradients) {
  57060. this._vertexData[offset++] = particle.remapData.x;
  57061. this._vertexData[offset++] = particle.remapData.y;
  57062. this._vertexData[offset++] = particle.remapData.z;
  57063. this._vertexData[offset++] = particle.remapData.w;
  57064. }
  57065. };
  57066. ParticleSystem.prototype._stopSubEmitters = function () {
  57067. if (!this.activeSubSystems) {
  57068. return;
  57069. }
  57070. this.activeSubSystems.forEach(function (subSystem) {
  57071. subSystem.stop(true);
  57072. });
  57073. this.activeSubSystems = new Array();
  57074. };
  57075. ParticleSystem.prototype._removeFromRoot = function () {
  57076. if (!this._rootParticleSystem) {
  57077. return;
  57078. }
  57079. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  57080. if (index !== -1) {
  57081. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  57082. }
  57083. };
  57084. // End of sub system methods
  57085. ParticleSystem.prototype._update = function (newParticles) {
  57086. var _this = this;
  57087. // Update current
  57088. this._alive = this._particles.length > 0;
  57089. if (this.emitter.position) {
  57090. var emitterMesh = this.emitter;
  57091. this._emitterWorldMatrix = emitterMesh.getWorldMatrix();
  57092. }
  57093. else {
  57094. var emitterPosition = this.emitter;
  57095. this._emitterWorldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  57096. }
  57097. this.updateFunction(this._particles);
  57098. // Add new ones
  57099. var particle;
  57100. var _loop_2 = function () {
  57101. if (this_1._particles.length === this_1._capacity) {
  57102. return "break";
  57103. }
  57104. particle = this_1._createParticle();
  57105. this_1._particles.push(particle);
  57106. // Emitter
  57107. var emitPower = BABYLON.Scalar.RandomRange(this_1.minEmitPower, this_1.maxEmitPower);
  57108. if (this_1.startPositionFunction) {
  57109. this_1.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  57110. }
  57111. else {
  57112. this_1.particleEmitterType.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  57113. }
  57114. if (this_1.startDirectionFunction) {
  57115. this_1.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  57116. }
  57117. else {
  57118. this_1.particleEmitterType.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  57119. }
  57120. if (emitPower === 0) {
  57121. if (!particle._initialDirection) {
  57122. particle._initialDirection = particle.direction.clone();
  57123. }
  57124. else {
  57125. particle._initialDirection.copyFrom(particle.direction);
  57126. }
  57127. }
  57128. else {
  57129. particle._initialDirection = null;
  57130. }
  57131. particle.direction.scaleInPlace(emitPower);
  57132. // Life time
  57133. if (this_1.targetStopDuration && this_1._lifeTimeGradients && this_1._lifeTimeGradients.length > 0) {
  57134. var ratio_1 = BABYLON.Scalar.Clamp(this_1._actualFrame / this_1.targetStopDuration);
  57135. BABYLON.Tools.GetCurrentGradient(ratio_1, this_1._lifeTimeGradients, function (currentGradient, nextGradient, scale) {
  57136. var factorGradient1 = currentGradient;
  57137. var factorGradient2 = nextGradient;
  57138. var lifeTime1 = factorGradient1.getFactor();
  57139. var lifeTime2 = factorGradient2.getFactor();
  57140. var gradient = (ratio_1 - factorGradient1.gradient) / (factorGradient2.gradient - factorGradient1.gradient);
  57141. particle.lifeTime = BABYLON.Scalar.Lerp(lifeTime1, lifeTime2, gradient);
  57142. });
  57143. }
  57144. else {
  57145. particle.lifeTime = BABYLON.Scalar.RandomRange(this_1.minLifeTime, this_1.maxLifeTime);
  57146. }
  57147. // Size
  57148. if (!this_1._sizeGradients || this_1._sizeGradients.length === 0) {
  57149. particle.size = BABYLON.Scalar.RandomRange(this_1.minSize, this_1.maxSize);
  57150. }
  57151. else {
  57152. particle._currentSizeGradient = this_1._sizeGradients[0];
  57153. particle._currentSize1 = particle._currentSizeGradient.getFactor();
  57154. particle.size = particle._currentSize1;
  57155. if (this_1._sizeGradients.length > 1) {
  57156. particle._currentSize2 = this_1._sizeGradients[1].getFactor();
  57157. }
  57158. else {
  57159. particle._currentSize2 = particle._currentSize1;
  57160. }
  57161. }
  57162. // Size and scale
  57163. particle.scale.copyFromFloats(BABYLON.Scalar.RandomRange(this_1.minScaleX, this_1.maxScaleX), BABYLON.Scalar.RandomRange(this_1.minScaleY, this_1.maxScaleY));
  57164. // Adjust scale by start size
  57165. if (this_1._startSizeGradients && this_1._startSizeGradients[0]) {
  57166. var ratio = this_1._actualFrame / this_1.targetStopDuration;
  57167. BABYLON.Tools.GetCurrentGradient(ratio, this_1._startSizeGradients, function (currentGradient, nextGradient, scale) {
  57168. if (currentGradient !== _this._currentStartSizeGradient) {
  57169. _this._currentStartSize1 = _this._currentStartSize2;
  57170. _this._currentStartSize2 = nextGradient.getFactor();
  57171. _this._currentStartSizeGradient = currentGradient;
  57172. }
  57173. var value = BABYLON.Scalar.Lerp(_this._currentStartSize1, _this._currentStartSize2, scale);
  57174. particle.scale.scaleInPlace(value);
  57175. });
  57176. }
  57177. // Angle
  57178. if (!this_1._angularSpeedGradients || this_1._angularSpeedGradients.length === 0) {
  57179. particle.angularSpeed = BABYLON.Scalar.RandomRange(this_1.minAngularSpeed, this_1.maxAngularSpeed);
  57180. }
  57181. else {
  57182. particle._currentAngularSpeedGradient = this_1._angularSpeedGradients[0];
  57183. particle.angularSpeed = particle._currentAngularSpeedGradient.getFactor();
  57184. particle._currentAngularSpeed1 = particle.angularSpeed;
  57185. if (this_1._angularSpeedGradients.length > 1) {
  57186. particle._currentAngularSpeed2 = this_1._angularSpeedGradients[1].getFactor();
  57187. }
  57188. else {
  57189. particle._currentAngularSpeed2 = particle._currentAngularSpeed1;
  57190. }
  57191. }
  57192. particle.angle = BABYLON.Scalar.RandomRange(this_1.minInitialRotation, this_1.maxInitialRotation);
  57193. // Velocity
  57194. if (this_1._velocityGradients && this_1._velocityGradients.length > 0) {
  57195. particle._currentVelocityGradient = this_1._velocityGradients[0];
  57196. particle._currentVelocity1 = particle._currentVelocityGradient.getFactor();
  57197. if (this_1._velocityGradients.length > 1) {
  57198. particle._currentVelocity2 = this_1._velocityGradients[1].getFactor();
  57199. }
  57200. else {
  57201. particle._currentVelocity2 = particle._currentVelocity1;
  57202. }
  57203. }
  57204. // Limit velocity
  57205. if (this_1._limitVelocityGradients && this_1._limitVelocityGradients.length > 0) {
  57206. particle._currentLimitVelocityGradient = this_1._limitVelocityGradients[0];
  57207. particle._currentLimitVelocity1 = particle._currentLimitVelocityGradient.getFactor();
  57208. if (this_1._limitVelocityGradients.length > 1) {
  57209. particle._currentLimitVelocity2 = this_1._limitVelocityGradients[1].getFactor();
  57210. }
  57211. else {
  57212. particle._currentLimitVelocity2 = particle._currentLimitVelocity1;
  57213. }
  57214. }
  57215. // Drag
  57216. if (this_1._dragGradients && this_1._dragGradients.length > 0) {
  57217. particle._currentDragGradient = this_1._dragGradients[0];
  57218. particle._currentDrag1 = particle._currentDragGradient.getFactor();
  57219. if (this_1._dragGradients.length > 1) {
  57220. particle._currentDrag2 = this_1._dragGradients[1].getFactor();
  57221. }
  57222. else {
  57223. particle._currentDrag2 = particle._currentDrag1;
  57224. }
  57225. }
  57226. // Color
  57227. if (!this_1._colorGradients || this_1._colorGradients.length === 0) {
  57228. step = BABYLON.Scalar.RandomRange(0, 1.0);
  57229. BABYLON.Color4.LerpToRef(this_1.color1, this_1.color2, step, particle.color);
  57230. this_1.colorDead.subtractToRef(particle.color, this_1._colorDiff);
  57231. this_1._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  57232. }
  57233. else {
  57234. particle._currentColorGradient = this_1._colorGradients[0];
  57235. particle._currentColorGradient.getColorToRef(particle.color);
  57236. particle._currentColor1.copyFrom(particle.color);
  57237. if (this_1._colorGradients.length > 1) {
  57238. this_1._colorGradients[1].getColorToRef(particle._currentColor2);
  57239. }
  57240. else {
  57241. particle._currentColor2.copyFrom(particle.color);
  57242. }
  57243. }
  57244. // Sheet
  57245. if (this_1._isAnimationSheetEnabled) {
  57246. particle._initialStartSpriteCellID = this_1.startSpriteCellID;
  57247. particle._initialEndSpriteCellID = this_1.endSpriteCellID;
  57248. }
  57249. // Inherited Velocity
  57250. particle.direction.addInPlace(this_1._inheritedVelocityOffset);
  57251. // Ramp
  57252. if (this_1._useRampGradients) {
  57253. particle.remapData = new BABYLON.Vector4(0, 1, 0, 1);
  57254. }
  57255. };
  57256. var this_1 = this, step;
  57257. for (var index = 0; index < newParticles; index++) {
  57258. var state_1 = _loop_2();
  57259. if (state_1 === "break")
  57260. break;
  57261. }
  57262. };
  57263. /** @hidden */
  57264. ParticleSystem._GetAttributeNamesOrOptions = function (isAnimationSheetEnabled, isBillboardBased, useRampGradients) {
  57265. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  57266. if (isBillboardBased === void 0) { isBillboardBased = false; }
  57267. if (useRampGradients === void 0) { useRampGradients = false; }
  57268. var attributeNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "angle", "offset", "size"];
  57269. if (isAnimationSheetEnabled) {
  57270. attributeNamesOrOptions.push("cellIndex");
  57271. }
  57272. if (!isBillboardBased) {
  57273. attributeNamesOrOptions.push("direction");
  57274. }
  57275. if (useRampGradients) {
  57276. attributeNamesOrOptions.push("remapData");
  57277. }
  57278. return attributeNamesOrOptions;
  57279. };
  57280. ParticleSystem._GetEffectCreationOptions = function (isAnimationSheetEnabled) {
  57281. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  57282. var effectCreationOption = ["invView", "view", "projection", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "textureMask", "translationPivot", "eyePosition"];
  57283. if (isAnimationSheetEnabled) {
  57284. effectCreationOption.push("particlesInfos");
  57285. }
  57286. return effectCreationOption;
  57287. };
  57288. ParticleSystem.prototype._getEffect = function () {
  57289. if (this._customEffect) {
  57290. return this._customEffect;
  57291. }
  57292. ;
  57293. var defines = [];
  57294. if (this._scene.clipPlane) {
  57295. defines.push("#define CLIPPLANE");
  57296. }
  57297. if (this._scene.clipPlane2) {
  57298. defines.push("#define CLIPPLANE2");
  57299. }
  57300. if (this._scene.clipPlane3) {
  57301. defines.push("#define CLIPPLANE3");
  57302. }
  57303. if (this._scene.clipPlane4) {
  57304. defines.push("#define CLIPPLANE4");
  57305. }
  57306. if (this._isAnimationSheetEnabled) {
  57307. defines.push("#define ANIMATESHEET");
  57308. }
  57309. if (this.blendMode === ParticleSystem.BLENDMODE_MULTIPLY) {
  57310. defines.push("#define BLENDMULTIPLYMODE");
  57311. }
  57312. if (this._useRampGradients) {
  57313. defines.push("#define RAMPGRADIENT");
  57314. }
  57315. if (this._isBillboardBased) {
  57316. defines.push("#define BILLBOARD");
  57317. switch (this.billboardMode) {
  57318. case BABYLON.AbstractMesh.BILLBOARDMODE_Y:
  57319. defines.push("#define BILLBOARDY");
  57320. break;
  57321. case BABYLON.AbstractMesh.BILLBOARDMODE_ALL:
  57322. default:
  57323. break;
  57324. }
  57325. }
  57326. if (this._imageProcessingConfiguration) {
  57327. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  57328. defines.push(this._imageProcessingConfigurationDefines.toString());
  57329. }
  57330. // Effect
  57331. var join = defines.join("\n");
  57332. if (this._cachedDefines !== join) {
  57333. this._cachedDefines = join;
  57334. var attributesNamesOrOptions = ParticleSystem._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled, this._isBillboardBased, this._useRampGradients);
  57335. var effectCreationOption = ParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled);
  57336. var samplers = ["diffuseSampler", "rampSampler"];
  57337. if (BABYLON.ImageProcessingConfiguration) {
  57338. BABYLON.ImageProcessingConfiguration.PrepareUniforms(effectCreationOption, this._imageProcessingConfigurationDefines);
  57339. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  57340. }
  57341. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, samplers, join);
  57342. }
  57343. return this._effect;
  57344. };
  57345. /**
  57346. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  57347. * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false)
  57348. */
  57349. ParticleSystem.prototype.animate = function (preWarmOnly) {
  57350. var _this = this;
  57351. if (preWarmOnly === void 0) { preWarmOnly = false; }
  57352. if (!this._started)
  57353. return;
  57354. if (!preWarmOnly) {
  57355. var effect = this._getEffect();
  57356. // Check
  57357. if (!this.emitter || !this._imageProcessingConfiguration.isReady() || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  57358. return;
  57359. if (this._currentRenderId === this._scene.getRenderId()) {
  57360. return;
  57361. }
  57362. this._currentRenderId = this._scene.getRenderId();
  57363. }
  57364. this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  57365. // Determine the number of particles we need to create
  57366. var newParticles;
  57367. if (this.manualEmitCount > -1) {
  57368. newParticles = this.manualEmitCount;
  57369. this._newPartsExcess = 0;
  57370. this.manualEmitCount = 0;
  57371. }
  57372. else {
  57373. var rate_1 = this.emitRate;
  57374. if (this._emitRateGradients && this._emitRateGradients.length > 0 && this.targetStopDuration) {
  57375. var ratio = this._actualFrame / this.targetStopDuration;
  57376. BABYLON.Tools.GetCurrentGradient(ratio, this._emitRateGradients, function (currentGradient, nextGradient, scale) {
  57377. if (currentGradient !== _this._currentEmitRateGradient) {
  57378. _this._currentEmitRate1 = _this._currentEmitRate2;
  57379. _this._currentEmitRate2 = nextGradient.getFactor();
  57380. _this._currentEmitRateGradient = currentGradient;
  57381. }
  57382. rate_1 = BABYLON.Scalar.Lerp(_this._currentEmitRate1, _this._currentEmitRate2, scale);
  57383. });
  57384. }
  57385. newParticles = ((rate_1 * this._scaledUpdateSpeed) >> 0);
  57386. this._newPartsExcess += rate_1 * this._scaledUpdateSpeed - newParticles;
  57387. }
  57388. if (this._newPartsExcess > 1.0) {
  57389. newParticles += this._newPartsExcess >> 0;
  57390. this._newPartsExcess -= this._newPartsExcess >> 0;
  57391. }
  57392. this._alive = false;
  57393. if (!this._stopped) {
  57394. this._actualFrame += this._scaledUpdateSpeed;
  57395. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  57396. this.stop();
  57397. }
  57398. else {
  57399. newParticles = 0;
  57400. }
  57401. this._update(newParticles);
  57402. // Stopped?
  57403. if (this._stopped) {
  57404. if (!this._alive) {
  57405. this._started = false;
  57406. if (this.onAnimationEnd) {
  57407. this.onAnimationEnd();
  57408. }
  57409. if (this.disposeOnStop) {
  57410. this._scene._toBeDisposed.push(this);
  57411. }
  57412. }
  57413. }
  57414. if (!preWarmOnly) {
  57415. // Update VBO
  57416. var offset = 0;
  57417. for (var index = 0; index < this._particles.length; index++) {
  57418. var particle = this._particles[index];
  57419. this._appendParticleVertices(offset, particle);
  57420. offset += this._useInstancing ? 1 : 4;
  57421. }
  57422. if (this._vertexBuffer) {
  57423. this._vertexBuffer.update(this._vertexData);
  57424. }
  57425. }
  57426. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  57427. this.stop();
  57428. }
  57429. };
  57430. ParticleSystem.prototype._appendParticleVertices = function (offset, particle) {
  57431. this._appendParticleVertex(offset++, particle, 0, 0);
  57432. if (!this._useInstancing) {
  57433. this._appendParticleVertex(offset++, particle, 1, 0);
  57434. this._appendParticleVertex(offset++, particle, 1, 1);
  57435. this._appendParticleVertex(offset++, particle, 0, 1);
  57436. }
  57437. };
  57438. /**
  57439. * Rebuilds the particle system.
  57440. */
  57441. ParticleSystem.prototype.rebuild = function () {
  57442. this._createIndexBuffer();
  57443. if (this._vertexBuffer) {
  57444. this._vertexBuffer._rebuild();
  57445. }
  57446. };
  57447. /**
  57448. * Is this system ready to be used/rendered
  57449. * @return true if the system is ready
  57450. */
  57451. ParticleSystem.prototype.isReady = function () {
  57452. var effect = this._getEffect();
  57453. if (!this.emitter || !this._imageProcessingConfiguration.isReady() || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  57454. return false;
  57455. }
  57456. return true;
  57457. };
  57458. /**
  57459. * Renders the particle system in its current state.
  57460. * @returns the current number of particles
  57461. */
  57462. ParticleSystem.prototype.render = function () {
  57463. var effect = this._getEffect();
  57464. // Check
  57465. if (!this.isReady() || !this._particles.length) {
  57466. return 0;
  57467. }
  57468. var engine = this._scene.getEngine();
  57469. // Render
  57470. engine.enableEffect(effect);
  57471. engine.setState(false);
  57472. var viewMatrix = this._scene.getViewMatrix();
  57473. effect.setTexture("diffuseSampler", this.particleTexture);
  57474. effect.setMatrix("view", viewMatrix);
  57475. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  57476. if (this._isAnimationSheetEnabled && this.particleTexture) {
  57477. var baseSize = this.particleTexture.getBaseSize();
  57478. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  57479. }
  57480. effect.setVector2("translationPivot", this.translationPivot);
  57481. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  57482. if (this._isBillboardBased) {
  57483. var camera = this._scene.activeCamera;
  57484. effect.setVector3("eyePosition", camera.globalPosition);
  57485. }
  57486. if (this._rampGradientsTexture) {
  57487. effect.setTexture("rampSampler", this._rampGradientsTexture);
  57488. }
  57489. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  57490. var invView = viewMatrix.clone();
  57491. invView.invert();
  57492. effect.setMatrix("invView", invView);
  57493. BABYLON.MaterialHelper.BindClipPlane(effect, this._scene);
  57494. }
  57495. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  57496. // image processing
  57497. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  57498. this._imageProcessingConfiguration.bind(effect);
  57499. }
  57500. // Draw order
  57501. switch (this.blendMode) {
  57502. case ParticleSystem.BLENDMODE_ADD:
  57503. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  57504. break;
  57505. case ParticleSystem.BLENDMODE_ONEONE:
  57506. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  57507. break;
  57508. case ParticleSystem.BLENDMODE_STANDARD:
  57509. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  57510. break;
  57511. case ParticleSystem.BLENDMODE_MULTIPLY:
  57512. engine.setAlphaMode(BABYLON.Engine.ALPHA_MULTIPLY);
  57513. break;
  57514. }
  57515. if (this.forceDepthWrite) {
  57516. engine.setDepthWrite(true);
  57517. }
  57518. if (this._useInstancing) {
  57519. engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._particles.length);
  57520. engine.unbindInstanceAttributes();
  57521. }
  57522. else {
  57523. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  57524. }
  57525. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  57526. return this._particles.length;
  57527. };
  57528. /**
  57529. * Disposes the particle system and free the associated resources
  57530. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  57531. */
  57532. ParticleSystem.prototype.dispose = function (disposeTexture) {
  57533. if (disposeTexture === void 0) { disposeTexture = true; }
  57534. if (this._vertexBuffer) {
  57535. this._vertexBuffer.dispose();
  57536. this._vertexBuffer = null;
  57537. }
  57538. if (this._spriteBuffer) {
  57539. this._spriteBuffer.dispose();
  57540. this._spriteBuffer = null;
  57541. }
  57542. if (this._indexBuffer) {
  57543. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  57544. this._indexBuffer = null;
  57545. }
  57546. if (disposeTexture && this.particleTexture) {
  57547. this.particleTexture.dispose();
  57548. this.particleTexture = null;
  57549. }
  57550. if (disposeTexture && this.noiseTexture) {
  57551. this.noiseTexture.dispose();
  57552. this.noiseTexture = null;
  57553. }
  57554. this._removeFromRoot();
  57555. if (this._disposeEmitterOnDispose && !this.emitter.isDisposed) {
  57556. this.emitter.dispose();
  57557. }
  57558. // Remove from scene
  57559. var index = this._scene.particleSystems.indexOf(this);
  57560. if (index > -1) {
  57561. this._scene.particleSystems.splice(index, 1);
  57562. }
  57563. // Callback
  57564. this.onDisposeObservable.notifyObservers(this);
  57565. this.onDisposeObservable.clear();
  57566. };
  57567. // Clone
  57568. /**
  57569. * Clones the particle system.
  57570. * @param name The name of the cloned object
  57571. * @param newEmitter The new emitter to use
  57572. * @returns the cloned particle system
  57573. */
  57574. ParticleSystem.prototype.clone = function (name, newEmitter) {
  57575. var custom = null;
  57576. var program = null;
  57577. if (this.customShader != null) {
  57578. program = this.customShader;
  57579. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  57580. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  57581. }
  57582. else if (this._customEffect) {
  57583. custom = this._customEffect;
  57584. }
  57585. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  57586. result.customShader = program;
  57587. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  57588. if (newEmitter === undefined) {
  57589. newEmitter = this.emitter;
  57590. }
  57591. result.emitter = newEmitter;
  57592. if (this.particleTexture) {
  57593. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  57594. }
  57595. // Clone gradients
  57596. if (this._colorGradients) {
  57597. this._colorGradients.forEach(function (v) {
  57598. result.addColorGradient(v.gradient, v.color1, v.color2);
  57599. });
  57600. }
  57601. if (this._dragGradients) {
  57602. this._dragGradients.forEach(function (v) {
  57603. result.addDragGradient(v.gradient, v.factor1, v.factor2);
  57604. });
  57605. }
  57606. if (this._angularSpeedGradients) {
  57607. this._angularSpeedGradients.forEach(function (v) {
  57608. result.addAngularSpeedGradient(v.gradient, v.factor1, v.factor2);
  57609. });
  57610. }
  57611. if (this._emitRateGradients) {
  57612. this._emitRateGradients.forEach(function (v) {
  57613. result.addEmitRateGradient(v.gradient, v.factor1, v.factor2);
  57614. });
  57615. }
  57616. if (this._lifeTimeGradients) {
  57617. this._lifeTimeGradients.forEach(function (v) {
  57618. result.addLifeTimeGradient(v.gradient, v.factor1, v.factor2);
  57619. });
  57620. }
  57621. if (this._limitVelocityGradients) {
  57622. this._limitVelocityGradients.forEach(function (v) {
  57623. result.addLimitVelocityGradient(v.gradient, v.factor1, v.factor2);
  57624. });
  57625. }
  57626. if (this._sizeGradients) {
  57627. this._sizeGradients.forEach(function (v) {
  57628. result.addSizeGradient(v.gradient, v.factor1, v.factor2);
  57629. });
  57630. }
  57631. if (this._startSizeGradients) {
  57632. this._startSizeGradients.forEach(function (v) {
  57633. result.addStartSizeGradient(v.gradient, v.factor1, v.factor2);
  57634. });
  57635. }
  57636. if (this._velocityGradients) {
  57637. this._velocityGradients.forEach(function (v) {
  57638. result.addVelocityGradient(v.gradient, v.factor1, v.factor2);
  57639. });
  57640. }
  57641. if (this._rampGradients) {
  57642. this._rampGradients.forEach(function (v) {
  57643. result.addRampGradient(v.gradient, v.color1);
  57644. });
  57645. }
  57646. if (this._colorRemapGradients) {
  57647. this._colorRemapGradients.forEach(function (v) {
  57648. result.addColorRemapGradient(v.gradient, v.factor1, v.factor2);
  57649. });
  57650. }
  57651. if (this._alphaRemapGradients) {
  57652. this._alphaRemapGradients.forEach(function (v) {
  57653. result.addAlphaRemapGradient(v.gradient, v.factor1, v.factor2);
  57654. });
  57655. }
  57656. if (!this.preventAutoStart) {
  57657. result.start();
  57658. }
  57659. return result;
  57660. };
  57661. /**
  57662. * Serializes the particle system to a JSON object.
  57663. * @returns the JSON object
  57664. */
  57665. ParticleSystem.prototype.serialize = function () {
  57666. var serializationObject = {};
  57667. ParticleSystem._Serialize(serializationObject, this);
  57668. serializationObject.textureMask = this.textureMask.asArray();
  57669. serializationObject.customShader = this.customShader;
  57670. serializationObject.preventAutoStart = this.preventAutoStart;
  57671. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  57672. return serializationObject;
  57673. };
  57674. /** @hidden */
  57675. ParticleSystem._Serialize = function (serializationObject, particleSystem) {
  57676. serializationObject.name = particleSystem.name;
  57677. serializationObject.id = particleSystem.id;
  57678. serializationObject.capacity = particleSystem.getCapacity();
  57679. // Emitter
  57680. if (particleSystem.emitter.position) {
  57681. var emitterMesh = particleSystem.emitter;
  57682. serializationObject.emitterId = emitterMesh.id;
  57683. }
  57684. else {
  57685. var emitterPosition = particleSystem.emitter;
  57686. serializationObject.emitter = emitterPosition.asArray();
  57687. }
  57688. // Emitter
  57689. if (particleSystem.particleEmitterType) {
  57690. serializationObject.particleEmitterType = particleSystem.particleEmitterType.serialize();
  57691. }
  57692. if (particleSystem.particleTexture) {
  57693. serializationObject.textureName = particleSystem.particleTexture.name;
  57694. }
  57695. // Animations
  57696. BABYLON.Animation.AppendSerializedAnimations(particleSystem, serializationObject);
  57697. // Particle system
  57698. serializationObject.renderingGroupId = particleSystem.renderingGroupId;
  57699. serializationObject.isBillboardBased = particleSystem.isBillboardBased;
  57700. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  57701. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  57702. serializationObject.minSize = particleSystem.minSize;
  57703. serializationObject.maxSize = particleSystem.maxSize;
  57704. serializationObject.minScaleX = particleSystem.minScaleX;
  57705. serializationObject.maxScaleX = particleSystem.maxScaleX;
  57706. serializationObject.minScaleY = particleSystem.minScaleY;
  57707. serializationObject.maxScaleY = particleSystem.maxScaleY;
  57708. serializationObject.minEmitPower = particleSystem.minEmitPower;
  57709. serializationObject.maxEmitPower = particleSystem.maxEmitPower;
  57710. serializationObject.minLifeTime = particleSystem.minLifeTime;
  57711. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  57712. serializationObject.emitRate = particleSystem.emitRate;
  57713. serializationObject.gravity = particleSystem.gravity.asArray();
  57714. serializationObject.noiseStrength = particleSystem.noiseStrength.asArray();
  57715. serializationObject.color1 = particleSystem.color1.asArray();
  57716. serializationObject.color2 = particleSystem.color2.asArray();
  57717. serializationObject.colorDead = particleSystem.colorDead.asArray();
  57718. serializationObject.updateSpeed = particleSystem.updateSpeed;
  57719. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  57720. serializationObject.blendMode = particleSystem.blendMode;
  57721. serializationObject.preWarmCycles = particleSystem.preWarmCycles;
  57722. serializationObject.preWarmStepOffset = particleSystem.preWarmStepOffset;
  57723. serializationObject.minInitialRotation = particleSystem.minInitialRotation;
  57724. serializationObject.maxInitialRotation = particleSystem.maxInitialRotation;
  57725. serializationObject.startSpriteCellID = particleSystem.startSpriteCellID;
  57726. serializationObject.endSpriteCellID = particleSystem.endSpriteCellID;
  57727. serializationObject.spriteCellChangeSpeed = particleSystem.spriteCellChangeSpeed;
  57728. serializationObject.spriteCellWidth = particleSystem.spriteCellWidth;
  57729. serializationObject.spriteCellHeight = particleSystem.spriteCellHeight;
  57730. var colorGradients = particleSystem.getColorGradients();
  57731. if (colorGradients) {
  57732. serializationObject.colorGradients = [];
  57733. for (var _i = 0, colorGradients_1 = colorGradients; _i < colorGradients_1.length; _i++) {
  57734. var colorGradient = colorGradients_1[_i];
  57735. var serializedGradient = {
  57736. gradient: colorGradient.gradient,
  57737. color1: colorGradient.color1.asArray()
  57738. };
  57739. if (colorGradient.color2) {
  57740. serializedGradient.color2 = colorGradient.color2.asArray();
  57741. }
  57742. serializationObject.colorGradients.push(serializedGradient);
  57743. }
  57744. }
  57745. var rampGradients = particleSystem.getRampGradients();
  57746. if (rampGradients) {
  57747. serializationObject.rampGradients = [];
  57748. for (var _a = 0, rampGradients_1 = rampGradients; _a < rampGradients_1.length; _a++) {
  57749. var rampGradient = rampGradients_1[_a];
  57750. var serializedGradient = {
  57751. gradient: rampGradient.gradient,
  57752. color1: rampGradient.color1.asArray()
  57753. };
  57754. serializationObject.rampGradients.push(serializedGradient);
  57755. }
  57756. }
  57757. var colorRemapGradients = particleSystem.getColorRemapGradients();
  57758. if (colorRemapGradients) {
  57759. serializationObject.colorRemapGradients = [];
  57760. for (var _b = 0, colorRemapGradients_1 = colorRemapGradients; _b < colorRemapGradients_1.length; _b++) {
  57761. var colorRemapGradient = colorRemapGradients_1[_b];
  57762. var serializedGradient = {
  57763. gradient: colorRemapGradient.gradient,
  57764. factor1: colorRemapGradient.factor1
  57765. };
  57766. if (colorRemapGradient.factor2 !== undefined) {
  57767. serializedGradient.factor2 = colorRemapGradient.factor2;
  57768. }
  57769. serializationObject.colorRemapGradients.push(serializedGradient);
  57770. }
  57771. }
  57772. var alphaRemapGradients = particleSystem.getAlphaRemapGradients();
  57773. if (alphaRemapGradients) {
  57774. serializationObject.alphaRemapGradients = [];
  57775. for (var _c = 0, alphaRemapGradients_1 = alphaRemapGradients; _c < alphaRemapGradients_1.length; _c++) {
  57776. var alphaRemapGradient = alphaRemapGradients_1[_c];
  57777. var serializedGradient = {
  57778. gradient: alphaRemapGradient.gradient,
  57779. factor1: alphaRemapGradient.factor1
  57780. };
  57781. if (alphaRemapGradient.factor2 !== undefined) {
  57782. serializedGradient.factor2 = alphaRemapGradient.factor2;
  57783. }
  57784. serializationObject.alphaRemapGradients.push(serializedGradient);
  57785. }
  57786. }
  57787. var sizeGradients = particleSystem.getSizeGradients();
  57788. if (sizeGradients) {
  57789. serializationObject.sizeGradients = [];
  57790. for (var _d = 0, sizeGradients_1 = sizeGradients; _d < sizeGradients_1.length; _d++) {
  57791. var sizeGradient = sizeGradients_1[_d];
  57792. var serializedGradient = {
  57793. gradient: sizeGradient.gradient,
  57794. factor1: sizeGradient.factor1
  57795. };
  57796. if (sizeGradient.factor2 !== undefined) {
  57797. serializedGradient.factor2 = sizeGradient.factor2;
  57798. }
  57799. serializationObject.sizeGradients.push(serializedGradient);
  57800. }
  57801. }
  57802. var angularSpeedGradients = particleSystem.getAngularSpeedGradients();
  57803. if (angularSpeedGradients) {
  57804. serializationObject.angularSpeedGradients = [];
  57805. for (var _e = 0, angularSpeedGradients_1 = angularSpeedGradients; _e < angularSpeedGradients_1.length; _e++) {
  57806. var angularSpeedGradient = angularSpeedGradients_1[_e];
  57807. var serializedGradient = {
  57808. gradient: angularSpeedGradient.gradient,
  57809. factor1: angularSpeedGradient.factor1
  57810. };
  57811. if (angularSpeedGradient.factor2 !== undefined) {
  57812. serializedGradient.factor2 = angularSpeedGradient.factor2;
  57813. }
  57814. serializationObject.angularSpeedGradients.push(serializedGradient);
  57815. }
  57816. }
  57817. var velocityGradients = particleSystem.getVelocityGradients();
  57818. if (velocityGradients) {
  57819. serializationObject.velocityGradients = [];
  57820. for (var _f = 0, velocityGradients_1 = velocityGradients; _f < velocityGradients_1.length; _f++) {
  57821. var velocityGradient = velocityGradients_1[_f];
  57822. var serializedGradient = {
  57823. gradient: velocityGradient.gradient,
  57824. factor1: velocityGradient.factor1
  57825. };
  57826. if (velocityGradient.factor2 !== undefined) {
  57827. serializedGradient.factor2 = velocityGradient.factor2;
  57828. }
  57829. serializationObject.velocityGradients.push(serializedGradient);
  57830. }
  57831. }
  57832. var dragGradients = particleSystem.getDragGradients();
  57833. if (dragGradients) {
  57834. serializationObject.dragyGradients = [];
  57835. for (var _g = 0, dragGradients_1 = dragGradients; _g < dragGradients_1.length; _g++) {
  57836. var dragGradient = dragGradients_1[_g];
  57837. var serializedGradient = {
  57838. gradient: dragGradient.gradient,
  57839. factor1: dragGradient.factor1
  57840. };
  57841. if (dragGradient.factor2 !== undefined) {
  57842. serializedGradient.factor2 = dragGradient.factor2;
  57843. }
  57844. serializationObject.dragGradients.push(serializedGradient);
  57845. }
  57846. }
  57847. var emitRateGradients = particleSystem.getEmitRateGradients();
  57848. if (emitRateGradients) {
  57849. serializationObject.emitRateGradients = [];
  57850. for (var _h = 0, emitRateGradients_1 = emitRateGradients; _h < emitRateGradients_1.length; _h++) {
  57851. var emitRateGradient = emitRateGradients_1[_h];
  57852. var serializedGradient = {
  57853. gradient: emitRateGradient.gradient,
  57854. factor1: emitRateGradient.factor1
  57855. };
  57856. if (emitRateGradient.factor2 !== undefined) {
  57857. serializedGradient.factor2 = emitRateGradient.factor2;
  57858. }
  57859. serializationObject.emitRateGradients.push(serializedGradient);
  57860. }
  57861. }
  57862. var startSizeGradients = particleSystem.getStartSizeGradients();
  57863. if (startSizeGradients) {
  57864. serializationObject.startSizeGradients = [];
  57865. for (var _j = 0, startSizeGradients_1 = startSizeGradients; _j < startSizeGradients_1.length; _j++) {
  57866. var startSizeGradient = startSizeGradients_1[_j];
  57867. var serializedGradient = {
  57868. gradient: startSizeGradient.gradient,
  57869. factor1: startSizeGradient.factor1
  57870. };
  57871. if (startSizeGradient.factor2 !== undefined) {
  57872. serializedGradient.factor2 = startSizeGradient.factor2;
  57873. }
  57874. serializationObject.startSizeGradients.push(serializedGradient);
  57875. }
  57876. }
  57877. var limitVelocityGradients = particleSystem.getLimitVelocityGradients();
  57878. if (limitVelocityGradients) {
  57879. serializationObject.limitVelocityGradients = [];
  57880. for (var _k = 0, limitVelocityGradients_1 = limitVelocityGradients; _k < limitVelocityGradients_1.length; _k++) {
  57881. var limitVelocityGradient = limitVelocityGradients_1[_k];
  57882. var serializedGradient = {
  57883. gradient: limitVelocityGradient.gradient,
  57884. factor1: limitVelocityGradient.factor1
  57885. };
  57886. if (limitVelocityGradient.factor2 !== undefined) {
  57887. serializedGradient.factor2 = limitVelocityGradient.factor2;
  57888. }
  57889. serializationObject.limitVelocityGradients.push(serializedGradient);
  57890. }
  57891. serializationObject.limitVelocityDamping = particleSystem.limitVelocityDamping;
  57892. }
  57893. if (BABYLON.ProceduralTexture && particleSystem.noiseTexture && particleSystem.noiseTexture instanceof BABYLON.ProceduralTexture) {
  57894. var noiseTexture = particleSystem.noiseTexture;
  57895. serializationObject.noiseTexture = noiseTexture.serialize();
  57896. }
  57897. };
  57898. /** @hidden */
  57899. ParticleSystem._Parse = function (parsedParticleSystem, particleSystem, scene, rootUrl) {
  57900. // Texture
  57901. if (parsedParticleSystem.textureName) {
  57902. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  57903. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  57904. }
  57905. // Emitter
  57906. if (parsedParticleSystem.emitterId === undefined) {
  57907. particleSystem.emitter = BABYLON.Vector3.Zero();
  57908. }
  57909. else if (parsedParticleSystem.emitterId) {
  57910. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  57911. }
  57912. else {
  57913. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  57914. }
  57915. // Misc.
  57916. if (parsedParticleSystem.renderingGroupId !== undefined) {
  57917. particleSystem.renderingGroupId = parsedParticleSystem.renderingGroupId;
  57918. }
  57919. if (parsedParticleSystem.isBillboardBased !== undefined) {
  57920. particleSystem.isBillboardBased = parsedParticleSystem.isBillboardBased;
  57921. }
  57922. // Animations
  57923. if (parsedParticleSystem.animations) {
  57924. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  57925. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  57926. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  57927. }
  57928. }
  57929. if (parsedParticleSystem.autoAnimate) {
  57930. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  57931. }
  57932. // Particle system
  57933. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  57934. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  57935. particleSystem.minSize = parsedParticleSystem.minSize;
  57936. particleSystem.maxSize = parsedParticleSystem.maxSize;
  57937. if (parsedParticleSystem.minScaleX) {
  57938. particleSystem.minScaleX = parsedParticleSystem.minScaleX;
  57939. particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
  57940. particleSystem.minScaleY = parsedParticleSystem.minScaleY;
  57941. particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
  57942. }
  57943. if (parsedParticleSystem.preWarmCycles !== undefined) {
  57944. particleSystem.preWarmCycles = parsedParticleSystem.preWarmCycles;
  57945. particleSystem.preWarmStepOffset = parsedParticleSystem.preWarmStepOffset;
  57946. }
  57947. if (parsedParticleSystem.minInitialRotation !== undefined) {
  57948. particleSystem.minInitialRotation = parsedParticleSystem.minInitialRotation;
  57949. particleSystem.maxInitialRotation = parsedParticleSystem.maxInitialRotation;
  57950. }
  57951. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  57952. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  57953. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  57954. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  57955. particleSystem.emitRate = parsedParticleSystem.emitRate;
  57956. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  57957. if (parsedParticleSystem.noiseStrength) {
  57958. particleSystem.noiseStrength = BABYLON.Vector3.FromArray(parsedParticleSystem.noiseStrength);
  57959. }
  57960. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  57961. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  57962. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  57963. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  57964. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  57965. particleSystem.blendMode = parsedParticleSystem.blendMode;
  57966. if (parsedParticleSystem.colorGradients) {
  57967. for (var _i = 0, _a = parsedParticleSystem.colorGradients; _i < _a.length; _i++) {
  57968. var colorGradient = _a[_i];
  57969. particleSystem.addColorGradient(colorGradient.gradient, BABYLON.Color4.FromArray(colorGradient.color1), colorGradient.color2 ? BABYLON.Color4.FromArray(colorGradient.color2) : undefined);
  57970. }
  57971. }
  57972. if (parsedParticleSystem.rampGradients) {
  57973. for (var _b = 0, _c = parsedParticleSystem.rampGradients; _b < _c.length; _b++) {
  57974. var rampGradient = _c[_b];
  57975. particleSystem.addRampGradient(rampGradient.gradient, BABYLON.Color4.FromArray(rampGradient.color1));
  57976. }
  57977. }
  57978. if (parsedParticleSystem.colorRemapGradients) {
  57979. for (var _d = 0, _e = parsedParticleSystem.colorRemapGradients; _d < _e.length; _d++) {
  57980. var colorRemapGradient = _e[_d];
  57981. particleSystem.addColorRemapGradient(colorRemapGradient.gradient, colorRemapGradient.factor1 !== undefined ? colorRemapGradient.factor1 : colorRemapGradient.factor, colorRemapGradient.factor2);
  57982. }
  57983. }
  57984. if (parsedParticleSystem.alphaRemapGradients) {
  57985. for (var _f = 0, _g = parsedParticleSystem.alphaRemapGradients; _f < _g.length; _f++) {
  57986. var alphaRemapGradient = _g[_f];
  57987. particleSystem.addAlphaRemapGradient(alphaRemapGradient.gradient, alphaRemapGradient.factor1 !== undefined ? alphaRemapGradient.factor1 : alphaRemapGradient.factor, alphaRemapGradient.factor2);
  57988. }
  57989. }
  57990. if (parsedParticleSystem.sizeGradients) {
  57991. for (var _h = 0, _j = parsedParticleSystem.sizeGradients; _h < _j.length; _h++) {
  57992. var sizeGradient = _j[_h];
  57993. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  57994. }
  57995. }
  57996. if (parsedParticleSystem.sizeGradients) {
  57997. for (var _k = 0, _l = parsedParticleSystem.sizeGradients; _k < _l.length; _k++) {
  57998. var sizeGradient = _l[_k];
  57999. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  58000. }
  58001. }
  58002. if (parsedParticleSystem.angularSpeedGradients) {
  58003. for (var _m = 0, _o = parsedParticleSystem.angularSpeedGradients; _m < _o.length; _m++) {
  58004. var angularSpeedGradient = _o[_m];
  58005. particleSystem.addAngularSpeedGradient(angularSpeedGradient.gradient, angularSpeedGradient.factor1 !== undefined ? angularSpeedGradient.factor1 : angularSpeedGradient.factor, angularSpeedGradient.factor2);
  58006. }
  58007. }
  58008. if (parsedParticleSystem.velocityGradients) {
  58009. for (var _p = 0, _q = parsedParticleSystem.velocityGradients; _p < _q.length; _p++) {
  58010. var velocityGradient = _q[_p];
  58011. particleSystem.addVelocityGradient(velocityGradient.gradient, velocityGradient.factor1 !== undefined ? velocityGradient.factor1 : velocityGradient.factor, velocityGradient.factor2);
  58012. }
  58013. }
  58014. if (parsedParticleSystem.dragGradients) {
  58015. for (var _r = 0, _s = parsedParticleSystem.dragGradients; _r < _s.length; _r++) {
  58016. var dragGradient = _s[_r];
  58017. particleSystem.addDragGradient(dragGradient.gradient, dragGradient.factor1 !== undefined ? dragGradient.factor1 : dragGradient.factor, dragGradient.factor2);
  58018. }
  58019. }
  58020. if (parsedParticleSystem.emitRateGradients) {
  58021. for (var _t = 0, _u = parsedParticleSystem.emitRateGradients; _t < _u.length; _t++) {
  58022. var emitRateGradient = _u[_t];
  58023. particleSystem.addEmitRateGradient(emitRateGradient.gradient, emitRateGradient.factor1 !== undefined ? emitRateGradient.factor1 : emitRateGradient.factor, emitRateGradient.factor2);
  58024. }
  58025. }
  58026. if (parsedParticleSystem.startSizeGradients) {
  58027. for (var _v = 0, _w = parsedParticleSystem.startSizeGradients; _v < _w.length; _v++) {
  58028. var startSizeGradient = _w[_v];
  58029. particleSystem.addStartSizeGradient(startSizeGradient.gradient, startSizeGradient.factor1 !== undefined ? startSizeGradient.factor1 : startSizeGradient.factor, startSizeGradient.factor2);
  58030. }
  58031. }
  58032. if (parsedParticleSystem.limitVelocityGradients) {
  58033. for (var _x = 0, _y = parsedParticleSystem.limitVelocityGradients; _x < _y.length; _x++) {
  58034. var limitVelocityGradient = _y[_x];
  58035. particleSystem.addLimitVelocityGradient(limitVelocityGradient.gradient, limitVelocityGradient.factor1 !== undefined ? limitVelocityGradient.factor1 : limitVelocityGradient.factor, limitVelocityGradient.factor2);
  58036. }
  58037. particleSystem.limitVelocityDamping = parsedParticleSystem.limitVelocityDamping;
  58038. }
  58039. if (parsedParticleSystem.noiseTexture) {
  58040. particleSystem.noiseTexture = BABYLON.ProceduralTexture.Parse(parsedParticleSystem.noiseTexture, scene, rootUrl);
  58041. }
  58042. // Emitter
  58043. var emitterType;
  58044. if (parsedParticleSystem.particleEmitterType) {
  58045. switch (parsedParticleSystem.particleEmitterType.type) {
  58046. case "SphereParticleEmitter":
  58047. emitterType = new BABYLON.SphereParticleEmitter();
  58048. break;
  58049. case "SphereDirectedParticleEmitter":
  58050. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  58051. break;
  58052. case "ConeEmitter":
  58053. case "ConeParticleEmitter":
  58054. emitterType = new BABYLON.ConeParticleEmitter();
  58055. break;
  58056. case "BoxEmitter":
  58057. case "BoxParticleEmitter":
  58058. default:
  58059. emitterType = new BABYLON.BoxParticleEmitter();
  58060. break;
  58061. }
  58062. emitterType.parse(parsedParticleSystem.particleEmitterType);
  58063. }
  58064. else {
  58065. emitterType = new BABYLON.BoxParticleEmitter();
  58066. emitterType.parse(parsedParticleSystem);
  58067. }
  58068. particleSystem.particleEmitterType = emitterType;
  58069. // Animation sheet
  58070. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  58071. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  58072. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  58073. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  58074. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  58075. };
  58076. /**
  58077. * Parses a JSON object to create a particle system.
  58078. * @param parsedParticleSystem The JSON object to parse
  58079. * @param scene The scene to create the particle system in
  58080. * @param rootUrl The root url to use to load external dependencies like texture
  58081. * @returns the Parsed particle system
  58082. */
  58083. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  58084. var name = parsedParticleSystem.name;
  58085. var custom = null;
  58086. var program = null;
  58087. if (parsedParticleSystem.customShader) {
  58088. program = parsedParticleSystem.customShader;
  58089. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  58090. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  58091. }
  58092. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  58093. particleSystem.customShader = program;
  58094. if (parsedParticleSystem.id) {
  58095. particleSystem.id = parsedParticleSystem.id;
  58096. }
  58097. // Auto start
  58098. if (parsedParticleSystem.preventAutoStart) {
  58099. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  58100. }
  58101. ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  58102. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  58103. if (!particleSystem.preventAutoStart) {
  58104. particleSystem.start();
  58105. }
  58106. return particleSystem;
  58107. };
  58108. return ParticleSystem;
  58109. }(BABYLON.BaseParticleSystem));
  58110. BABYLON.ParticleSystem = ParticleSystem;
  58111. })(BABYLON || (BABYLON = {}));
  58112. //# sourceMappingURL=babylon.particleSystem.js.map
  58113. var BABYLON;
  58114. (function (BABYLON) {
  58115. /**
  58116. * Particle emitter emitting particles from the inside of a box.
  58117. * It emits the particles randomly between 2 given directions.
  58118. */
  58119. var BoxParticleEmitter = /** @class */ (function () {
  58120. /**
  58121. * Creates a new instance BoxParticleEmitter
  58122. */
  58123. function BoxParticleEmitter() {
  58124. /**
  58125. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  58126. */
  58127. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  58128. /**
  58129. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  58130. */
  58131. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  58132. /**
  58133. * 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.
  58134. */
  58135. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  58136. /**
  58137. * 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.
  58138. */
  58139. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  58140. }
  58141. /**
  58142. * Called by the particle System when the direction is computed for the created particle.
  58143. * @param worldMatrix is the world matrix of the particle system
  58144. * @param directionToUpdate is the direction vector to update with the result
  58145. * @param particle is the particle we are computed the direction for
  58146. */
  58147. BoxParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58148. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  58149. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  58150. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  58151. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  58152. };
  58153. /**
  58154. * Called by the particle System when the position is computed for the created particle.
  58155. * @param worldMatrix is the world matrix of the particle system
  58156. * @param positionToUpdate is the position vector to update with the result
  58157. * @param particle is the particle we are computed the position for
  58158. */
  58159. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  58160. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  58161. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  58162. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  58163. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  58164. };
  58165. /**
  58166. * Clones the current emitter and returns a copy of it
  58167. * @returns the new emitter
  58168. */
  58169. BoxParticleEmitter.prototype.clone = function () {
  58170. var newOne = new BoxParticleEmitter();
  58171. BABYLON.Tools.DeepCopy(this, newOne);
  58172. return newOne;
  58173. };
  58174. /**
  58175. * Called by the GPUParticleSystem to setup the update shader
  58176. * @param effect defines the update shader
  58177. */
  58178. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  58179. effect.setVector3("direction1", this.direction1);
  58180. effect.setVector3("direction2", this.direction2);
  58181. effect.setVector3("minEmitBox", this.minEmitBox);
  58182. effect.setVector3("maxEmitBox", this.maxEmitBox);
  58183. };
  58184. /**
  58185. * Returns a string to use to update the GPU particles update shader
  58186. * @returns a string containng the defines string
  58187. */
  58188. BoxParticleEmitter.prototype.getEffectDefines = function () {
  58189. return "#define BOXEMITTER";
  58190. };
  58191. /**
  58192. * Returns the string "BoxParticleEmitter"
  58193. * @returns a string containing the class name
  58194. */
  58195. BoxParticleEmitter.prototype.getClassName = function () {
  58196. return "BoxParticleEmitter";
  58197. };
  58198. /**
  58199. * Serializes the particle system to a JSON object.
  58200. * @returns the JSON object
  58201. */
  58202. BoxParticleEmitter.prototype.serialize = function () {
  58203. var serializationObject = {};
  58204. serializationObject.type = this.getClassName();
  58205. serializationObject.direction1 = this.direction1.asArray();
  58206. serializationObject.direction2 = this.direction2.asArray();
  58207. serializationObject.minEmitBox = this.minEmitBox.asArray();
  58208. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  58209. return serializationObject;
  58210. };
  58211. /**
  58212. * Parse properties from a JSON object
  58213. * @param serializationObject defines the JSON object
  58214. */
  58215. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  58216. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  58217. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  58218. BABYLON.Vector3.FromArrayToRef(serializationObject.minEmitBox, 0, this.minEmitBox);
  58219. BABYLON.Vector3.FromArrayToRef(serializationObject.maxEmitBox, 0, this.maxEmitBox);
  58220. };
  58221. return BoxParticleEmitter;
  58222. }());
  58223. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  58224. })(BABYLON || (BABYLON = {}));
  58225. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  58226. var BABYLON;
  58227. (function (BABYLON) {
  58228. /**
  58229. * Particle emitter emitting particles from the inside of a cylinder.
  58230. * It emits the particles alongside the cylinder radius. The emission direction might be randomized.
  58231. */
  58232. var CylinderParticleEmitter = /** @class */ (function () {
  58233. /**
  58234. * Creates a new instance CylinderParticleEmitter
  58235. * @param radius the radius of the emission cylinder (1 by default)
  58236. * @param height the height of the emission cylinder (1 by default)
  58237. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  58238. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  58239. */
  58240. function CylinderParticleEmitter(
  58241. /**
  58242. * The radius of the emission cylinder.
  58243. */
  58244. radius,
  58245. /**
  58246. * The height of the emission cylinder.
  58247. */
  58248. height,
  58249. /**
  58250. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  58251. */
  58252. radiusRange,
  58253. /**
  58254. * How much to randomize the particle direction [0-1].
  58255. */
  58256. directionRandomizer) {
  58257. if (radius === void 0) { radius = 1; }
  58258. if (height === void 0) { height = 1; }
  58259. if (radiusRange === void 0) { radiusRange = 1; }
  58260. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  58261. this.radius = radius;
  58262. this.height = height;
  58263. this.radiusRange = radiusRange;
  58264. this.directionRandomizer = directionRandomizer;
  58265. }
  58266. /**
  58267. * Called by the particle System when the direction is computed for the created particle.
  58268. * @param worldMatrix is the world matrix of the particle system
  58269. * @param directionToUpdate is the direction vector to update with the result
  58270. * @param particle is the particle we are computed the direction for
  58271. */
  58272. CylinderParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58273. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  58274. var randY = BABYLON.Scalar.RandomRange(-this.directionRandomizer / 2, this.directionRandomizer / 2);
  58275. var angle = Math.atan2(direction.x, direction.z);
  58276. angle += BABYLON.Scalar.RandomRange(-Math.PI / 2, Math.PI / 2) * this.directionRandomizer;
  58277. direction.y = randY; // set direction y to rand y to mirror normal of cylinder surface
  58278. direction.x = Math.sin(angle);
  58279. direction.z = Math.cos(angle);
  58280. direction.normalize();
  58281. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  58282. };
  58283. /**
  58284. * Called by the particle System when the position is computed for the created particle.
  58285. * @param worldMatrix is the world matrix of the particle system
  58286. * @param positionToUpdate is the position vector to update with the result
  58287. * @param particle is the particle we are computed the position for
  58288. */
  58289. CylinderParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  58290. var yPos = BABYLON.Scalar.RandomRange(-this.height / 2, this.height / 2);
  58291. var angle = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  58292. // Pick a properly distributed point within the circle https://programming.guide/random-point-within-circle.html
  58293. var radiusDistribution = BABYLON.Scalar.RandomRange((1 - this.radiusRange) * (1 - this.radiusRange), 1);
  58294. var positionRadius = Math.sqrt(radiusDistribution) * this.radius;
  58295. var xPos = positionRadius * Math.cos(angle);
  58296. var zPos = positionRadius * Math.sin(angle);
  58297. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(xPos, yPos, zPos, worldMatrix, positionToUpdate);
  58298. };
  58299. /**
  58300. * Clones the current emitter and returns a copy of it
  58301. * @returns the new emitter
  58302. */
  58303. CylinderParticleEmitter.prototype.clone = function () {
  58304. var newOne = new CylinderParticleEmitter(this.radius, this.directionRandomizer);
  58305. BABYLON.Tools.DeepCopy(this, newOne);
  58306. return newOne;
  58307. };
  58308. /**
  58309. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  58310. * @param effect defines the update shader
  58311. */
  58312. CylinderParticleEmitter.prototype.applyToShader = function (effect) {
  58313. effect.setFloat("radius", this.radius);
  58314. effect.setFloat("height", this.height);
  58315. effect.setFloat("radiusRange", this.radiusRange);
  58316. effect.setFloat("directionRandomizer", this.directionRandomizer);
  58317. };
  58318. /**
  58319. * Returns a string to use to update the GPU particles update shader
  58320. * @returns a string containng the defines string
  58321. */
  58322. CylinderParticleEmitter.prototype.getEffectDefines = function () {
  58323. return "#define CYLINDEREMITTER";
  58324. };
  58325. /**
  58326. * Returns the string "CylinderParticleEmitter"
  58327. * @returns a string containing the class name
  58328. */
  58329. CylinderParticleEmitter.prototype.getClassName = function () {
  58330. return "CylinderParticleEmitter";
  58331. };
  58332. /**
  58333. * Serializes the particle system to a JSON object.
  58334. * @returns the JSON object
  58335. */
  58336. CylinderParticleEmitter.prototype.serialize = function () {
  58337. var serializationObject = {};
  58338. serializationObject.type = this.getClassName();
  58339. serializationObject.radius = this.radius;
  58340. serializationObject.height = this.height;
  58341. serializationObject.radiusRange = this.radiusRange;
  58342. serializationObject.directionRandomizer = this.directionRandomizer;
  58343. return serializationObject;
  58344. };
  58345. /**
  58346. * Parse properties from a JSON object
  58347. * @param serializationObject defines the JSON object
  58348. */
  58349. CylinderParticleEmitter.prototype.parse = function (serializationObject) {
  58350. this.radius = serializationObject.radius;
  58351. this.height = serializationObject.height;
  58352. this.radiusRange = serializationObject.radiusRange;
  58353. this.directionRandomizer = serializationObject.directionRandomizer;
  58354. };
  58355. return CylinderParticleEmitter;
  58356. }());
  58357. BABYLON.CylinderParticleEmitter = CylinderParticleEmitter;
  58358. /**
  58359. * Particle emitter emitting particles from the inside of a cylinder.
  58360. * It emits the particles randomly between two vectors.
  58361. */
  58362. var CylinderDirectedParticleEmitter = /** @class */ (function (_super) {
  58363. __extends(CylinderDirectedParticleEmitter, _super);
  58364. /**
  58365. * Creates a new instance CylinderDirectedParticleEmitter
  58366. * @param radius the radius of the emission cylinder (1 by default)
  58367. * @param height the height of the emission cylinder (1 by default)
  58368. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  58369. * @param direction1 the min limit of the emission direction (up vector by default)
  58370. * @param direction2 the max limit of the emission direction (up vector by default)
  58371. */
  58372. function CylinderDirectedParticleEmitter(radius, height, radiusRange,
  58373. /**
  58374. * The min limit of the emission direction.
  58375. */
  58376. direction1,
  58377. /**
  58378. * The max limit of the emission direction.
  58379. */
  58380. direction2) {
  58381. if (radius === void 0) { radius = 1; }
  58382. if (height === void 0) { height = 1; }
  58383. if (radiusRange === void 0) { radiusRange = 1; }
  58384. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  58385. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  58386. var _this = _super.call(this, radius, height, radiusRange) || this;
  58387. _this.direction1 = direction1;
  58388. _this.direction2 = direction2;
  58389. return _this;
  58390. }
  58391. /**
  58392. * Called by the particle System when the direction is computed for the created particle.
  58393. * @param worldMatrix is the world matrix of the particle system
  58394. * @param directionToUpdate is the direction vector to update with the result
  58395. * @param particle is the particle we are computed the direction for
  58396. */
  58397. CylinderDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58398. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  58399. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  58400. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  58401. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  58402. };
  58403. /**
  58404. * Clones the current emitter and returns a copy of it
  58405. * @returns the new emitter
  58406. */
  58407. CylinderDirectedParticleEmitter.prototype.clone = function () {
  58408. var newOne = new CylinderDirectedParticleEmitter(this.radius, this.height, this.radiusRange, this.direction1, this.direction2);
  58409. BABYLON.Tools.DeepCopy(this, newOne);
  58410. return newOne;
  58411. };
  58412. /**
  58413. * Called by the GPUParticleSystem to setup the update shader
  58414. * @param effect defines the update shader
  58415. */
  58416. CylinderDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  58417. effect.setFloat("radius", this.radius);
  58418. effect.setFloat("height", this.height);
  58419. effect.setFloat("radiusRange", this.radiusRange);
  58420. effect.setVector3("direction1", this.direction1);
  58421. effect.setVector3("direction2", this.direction2);
  58422. };
  58423. /**
  58424. * Returns a string to use to update the GPU particles update shader
  58425. * @returns a string containng the defines string
  58426. */
  58427. CylinderDirectedParticleEmitter.prototype.getEffectDefines = function () {
  58428. return "#define CYLINDEREMITTER\n#define DIRECTEDCYLINDEREMITTER";
  58429. };
  58430. /**
  58431. * Returns the string "CylinderDirectedParticleEmitter"
  58432. * @returns a string containing the class name
  58433. */
  58434. CylinderDirectedParticleEmitter.prototype.getClassName = function () {
  58435. return "CylinderDirectedParticleEmitter";
  58436. };
  58437. /**
  58438. * Serializes the particle system to a JSON object.
  58439. * @returns the JSON object
  58440. */
  58441. CylinderDirectedParticleEmitter.prototype.serialize = function () {
  58442. var serializationObject = _super.prototype.serialize.call(this);
  58443. serializationObject.direction1 = this.direction1.asArray();
  58444. serializationObject.direction2 = this.direction2.asArray();
  58445. return serializationObject;
  58446. };
  58447. /**
  58448. * Parse properties from a JSON object
  58449. * @param serializationObject defines the JSON object
  58450. */
  58451. CylinderDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  58452. _super.prototype.parse.call(this, serializationObject);
  58453. this.direction1.copyFrom(serializationObject.direction1);
  58454. this.direction2.copyFrom(serializationObject.direction2);
  58455. };
  58456. return CylinderDirectedParticleEmitter;
  58457. }(CylinderParticleEmitter));
  58458. BABYLON.CylinderDirectedParticleEmitter = CylinderDirectedParticleEmitter;
  58459. })(BABYLON || (BABYLON = {}));
  58460. //# sourceMappingURL=babylon.cylinderParticleEmitter.js.map
  58461. var BABYLON;
  58462. (function (BABYLON) {
  58463. /**
  58464. * Particle emitter emitting particles from the inside of a cone.
  58465. * It emits the particles alongside the cone volume from the base to the particle.
  58466. * The emission direction might be randomized.
  58467. */
  58468. var ConeParticleEmitter = /** @class */ (function () {
  58469. /**
  58470. * Creates a new instance ConeParticleEmitter
  58471. * @param radius the radius of the emission cone (1 by default)
  58472. * @param angles the cone base angle (PI by default)
  58473. * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0)
  58474. */
  58475. function ConeParticleEmitter(radius, angle,
  58476. /** defines how much to randomize the particle direction [0-1] (default is 0) */
  58477. directionRandomizer) {
  58478. if (radius === void 0) { radius = 1; }
  58479. if (angle === void 0) { angle = Math.PI; }
  58480. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  58481. this.directionRandomizer = directionRandomizer;
  58482. /**
  58483. * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)
  58484. */
  58485. this.radiusRange = 1;
  58486. /**
  58487. * Gets or sets a value indicating where on the height the start position should be picked (1 = everywhere, 0 = only surface)
  58488. */
  58489. this.heightRange = 1;
  58490. /**
  58491. * Gets or sets a value indicating if all the particles should be emitted from the spawn point only (the base of the cone)
  58492. */
  58493. this.emitFromSpawnPointOnly = false;
  58494. this.angle = angle;
  58495. this.radius = radius;
  58496. }
  58497. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  58498. /**
  58499. * Gets or sets the radius of the emission cone
  58500. */
  58501. get: function () {
  58502. return this._radius;
  58503. },
  58504. set: function (value) {
  58505. this._radius = value;
  58506. this._buildHeight();
  58507. },
  58508. enumerable: true,
  58509. configurable: true
  58510. });
  58511. Object.defineProperty(ConeParticleEmitter.prototype, "angle", {
  58512. /**
  58513. * Gets or sets the angle of the emission cone
  58514. */
  58515. get: function () {
  58516. return this._angle;
  58517. },
  58518. set: function (value) {
  58519. this._angle = value;
  58520. this._buildHeight();
  58521. },
  58522. enumerable: true,
  58523. configurable: true
  58524. });
  58525. ConeParticleEmitter.prototype._buildHeight = function () {
  58526. if (this._angle !== 0) {
  58527. this._height = this._radius / Math.tan(this._angle / 2);
  58528. }
  58529. else {
  58530. this._height = 1;
  58531. }
  58532. };
  58533. /**
  58534. * Called by the particle System when the direction is computed for the created particle.
  58535. * @param worldMatrix is the world matrix of the particle system
  58536. * @param directionToUpdate is the direction vector to update with the result
  58537. * @param particle is the particle we are computed the direction for
  58538. */
  58539. ConeParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58540. if (Math.abs(Math.cos(this._angle)) === 1.0) {
  58541. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, 1.0, 0, worldMatrix, directionToUpdate);
  58542. }
  58543. else {
  58544. // measure the direction Vector from the emitter to the particle.
  58545. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  58546. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58547. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58548. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58549. direction.x += randX;
  58550. direction.y += randY;
  58551. direction.z += randZ;
  58552. direction.normalize();
  58553. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  58554. }
  58555. };
  58556. /**
  58557. * Called by the particle System when the position is computed for the created particle.
  58558. * @param worldMatrix is the world matrix of the particle system
  58559. * @param positionToUpdate is the position vector to update with the result
  58560. * @param particle is the particle we are computed the position for
  58561. */
  58562. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  58563. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  58564. var h;
  58565. if (!this.emitFromSpawnPointOnly) {
  58566. h = BABYLON.Scalar.RandomRange(0, this.heightRange);
  58567. // Better distribution in a cone at normal angles.
  58568. h = 1 - h * h;
  58569. }
  58570. else {
  58571. h = 0.0001;
  58572. }
  58573. var radius = this._radius - BABYLON.Scalar.RandomRange(0, this._radius * this.radiusRange);
  58574. radius = radius * h;
  58575. var randX = radius * Math.sin(s);
  58576. var randZ = radius * Math.cos(s);
  58577. var randY = h * this._height;
  58578. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  58579. };
  58580. /**
  58581. * Clones the current emitter and returns a copy of it
  58582. * @returns the new emitter
  58583. */
  58584. ConeParticleEmitter.prototype.clone = function () {
  58585. var newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer);
  58586. BABYLON.Tools.DeepCopy(this, newOne);
  58587. return newOne;
  58588. };
  58589. /**
  58590. * Called by the GPUParticleSystem to setup the update shader
  58591. * @param effect defines the update shader
  58592. */
  58593. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  58594. effect.setFloat2("radius", this._radius, this.radiusRange);
  58595. effect.setFloat("coneAngle", this._angle);
  58596. effect.setFloat2("height", this._height, this.heightRange);
  58597. effect.setFloat("directionRandomizer", this.directionRandomizer);
  58598. };
  58599. /**
  58600. * Returns a string to use to update the GPU particles update shader
  58601. * @returns a string containng the defines string
  58602. */
  58603. ConeParticleEmitter.prototype.getEffectDefines = function () {
  58604. var defines = "#define CONEEMITTER";
  58605. if (this.emitFromSpawnPointOnly) {
  58606. defines += "\n#define CONEEMITTERSPAWNPOINT";
  58607. }
  58608. return defines;
  58609. };
  58610. /**
  58611. * Returns the string "ConeParticleEmitter"
  58612. * @returns a string containing the class name
  58613. */
  58614. ConeParticleEmitter.prototype.getClassName = function () {
  58615. return "ConeParticleEmitter";
  58616. };
  58617. /**
  58618. * Serializes the particle system to a JSON object.
  58619. * @returns the JSON object
  58620. */
  58621. ConeParticleEmitter.prototype.serialize = function () {
  58622. var serializationObject = {};
  58623. serializationObject.type = this.getClassName();
  58624. serializationObject.radius = this._radius;
  58625. serializationObject.angle = this._angle;
  58626. serializationObject.directionRandomizer = this.directionRandomizer;
  58627. return serializationObject;
  58628. };
  58629. /**
  58630. * Parse properties from a JSON object
  58631. * @param serializationObject defines the JSON object
  58632. */
  58633. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  58634. this.radius = serializationObject.radius;
  58635. this.angle = serializationObject.angle;
  58636. this.directionRandomizer = serializationObject.directionRandomizer;
  58637. };
  58638. return ConeParticleEmitter;
  58639. }());
  58640. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  58641. })(BABYLON || (BABYLON = {}));
  58642. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  58643. var BABYLON;
  58644. (function (BABYLON) {
  58645. /**
  58646. * Particle emitter emitting particles from the inside of a sphere.
  58647. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  58648. */
  58649. var SphereParticleEmitter = /** @class */ (function () {
  58650. /**
  58651. * Creates a new instance SphereParticleEmitter
  58652. * @param radius the radius of the emission sphere (1 by default)
  58653. * @param radiusRange the range of the emission sphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  58654. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  58655. */
  58656. function SphereParticleEmitter(
  58657. /**
  58658. * The radius of the emission sphere.
  58659. */
  58660. radius,
  58661. /**
  58662. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  58663. */
  58664. radiusRange,
  58665. /**
  58666. * How much to randomize the particle direction [0-1].
  58667. */
  58668. directionRandomizer) {
  58669. if (radius === void 0) { radius = 1; }
  58670. if (radiusRange === void 0) { radiusRange = 1; }
  58671. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  58672. this.radius = radius;
  58673. this.radiusRange = radiusRange;
  58674. this.directionRandomizer = directionRandomizer;
  58675. }
  58676. /**
  58677. * Called by the particle System when the direction is computed for the created particle.
  58678. * @param worldMatrix is the world matrix of the particle system
  58679. * @param directionToUpdate is the direction vector to update with the result
  58680. * @param particle is the particle we are computed the direction for
  58681. */
  58682. SphereParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58683. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  58684. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58685. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58686. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58687. direction.x += randX;
  58688. direction.y += randY;
  58689. direction.z += randZ;
  58690. direction.normalize();
  58691. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  58692. };
  58693. /**
  58694. * Called by the particle System when the position is computed for the created particle.
  58695. * @param worldMatrix is the world matrix of the particle system
  58696. * @param positionToUpdate is the position vector to update with the result
  58697. * @param particle is the particle we are computed the position for
  58698. */
  58699. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  58700. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  58701. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  58702. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  58703. var theta = Math.acos(2 * v - 1);
  58704. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  58705. var randY = randRadius * Math.cos(theta);
  58706. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  58707. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  58708. };
  58709. /**
  58710. * Clones the current emitter and returns a copy of it
  58711. * @returns the new emitter
  58712. */
  58713. SphereParticleEmitter.prototype.clone = function () {
  58714. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  58715. BABYLON.Tools.DeepCopy(this, newOne);
  58716. return newOne;
  58717. };
  58718. /**
  58719. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  58720. * @param effect defines the update shader
  58721. */
  58722. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  58723. effect.setFloat("radius", this.radius);
  58724. effect.setFloat("radiusRange", this.radiusRange);
  58725. effect.setFloat("directionRandomizer", this.directionRandomizer);
  58726. };
  58727. /**
  58728. * Returns a string to use to update the GPU particles update shader
  58729. * @returns a string containng the defines string
  58730. */
  58731. SphereParticleEmitter.prototype.getEffectDefines = function () {
  58732. return "#define SPHEREEMITTER";
  58733. };
  58734. /**
  58735. * Returns the string "SphereParticleEmitter"
  58736. * @returns a string containing the class name
  58737. */
  58738. SphereParticleEmitter.prototype.getClassName = function () {
  58739. return "SphereParticleEmitter";
  58740. };
  58741. /**
  58742. * Serializes the particle system to a JSON object.
  58743. * @returns the JSON object
  58744. */
  58745. SphereParticleEmitter.prototype.serialize = function () {
  58746. var serializationObject = {};
  58747. serializationObject.type = this.getClassName();
  58748. serializationObject.radius = this.radius;
  58749. serializationObject.radiusRange = this.radiusRange;
  58750. serializationObject.directionRandomizer = this.directionRandomizer;
  58751. return serializationObject;
  58752. };
  58753. /**
  58754. * Parse properties from a JSON object
  58755. * @param serializationObject defines the JSON object
  58756. */
  58757. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  58758. this.radius = serializationObject.radius;
  58759. this.radiusRange = serializationObject.radiusRange;
  58760. this.directionRandomizer = serializationObject.directionRandomizer;
  58761. };
  58762. return SphereParticleEmitter;
  58763. }());
  58764. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  58765. /**
  58766. * Particle emitter emitting particles from the inside of a sphere.
  58767. * It emits the particles randomly between two vectors.
  58768. */
  58769. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  58770. __extends(SphereDirectedParticleEmitter, _super);
  58771. /**
  58772. * Creates a new instance SphereDirectedParticleEmitter
  58773. * @param radius the radius of the emission sphere (1 by default)
  58774. * @param direction1 the min limit of the emission direction (up vector by default)
  58775. * @param direction2 the max limit of the emission direction (up vector by default)
  58776. */
  58777. function SphereDirectedParticleEmitter(radius,
  58778. /**
  58779. * The min limit of the emission direction.
  58780. */
  58781. direction1,
  58782. /**
  58783. * The max limit of the emission direction.
  58784. */
  58785. direction2) {
  58786. if (radius === void 0) { radius = 1; }
  58787. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  58788. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  58789. var _this = _super.call(this, radius) || this;
  58790. _this.direction1 = direction1;
  58791. _this.direction2 = direction2;
  58792. return _this;
  58793. }
  58794. /**
  58795. * Called by the particle System when the direction is computed for the created particle.
  58796. * @param worldMatrix is the world matrix of the particle system
  58797. * @param directionToUpdate is the direction vector to update with the result
  58798. * @param particle is the particle we are computed the direction for
  58799. */
  58800. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58801. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  58802. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  58803. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  58804. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  58805. };
  58806. /**
  58807. * Clones the current emitter and returns a copy of it
  58808. * @returns the new emitter
  58809. */
  58810. SphereDirectedParticleEmitter.prototype.clone = function () {
  58811. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  58812. BABYLON.Tools.DeepCopy(this, newOne);
  58813. return newOne;
  58814. };
  58815. /**
  58816. * Called by the GPUParticleSystem to setup the update shader
  58817. * @param effect defines the update shader
  58818. */
  58819. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  58820. effect.setFloat("radius", this.radius);
  58821. effect.setFloat("radiusRange", this.radiusRange);
  58822. effect.setVector3("direction1", this.direction1);
  58823. effect.setVector3("direction2", this.direction2);
  58824. };
  58825. /**
  58826. * Returns a string to use to update the GPU particles update shader
  58827. * @returns a string containng the defines string
  58828. */
  58829. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  58830. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  58831. };
  58832. /**
  58833. * Returns the string "SphereDirectedParticleEmitter"
  58834. * @returns a string containing the class name
  58835. */
  58836. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  58837. return "SphereDirectedParticleEmitter";
  58838. };
  58839. /**
  58840. * Serializes the particle system to a JSON object.
  58841. * @returns the JSON object
  58842. */
  58843. SphereDirectedParticleEmitter.prototype.serialize = function () {
  58844. var serializationObject = _super.prototype.serialize.call(this);
  58845. serializationObject.direction1 = this.direction1.asArray();
  58846. serializationObject.direction2 = this.direction2.asArray();
  58847. return serializationObject;
  58848. };
  58849. /**
  58850. * Parse properties from a JSON object
  58851. * @param serializationObject defines the JSON object
  58852. */
  58853. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  58854. _super.prototype.parse.call(this, serializationObject);
  58855. this.direction1.copyFrom(serializationObject.direction1);
  58856. this.direction2.copyFrom(serializationObject.direction2);
  58857. };
  58858. return SphereDirectedParticleEmitter;
  58859. }(SphereParticleEmitter));
  58860. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  58861. })(BABYLON || (BABYLON = {}));
  58862. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  58863. var BABYLON;
  58864. (function (BABYLON) {
  58865. /**
  58866. * Particle emitter emitting particles from the inside of a hemisphere.
  58867. * It emits the particles alongside the hemisphere radius. The emission direction might be randomized.
  58868. */
  58869. var HemisphericParticleEmitter = /** @class */ (function () {
  58870. /**
  58871. * Creates a new instance HemisphericParticleEmitter
  58872. * @param radius the radius of the emission hemisphere (1 by default)
  58873. * @param radiusRange the range of the emission hemisphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  58874. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  58875. */
  58876. function HemisphericParticleEmitter(
  58877. /**
  58878. * The radius of the emission hemisphere.
  58879. */
  58880. radius,
  58881. /**
  58882. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  58883. */
  58884. radiusRange,
  58885. /**
  58886. * How much to randomize the particle direction [0-1].
  58887. */
  58888. directionRandomizer) {
  58889. if (radius === void 0) { radius = 1; }
  58890. if (radiusRange === void 0) { radiusRange = 1; }
  58891. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  58892. this.radius = radius;
  58893. this.radiusRange = radiusRange;
  58894. this.directionRandomizer = directionRandomizer;
  58895. }
  58896. /**
  58897. * Called by the particle System when the direction is computed for the created particle.
  58898. * @param worldMatrix is the world matrix of the particle system
  58899. * @param directionToUpdate is the direction vector to update with the result
  58900. * @param particle is the particle we are computed the direction for
  58901. */
  58902. HemisphericParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58903. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  58904. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58905. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58906. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58907. direction.x += randX;
  58908. direction.y += randY;
  58909. direction.z += randZ;
  58910. direction.normalize();
  58911. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  58912. };
  58913. /**
  58914. * Called by the particle System when the position is computed for the created particle.
  58915. * @param worldMatrix is the world matrix of the particle system
  58916. * @param positionToUpdate is the position vector to update with the result
  58917. * @param particle is the particle we are computed the position for
  58918. */
  58919. HemisphericParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  58920. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  58921. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  58922. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  58923. var theta = Math.acos(2 * v - 1);
  58924. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  58925. var randY = randRadius * Math.cos(theta);
  58926. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  58927. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, Math.abs(randY), randZ, worldMatrix, positionToUpdate);
  58928. };
  58929. /**
  58930. * Clones the current emitter and returns a copy of it
  58931. * @returns the new emitter
  58932. */
  58933. HemisphericParticleEmitter.prototype.clone = function () {
  58934. var newOne = new HemisphericParticleEmitter(this.radius, this.directionRandomizer);
  58935. BABYLON.Tools.DeepCopy(this, newOne);
  58936. return newOne;
  58937. };
  58938. /**
  58939. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  58940. * @param effect defines the update shader
  58941. */
  58942. HemisphericParticleEmitter.prototype.applyToShader = function (effect) {
  58943. effect.setFloat("radius", this.radius);
  58944. effect.setFloat("radiusRange", this.radiusRange);
  58945. effect.setFloat("directionRandomizer", this.directionRandomizer);
  58946. };
  58947. /**
  58948. * Returns a string to use to update the GPU particles update shader
  58949. * @returns a string containng the defines string
  58950. */
  58951. HemisphericParticleEmitter.prototype.getEffectDefines = function () {
  58952. return "#define HEMISPHERICEMITTER";
  58953. };
  58954. /**
  58955. * Returns the string "HemisphericParticleEmitter"
  58956. * @returns a string containing the class name
  58957. */
  58958. HemisphericParticleEmitter.prototype.getClassName = function () {
  58959. return "HemisphericParticleEmitter";
  58960. };
  58961. /**
  58962. * Serializes the particle system to a JSON object.
  58963. * @returns the JSON object
  58964. */
  58965. HemisphericParticleEmitter.prototype.serialize = function () {
  58966. var serializationObject = {};
  58967. serializationObject.type = this.getClassName();
  58968. serializationObject.radius = this.radius;
  58969. serializationObject.radiusRange = this.radiusRange;
  58970. serializationObject.directionRandomizer = this.directionRandomizer;
  58971. return serializationObject;
  58972. };
  58973. /**
  58974. * Parse properties from a JSON object
  58975. * @param serializationObject defines the JSON object
  58976. */
  58977. HemisphericParticleEmitter.prototype.parse = function (serializationObject) {
  58978. this.radius = serializationObject.radius;
  58979. this.radiusRange = serializationObject.radiusRange;
  58980. this.directionRandomizer = serializationObject.directionRandomizer;
  58981. };
  58982. return HemisphericParticleEmitter;
  58983. }());
  58984. BABYLON.HemisphericParticleEmitter = HemisphericParticleEmitter;
  58985. })(BABYLON || (BABYLON = {}));
  58986. //# sourceMappingURL=babylon.hemisphericParticleEmitter.js.map
  58987. var BABYLON;
  58988. (function (BABYLON) {
  58989. /**
  58990. * Particle emitter emitting particles from a point.
  58991. * It emits the particles randomly between 2 given directions.
  58992. */
  58993. var PointParticleEmitter = /** @class */ (function () {
  58994. /**
  58995. * Creates a new instance PointParticleEmitter
  58996. */
  58997. function PointParticleEmitter() {
  58998. /**
  58999. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  59000. */
  59001. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  59002. /**
  59003. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  59004. */
  59005. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  59006. }
  59007. /**
  59008. * Called by the particle System when the direction is computed for the created particle.
  59009. * @param worldMatrix is the world matrix of the particle system
  59010. * @param directionToUpdate is the direction vector to update with the result
  59011. * @param particle is the particle we are computed the direction for
  59012. */
  59013. PointParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  59014. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  59015. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  59016. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  59017. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  59018. };
  59019. /**
  59020. * Called by the particle System when the position is computed for the created particle.
  59021. * @param worldMatrix is the world matrix of the particle system
  59022. * @param positionToUpdate is the position vector to update with the result
  59023. * @param particle is the particle we are computed the position for
  59024. */
  59025. PointParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  59026. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0, 0, 0, worldMatrix, positionToUpdate);
  59027. };
  59028. /**
  59029. * Clones the current emitter and returns a copy of it
  59030. * @returns the new emitter
  59031. */
  59032. PointParticleEmitter.prototype.clone = function () {
  59033. var newOne = new PointParticleEmitter();
  59034. BABYLON.Tools.DeepCopy(this, newOne);
  59035. return newOne;
  59036. };
  59037. /**
  59038. * Called by the GPUParticleSystem to setup the update shader
  59039. * @param effect defines the update shader
  59040. */
  59041. PointParticleEmitter.prototype.applyToShader = function (effect) {
  59042. effect.setVector3("direction1", this.direction1);
  59043. effect.setVector3("direction2", this.direction2);
  59044. };
  59045. /**
  59046. * Returns a string to use to update the GPU particles update shader
  59047. * @returns a string containng the defines string
  59048. */
  59049. PointParticleEmitter.prototype.getEffectDefines = function () {
  59050. return "#define POINTEMITTER";
  59051. };
  59052. /**
  59053. * Returns the string "PointParticleEmitter"
  59054. * @returns a string containing the class name
  59055. */
  59056. PointParticleEmitter.prototype.getClassName = function () {
  59057. return "PointParticleEmitter";
  59058. };
  59059. /**
  59060. * Serializes the particle system to a JSON object.
  59061. * @returns the JSON object
  59062. */
  59063. PointParticleEmitter.prototype.serialize = function () {
  59064. var serializationObject = {};
  59065. serializationObject.type = this.getClassName();
  59066. serializationObject.direction1 = this.direction1.asArray();
  59067. serializationObject.direction2 = this.direction2.asArray();
  59068. return serializationObject;
  59069. };
  59070. /**
  59071. * Parse properties from a JSON object
  59072. * @param serializationObject defines the JSON object
  59073. */
  59074. PointParticleEmitter.prototype.parse = function (serializationObject) {
  59075. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  59076. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  59077. };
  59078. return PointParticleEmitter;
  59079. }());
  59080. BABYLON.PointParticleEmitter = PointParticleEmitter;
  59081. })(BABYLON || (BABYLON = {}));
  59082. //# sourceMappingURL=babylon.pointParticleEmitter.js.map
  59083. var BABYLON;
  59084. (function (BABYLON) {
  59085. // Adds the parsers to the scene parsers.
  59086. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedData, scene, container, rootUrl) {
  59087. var individualParser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  59088. if (!individualParser) {
  59089. return;
  59090. }
  59091. // Particles Systems
  59092. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  59093. for (var index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  59094. var parsedParticleSystem = parsedData.particleSystems[index];
  59095. container.particleSystems.push(individualParser(parsedParticleSystem, scene, rootUrl));
  59096. }
  59097. }
  59098. });
  59099. BABYLON.AbstractScene.AddIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedParticleSystem, scene, rootUrl) {
  59100. if (parsedParticleSystem.activeParticleCount) {
  59101. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  59102. return ps;
  59103. }
  59104. else {
  59105. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  59106. return ps;
  59107. }
  59108. });
  59109. BABYLON.Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  59110. if (uniformsNames === void 0) { uniformsNames = []; }
  59111. if (samplers === void 0) { samplers = []; }
  59112. if (defines === void 0) { defines = ""; }
  59113. var attributesNamesOrOptions = BABYLON.ParticleSystem._GetAttributeNamesOrOptions();
  59114. var effectCreationOption = BABYLON.ParticleSystem._GetEffectCreationOptions();
  59115. if (defines.indexOf(" BILLBOARD") === -1) {
  59116. defines += "\n#define BILLBOARD\n";
  59117. }
  59118. if (samplers.indexOf("diffuseSampler") === -1) {
  59119. samplers.push("diffuseSampler");
  59120. }
  59121. return this.createEffect({
  59122. vertex: "particles",
  59123. fragmentElement: fragmentName
  59124. }, attributesNamesOrOptions, effectCreationOption.concat(uniformsNames), samplers, defines, fallbacks, onCompiled, onError);
  59125. };
  59126. })(BABYLON || (BABYLON = {}));
  59127. //# sourceMappingURL=babylon.particleSystemComponent.js.map
  59128. var BABYLON;
  59129. (function (BABYLON) {
  59130. /**
  59131. * Type of sub emitter
  59132. */
  59133. var SubEmitterType;
  59134. (function (SubEmitterType) {
  59135. /**
  59136. * Attached to the particle over it's lifetime
  59137. */
  59138. SubEmitterType[SubEmitterType["ATTACHED"] = 0] = "ATTACHED";
  59139. /**
  59140. * Created when the particle dies
  59141. */
  59142. SubEmitterType[SubEmitterType["END"] = 1] = "END";
  59143. })(SubEmitterType = BABYLON.SubEmitterType || (BABYLON.SubEmitterType = {}));
  59144. /**
  59145. * Sub emitter class used to emit particles from an existing particle
  59146. */
  59147. var SubEmitter = /** @class */ (function () {
  59148. /**
  59149. * Creates a sub emitter
  59150. * @param particleSystem the particle system to be used by the sub emitter
  59151. */
  59152. function SubEmitter(
  59153. /**
  59154. * the particle system to be used by the sub emitter
  59155. */
  59156. particleSystem) {
  59157. this.particleSystem = particleSystem;
  59158. /**
  59159. * Type of the submitter (Default: END)
  59160. */
  59161. this.type = SubEmitterType.END;
  59162. /**
  59163. * If the particle should inherit the direction from the particle it's attached to. (+Y will face the direction the particle is moving) (Default: false)
  59164. * Note: This only is supported when using an emitter of type Mesh
  59165. */
  59166. this.inheritDirection = false;
  59167. /**
  59168. * How much of the attached particles speed should be added to the sub emitted particle (default: 0)
  59169. */
  59170. this.inheritedVelocityAmount = 0;
  59171. }
  59172. /**
  59173. * Clones the sub emitter
  59174. * @returns the cloned sub emitter
  59175. */
  59176. SubEmitter.prototype.clone = function () {
  59177. // Clone particle system
  59178. var emitter = this.particleSystem.emitter;
  59179. if (!emitter) {
  59180. emitter = new BABYLON.Vector3();
  59181. }
  59182. else if (emitter instanceof BABYLON.Vector3) {
  59183. emitter = emitter.clone();
  59184. }
  59185. else if (emitter instanceof BABYLON.AbstractMesh) {
  59186. emitter = new BABYLON.Mesh("", emitter._scene);
  59187. }
  59188. var clone = new SubEmitter(this.particleSystem.clone("", emitter));
  59189. // Clone properties
  59190. clone.type = this.type;
  59191. clone.inheritDirection = this.inheritDirection;
  59192. clone.inheritedVelocityAmount = this.inheritedVelocityAmount;
  59193. clone.particleSystem._disposeEmitterOnDispose = true;
  59194. return clone;
  59195. };
  59196. return SubEmitter;
  59197. }());
  59198. BABYLON.SubEmitter = SubEmitter;
  59199. })(BABYLON || (BABYLON = {}));
  59200. //# sourceMappingURL=babylon.subEmitter.js.map
  59201. var BABYLON;
  59202. (function (BABYLON) {
  59203. var ShaderMaterial = /** @class */ (function (_super) {
  59204. __extends(ShaderMaterial, _super);
  59205. function ShaderMaterial(name, scene, shaderPath, options) {
  59206. var _this = _super.call(this, name, scene) || this;
  59207. _this._textures = {};
  59208. _this._textureArrays = {};
  59209. _this._floats = {};
  59210. _this._ints = {};
  59211. _this._floatsArrays = {};
  59212. _this._colors3 = {};
  59213. _this._colors3Arrays = {};
  59214. _this._colors4 = {};
  59215. _this._vectors2 = {};
  59216. _this._vectors3 = {};
  59217. _this._vectors4 = {};
  59218. _this._matrices = {};
  59219. _this._matrices3x3 = {};
  59220. _this._matrices2x2 = {};
  59221. _this._vectors2Arrays = {};
  59222. _this._vectors3Arrays = {};
  59223. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  59224. _this._shaderPath = shaderPath;
  59225. options.needAlphaBlending = options.needAlphaBlending || false;
  59226. options.needAlphaTesting = options.needAlphaTesting || false;
  59227. options.attributes = options.attributes || ["position", "normal", "uv"];
  59228. options.uniforms = options.uniforms || ["worldViewProjection"];
  59229. options.uniformBuffers = options.uniformBuffers || [];
  59230. options.samplers = options.samplers || [];
  59231. options.defines = options.defines || [];
  59232. _this._options = options;
  59233. return _this;
  59234. }
  59235. ShaderMaterial.prototype.getClassName = function () {
  59236. return "ShaderMaterial";
  59237. };
  59238. ShaderMaterial.prototype.needAlphaBlending = function () {
  59239. return this._options.needAlphaBlending;
  59240. };
  59241. ShaderMaterial.prototype.needAlphaTesting = function () {
  59242. return this._options.needAlphaTesting;
  59243. };
  59244. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  59245. if (this._options.uniforms.indexOf(uniformName) === -1) {
  59246. this._options.uniforms.push(uniformName);
  59247. }
  59248. };
  59249. ShaderMaterial.prototype.setTexture = function (name, texture) {
  59250. if (this._options.samplers.indexOf(name) === -1) {
  59251. this._options.samplers.push(name);
  59252. }
  59253. this._textures[name] = texture;
  59254. return this;
  59255. };
  59256. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  59257. if (this._options.samplers.indexOf(name) === -1) {
  59258. this._options.samplers.push(name);
  59259. }
  59260. this._checkUniform(name);
  59261. this._textureArrays[name] = textures;
  59262. return this;
  59263. };
  59264. ShaderMaterial.prototype.setFloat = function (name, value) {
  59265. this._checkUniform(name);
  59266. this._floats[name] = value;
  59267. return this;
  59268. };
  59269. ShaderMaterial.prototype.setInt = function (name, value) {
  59270. this._checkUniform(name);
  59271. this._ints[name] = value;
  59272. return this;
  59273. };
  59274. ShaderMaterial.prototype.setFloats = function (name, value) {
  59275. this._checkUniform(name);
  59276. this._floatsArrays[name] = value;
  59277. return this;
  59278. };
  59279. ShaderMaterial.prototype.setColor3 = function (name, value) {
  59280. this._checkUniform(name);
  59281. this._colors3[name] = value;
  59282. return this;
  59283. };
  59284. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  59285. this._checkUniform(name);
  59286. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  59287. color.toArray(arr, arr.length);
  59288. return arr;
  59289. }, []);
  59290. return this;
  59291. };
  59292. ShaderMaterial.prototype.setColor4 = function (name, value) {
  59293. this._checkUniform(name);
  59294. this._colors4[name] = value;
  59295. return this;
  59296. };
  59297. ShaderMaterial.prototype.setVector2 = function (name, value) {
  59298. this._checkUniform(name);
  59299. this._vectors2[name] = value;
  59300. return this;
  59301. };
  59302. ShaderMaterial.prototype.setVector3 = function (name, value) {
  59303. this._checkUniform(name);
  59304. this._vectors3[name] = value;
  59305. return this;
  59306. };
  59307. ShaderMaterial.prototype.setVector4 = function (name, value) {
  59308. this._checkUniform(name);
  59309. this._vectors4[name] = value;
  59310. return this;
  59311. };
  59312. ShaderMaterial.prototype.setMatrix = function (name, value) {
  59313. this._checkUniform(name);
  59314. this._matrices[name] = value;
  59315. return this;
  59316. };
  59317. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  59318. this._checkUniform(name);
  59319. this._matrices3x3[name] = value;
  59320. return this;
  59321. };
  59322. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  59323. this._checkUniform(name);
  59324. this._matrices2x2[name] = value;
  59325. return this;
  59326. };
  59327. ShaderMaterial.prototype.setArray2 = function (name, value) {
  59328. this._checkUniform(name);
  59329. this._vectors2Arrays[name] = value;
  59330. return this;
  59331. };
  59332. ShaderMaterial.prototype.setArray3 = function (name, value) {
  59333. this._checkUniform(name);
  59334. this._vectors3Arrays[name] = value;
  59335. return this;
  59336. };
  59337. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  59338. if (!mesh) {
  59339. return true;
  59340. }
  59341. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  59342. return false;
  59343. }
  59344. return false;
  59345. };
  59346. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  59347. var scene = this.getScene();
  59348. var engine = scene.getEngine();
  59349. if (!this.checkReadyOnEveryCall) {
  59350. if (this._renderId === scene.getRenderId()) {
  59351. if (this._checkCache(scene, mesh, useInstances)) {
  59352. return true;
  59353. }
  59354. }
  59355. }
  59356. // Instances
  59357. var defines = [];
  59358. var attribs = [];
  59359. var fallbacks = new BABYLON.EffectFallbacks();
  59360. if (useInstances) {
  59361. defines.push("#define INSTANCES");
  59362. }
  59363. for (var index = 0; index < this._options.defines.length; index++) {
  59364. defines.push(this._options.defines[index]);
  59365. }
  59366. for (var index = 0; index < this._options.attributes.length; index++) {
  59367. attribs.push(this._options.attributes[index]);
  59368. }
  59369. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  59370. attribs.push(BABYLON.VertexBuffer.ColorKind);
  59371. defines.push("#define VERTEXCOLOR");
  59372. }
  59373. // Bones
  59374. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  59375. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59376. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59377. if (mesh.numBoneInfluencers > 4) {
  59378. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  59379. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  59380. }
  59381. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59382. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  59383. fallbacks.addCPUSkinningFallback(0, mesh);
  59384. if (this._options.uniforms.indexOf("mBones") === -1) {
  59385. this._options.uniforms.push("mBones");
  59386. }
  59387. }
  59388. else {
  59389. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59390. }
  59391. // Textures
  59392. for (var name in this._textures) {
  59393. if (!this._textures[name].isReady()) {
  59394. return false;
  59395. }
  59396. }
  59397. // Alpha test
  59398. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  59399. defines.push("#define ALPHATEST");
  59400. }
  59401. var previousEffect = this._effect;
  59402. var join = defines.join("\n");
  59403. this._effect = engine.createEffect(this._shaderPath, {
  59404. attributes: attribs,
  59405. uniformsNames: this._options.uniforms,
  59406. uniformBuffersNames: this._options.uniformBuffers,
  59407. samplers: this._options.samplers,
  59408. defines: join,
  59409. fallbacks: fallbacks,
  59410. onCompiled: this.onCompiled,
  59411. onError: this.onError
  59412. }, engine);
  59413. if (!this._effect.isReady()) {
  59414. return false;
  59415. }
  59416. if (previousEffect !== this._effect) {
  59417. scene.resetCachedMaterial();
  59418. }
  59419. this._renderId = scene.getRenderId();
  59420. return true;
  59421. };
  59422. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  59423. var scene = this.getScene();
  59424. if (!this._effect) {
  59425. return;
  59426. }
  59427. if (this._options.uniforms.indexOf("world") !== -1) {
  59428. this._effect.setMatrix("world", world);
  59429. }
  59430. if (this._options.uniforms.indexOf("worldView") !== -1) {
  59431. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  59432. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  59433. }
  59434. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  59435. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  59436. }
  59437. };
  59438. ShaderMaterial.prototype.bind = function (world, mesh) {
  59439. // Std values
  59440. this.bindOnlyWorldMatrix(world);
  59441. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  59442. if (this._options.uniforms.indexOf("view") !== -1) {
  59443. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  59444. }
  59445. if (this._options.uniforms.indexOf("projection") !== -1) {
  59446. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  59447. }
  59448. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  59449. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  59450. }
  59451. // Bones
  59452. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  59453. var name;
  59454. // Texture
  59455. for (name in this._textures) {
  59456. this._effect.setTexture(name, this._textures[name]);
  59457. }
  59458. // Texture arrays
  59459. for (name in this._textureArrays) {
  59460. this._effect.setTextureArray(name, this._textureArrays[name]);
  59461. }
  59462. // Int
  59463. for (name in this._ints) {
  59464. this._effect.setInt(name, this._ints[name]);
  59465. }
  59466. // Float
  59467. for (name in this._floats) {
  59468. this._effect.setFloat(name, this._floats[name]);
  59469. }
  59470. // Floats
  59471. for (name in this._floatsArrays) {
  59472. this._effect.setArray(name, this._floatsArrays[name]);
  59473. }
  59474. // Color3
  59475. for (name in this._colors3) {
  59476. this._effect.setColor3(name, this._colors3[name]);
  59477. }
  59478. for (name in this._colors3Arrays) {
  59479. this._effect.setArray3(name, this._colors3Arrays[name]);
  59480. }
  59481. // Color4
  59482. for (name in this._colors4) {
  59483. var color = this._colors4[name];
  59484. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  59485. }
  59486. // Vector2
  59487. for (name in this._vectors2) {
  59488. this._effect.setVector2(name, this._vectors2[name]);
  59489. }
  59490. // Vector3
  59491. for (name in this._vectors3) {
  59492. this._effect.setVector3(name, this._vectors3[name]);
  59493. }
  59494. // Vector4
  59495. for (name in this._vectors4) {
  59496. this._effect.setVector4(name, this._vectors4[name]);
  59497. }
  59498. // Matrix
  59499. for (name in this._matrices) {
  59500. this._effect.setMatrix(name, this._matrices[name]);
  59501. }
  59502. // Matrix 3x3
  59503. for (name in this._matrices3x3) {
  59504. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  59505. }
  59506. // Matrix 2x2
  59507. for (name in this._matrices2x2) {
  59508. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  59509. }
  59510. // Vector2Array
  59511. for (name in this._vectors2Arrays) {
  59512. this._effect.setArray2(name, this._vectors2Arrays[name]);
  59513. }
  59514. // Vector3Array
  59515. for (name in this._vectors3Arrays) {
  59516. this._effect.setArray3(name, this._vectors3Arrays[name]);
  59517. }
  59518. }
  59519. this._afterBind(mesh);
  59520. };
  59521. ShaderMaterial.prototype.getActiveTextures = function () {
  59522. var activeTextures = _super.prototype.getActiveTextures.call(this);
  59523. for (var name in this._textures) {
  59524. activeTextures.push(this._textures[name]);
  59525. }
  59526. for (var name in this._textureArrays) {
  59527. var array = this._textureArrays[name];
  59528. for (var index = 0; index < array.length; index++) {
  59529. activeTextures.push(array[index]);
  59530. }
  59531. }
  59532. return activeTextures;
  59533. };
  59534. ShaderMaterial.prototype.hasTexture = function (texture) {
  59535. if (_super.prototype.hasTexture.call(this, texture)) {
  59536. return true;
  59537. }
  59538. for (var name in this._textures) {
  59539. if (this._textures[name] === texture) {
  59540. return true;
  59541. }
  59542. }
  59543. for (var name in this._textureArrays) {
  59544. var array = this._textureArrays[name];
  59545. for (var index = 0; index < array.length; index++) {
  59546. if (array[index] === texture) {
  59547. return true;
  59548. }
  59549. }
  59550. }
  59551. return false;
  59552. };
  59553. ShaderMaterial.prototype.clone = function (name) {
  59554. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  59555. return newShaderMaterial;
  59556. };
  59557. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  59558. if (forceDisposeTextures) {
  59559. var name;
  59560. for (name in this._textures) {
  59561. this._textures[name].dispose();
  59562. }
  59563. for (name in this._textureArrays) {
  59564. var array = this._textureArrays[name];
  59565. for (var index = 0; index < array.length; index++) {
  59566. array[index].dispose();
  59567. }
  59568. }
  59569. }
  59570. this._textures = {};
  59571. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  59572. };
  59573. ShaderMaterial.prototype.serialize = function () {
  59574. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  59575. serializationObject.customType = "BABYLON.ShaderMaterial";
  59576. serializationObject.options = this._options;
  59577. serializationObject.shaderPath = this._shaderPath;
  59578. var name;
  59579. // Texture
  59580. serializationObject.textures = {};
  59581. for (name in this._textures) {
  59582. serializationObject.textures[name] = this._textures[name].serialize();
  59583. }
  59584. // Texture arrays
  59585. serializationObject.textureArrays = {};
  59586. for (name in this._textureArrays) {
  59587. serializationObject.textureArrays[name] = [];
  59588. var array = this._textureArrays[name];
  59589. for (var index = 0; index < array.length; index++) {
  59590. serializationObject.textureArrays[name].push(array[index].serialize());
  59591. }
  59592. }
  59593. // Float
  59594. serializationObject.floats = {};
  59595. for (name in this._floats) {
  59596. serializationObject.floats[name] = this._floats[name];
  59597. }
  59598. // Float s
  59599. serializationObject.FloatArrays = {};
  59600. for (name in this._floatsArrays) {
  59601. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  59602. }
  59603. // Color3
  59604. serializationObject.colors3 = {};
  59605. for (name in this._colors3) {
  59606. serializationObject.colors3[name] = this._colors3[name].asArray();
  59607. }
  59608. // Color3 array
  59609. serializationObject.colors3Arrays = {};
  59610. for (name in this._colors3Arrays) {
  59611. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  59612. }
  59613. // Color4
  59614. serializationObject.colors4 = {};
  59615. for (name in this._colors4) {
  59616. serializationObject.colors4[name] = this._colors4[name].asArray();
  59617. }
  59618. // Vector2
  59619. serializationObject.vectors2 = {};
  59620. for (name in this._vectors2) {
  59621. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  59622. }
  59623. // Vector3
  59624. serializationObject.vectors3 = {};
  59625. for (name in this._vectors3) {
  59626. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  59627. }
  59628. // Vector4
  59629. serializationObject.vectors4 = {};
  59630. for (name in this._vectors4) {
  59631. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  59632. }
  59633. // Matrix
  59634. serializationObject.matrices = {};
  59635. for (name in this._matrices) {
  59636. serializationObject.matrices[name] = this._matrices[name].asArray();
  59637. }
  59638. // Matrix 3x3
  59639. serializationObject.matrices3x3 = {};
  59640. for (name in this._matrices3x3) {
  59641. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  59642. }
  59643. // Matrix 2x2
  59644. serializationObject.matrices2x2 = {};
  59645. for (name in this._matrices2x2) {
  59646. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  59647. }
  59648. // Vector2Array
  59649. serializationObject.vectors2Arrays = {};
  59650. for (name in this._vectors2Arrays) {
  59651. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  59652. }
  59653. // Vector3Array
  59654. serializationObject.vectors3Arrays = {};
  59655. for (name in this._vectors3Arrays) {
  59656. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  59657. }
  59658. return serializationObject;
  59659. };
  59660. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  59661. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  59662. var name;
  59663. // Texture
  59664. for (name in source.textures) {
  59665. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  59666. }
  59667. // Texture arrays
  59668. for (name in source.textureArrays) {
  59669. var array = source.textureArrays[name];
  59670. var textureArray = new Array();
  59671. for (var index = 0; index < array.length; index++) {
  59672. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  59673. }
  59674. material.setTextureArray(name, textureArray);
  59675. }
  59676. // Float
  59677. for (name in source.floats) {
  59678. material.setFloat(name, source.floats[name]);
  59679. }
  59680. // Float s
  59681. for (name in source.floatsArrays) {
  59682. material.setFloats(name, source.floatsArrays[name]);
  59683. }
  59684. // Color3
  59685. for (name in source.colors3) {
  59686. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  59687. }
  59688. // Color3 arrays
  59689. for (name in source.colors3Arrays) {
  59690. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  59691. if (i % 3 === 0) {
  59692. arr.push([num]);
  59693. }
  59694. else {
  59695. arr[arr.length - 1].push(num);
  59696. }
  59697. return arr;
  59698. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  59699. material.setColor3Array(name, colors);
  59700. }
  59701. // Color4
  59702. for (name in source.colors4) {
  59703. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  59704. }
  59705. // Vector2
  59706. for (name in source.vectors2) {
  59707. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  59708. }
  59709. // Vector3
  59710. for (name in source.vectors3) {
  59711. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  59712. }
  59713. // Vector4
  59714. for (name in source.vectors4) {
  59715. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  59716. }
  59717. // Matrix
  59718. for (name in source.matrices) {
  59719. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  59720. }
  59721. // Matrix 3x3
  59722. for (name in source.matrices3x3) {
  59723. material.setMatrix3x3(name, source.matrices3x3[name]);
  59724. }
  59725. // Matrix 2x2
  59726. for (name in source.matrices2x2) {
  59727. material.setMatrix2x2(name, source.matrices2x2[name]);
  59728. }
  59729. // Vector2Array
  59730. for (name in source.vectors2Arrays) {
  59731. material.setArray2(name, source.vectors2Arrays[name]);
  59732. }
  59733. // Vector3Array
  59734. for (name in source.vectors3Arrays) {
  59735. material.setArray3(name, source.vectors3Arrays[name]);
  59736. }
  59737. return material;
  59738. };
  59739. return ShaderMaterial;
  59740. }(BABYLON.Material));
  59741. BABYLON.ShaderMaterial = ShaderMaterial;
  59742. })(BABYLON || (BABYLON = {}));
  59743. //# sourceMappingURL=babylon.shaderMaterial.js.map
  59744. var BABYLON;
  59745. (function (BABYLON) {
  59746. var GroundMesh = /** @class */ (function (_super) {
  59747. __extends(GroundMesh, _super);
  59748. function GroundMesh(name, scene) {
  59749. var _this = _super.call(this, name, scene) || this;
  59750. _this.generateOctree = false;
  59751. return _this;
  59752. }
  59753. GroundMesh.prototype.getClassName = function () {
  59754. return "GroundMesh";
  59755. };
  59756. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  59757. get: function () {
  59758. return Math.min(this._subdivisionsX, this._subdivisionsY);
  59759. },
  59760. enumerable: true,
  59761. configurable: true
  59762. });
  59763. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  59764. get: function () {
  59765. return this._subdivisionsX;
  59766. },
  59767. enumerable: true,
  59768. configurable: true
  59769. });
  59770. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  59771. get: function () {
  59772. return this._subdivisionsY;
  59773. },
  59774. enumerable: true,
  59775. configurable: true
  59776. });
  59777. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  59778. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  59779. this._subdivisionsX = chunksCount;
  59780. this._subdivisionsY = chunksCount;
  59781. this.subdivide(chunksCount);
  59782. // Call the octree system optimization if it is defined.
  59783. var thisAsAny = this;
  59784. if (thisAsAny.createOrUpdateSubmeshesOctree) {
  59785. thisAsAny.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  59786. }
  59787. };
  59788. /**
  59789. * Returns a height (y) value in the Worl system :
  59790. * the ground altitude at the coordinates (x, z) expressed in the World system.
  59791. * Returns the ground y position if (x, z) are outside the ground surface.
  59792. */
  59793. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  59794. var world = this.getWorldMatrix();
  59795. var invMat = BABYLON.Tmp.Matrix[5];
  59796. world.invertToRef(invMat);
  59797. var tmpVect = BABYLON.Tmp.Vector3[8];
  59798. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  59799. x = tmpVect.x;
  59800. z = tmpVect.z;
  59801. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59802. return this.position.y;
  59803. }
  59804. if (!this._heightQuads || this._heightQuads.length == 0) {
  59805. this._initHeightQuads();
  59806. this._computeHeightQuads();
  59807. }
  59808. var facet = this._getFacetAt(x, z);
  59809. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  59810. // return y in the World system
  59811. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  59812. return tmpVect.y;
  59813. };
  59814. /**
  59815. * Returns a normalized vector (Vector3) orthogonal to the ground
  59816. * at the ground coordinates (x, z) expressed in the World system.
  59817. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  59818. */
  59819. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  59820. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  59821. this.getNormalAtCoordinatesToRef(x, z, normal);
  59822. return normal;
  59823. };
  59824. /**
  59825. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  59826. * at the ground coordinates (x, z) expressed in the World system.
  59827. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  59828. * Returns the GroundMesh.
  59829. */
  59830. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  59831. var world = this.getWorldMatrix();
  59832. var tmpMat = BABYLON.Tmp.Matrix[5];
  59833. world.invertToRef(tmpMat);
  59834. var tmpVect = BABYLON.Tmp.Vector3[8];
  59835. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  59836. x = tmpVect.x;
  59837. z = tmpVect.z;
  59838. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59839. return this;
  59840. }
  59841. if (!this._heightQuads || this._heightQuads.length == 0) {
  59842. this._initHeightQuads();
  59843. this._computeHeightQuads();
  59844. }
  59845. var facet = this._getFacetAt(x, z);
  59846. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  59847. return this;
  59848. };
  59849. /**
  59850. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  59851. * if the ground has been updated.
  59852. * This can be used in the render loop.
  59853. * Returns the GroundMesh.
  59854. */
  59855. GroundMesh.prototype.updateCoordinateHeights = function () {
  59856. if (!this._heightQuads || this._heightQuads.length == 0) {
  59857. this._initHeightQuads();
  59858. }
  59859. this._computeHeightQuads();
  59860. return this;
  59861. };
  59862. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  59863. GroundMesh.prototype._getFacetAt = function (x, z) {
  59864. // retrieve col and row from x, z coordinates in the ground local system
  59865. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  59866. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  59867. var quad = this._heightQuads[row * this._subdivisionsX + col];
  59868. var facet;
  59869. if (z < quad.slope.x * x + quad.slope.y) {
  59870. facet = quad.facet1;
  59871. }
  59872. else {
  59873. facet = quad.facet2;
  59874. }
  59875. return facet;
  59876. };
  59877. // Creates and populates the heightMap array with "facet" elements :
  59878. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  59879. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  59880. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  59881. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  59882. // Returns the GroundMesh.
  59883. GroundMesh.prototype._initHeightQuads = function () {
  59884. var subdivisionsX = this._subdivisionsX;
  59885. var subdivisionsY = this._subdivisionsY;
  59886. this._heightQuads = new Array();
  59887. for (var row = 0; row < subdivisionsY; row++) {
  59888. for (var col = 0; col < subdivisionsX; col++) {
  59889. 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) };
  59890. this._heightQuads[row * subdivisionsX + col] = quad;
  59891. }
  59892. }
  59893. return this;
  59894. };
  59895. // Compute each quad element values and update the the heightMap array :
  59896. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  59897. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  59898. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  59899. // Returns the GroundMesh.
  59900. GroundMesh.prototype._computeHeightQuads = function () {
  59901. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  59902. if (!positions) {
  59903. return this;
  59904. }
  59905. var v1 = BABYLON.Tmp.Vector3[3];
  59906. var v2 = BABYLON.Tmp.Vector3[2];
  59907. var v3 = BABYLON.Tmp.Vector3[1];
  59908. var v4 = BABYLON.Tmp.Vector3[0];
  59909. var v1v2 = BABYLON.Tmp.Vector3[4];
  59910. var v1v3 = BABYLON.Tmp.Vector3[5];
  59911. var v1v4 = BABYLON.Tmp.Vector3[6];
  59912. var norm1 = BABYLON.Tmp.Vector3[7];
  59913. var norm2 = BABYLON.Tmp.Vector3[8];
  59914. var i = 0;
  59915. var j = 0;
  59916. var k = 0;
  59917. var cd = 0; // 2D slope coefficient : z = cd * x + h
  59918. var h = 0;
  59919. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  59920. var d2 = 0;
  59921. var subdivisionsX = this._subdivisionsX;
  59922. var subdivisionsY = this._subdivisionsY;
  59923. for (var row = 0; row < subdivisionsY; row++) {
  59924. for (var col = 0; col < subdivisionsX; col++) {
  59925. i = col * 3;
  59926. j = row * (subdivisionsX + 1) * 3;
  59927. k = (row + 1) * (subdivisionsX + 1) * 3;
  59928. v1.x = positions[j + i];
  59929. v1.y = positions[j + i + 1];
  59930. v1.z = positions[j + i + 2];
  59931. v2.x = positions[j + i + 3];
  59932. v2.y = positions[j + i + 4];
  59933. v2.z = positions[j + i + 5];
  59934. v3.x = positions[k + i];
  59935. v3.y = positions[k + i + 1];
  59936. v3.z = positions[k + i + 2];
  59937. v4.x = positions[k + i + 3];
  59938. v4.y = positions[k + i + 4];
  59939. v4.z = positions[k + i + 5];
  59940. // 2D slope V1V4
  59941. cd = (v4.z - v1.z) / (v4.x - v1.x);
  59942. h = v1.z - cd * v1.x; // v1 belongs to the slope
  59943. // facet equations :
  59944. // we compute each facet normal vector
  59945. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  59946. // we compute the value d by applying the equation to v1 which belongs to the plane
  59947. // then we store the facet equation in a Vector4
  59948. v2.subtractToRef(v1, v1v2);
  59949. v3.subtractToRef(v1, v1v3);
  59950. v4.subtractToRef(v1, v1v4);
  59951. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  59952. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  59953. norm1.normalize();
  59954. norm2.normalize();
  59955. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  59956. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  59957. var quad = this._heightQuads[row * subdivisionsX + col];
  59958. quad.slope.copyFromFloats(cd, h);
  59959. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  59960. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  59961. }
  59962. }
  59963. return this;
  59964. };
  59965. GroundMesh.prototype.serialize = function (serializationObject) {
  59966. _super.prototype.serialize.call(this, serializationObject);
  59967. serializationObject.subdivisionsX = this._subdivisionsX;
  59968. serializationObject.subdivisionsY = this._subdivisionsY;
  59969. serializationObject.minX = this._minX;
  59970. serializationObject.maxX = this._maxX;
  59971. serializationObject.minZ = this._minZ;
  59972. serializationObject.maxZ = this._maxZ;
  59973. serializationObject.width = this._width;
  59974. serializationObject.height = this._height;
  59975. };
  59976. GroundMesh.Parse = function (parsedMesh, scene) {
  59977. var result = new GroundMesh(parsedMesh.name, scene);
  59978. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  59979. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  59980. result._minX = parsedMesh.minX;
  59981. result._maxX = parsedMesh.maxX;
  59982. result._minZ = parsedMesh.minZ;
  59983. result._maxZ = parsedMesh.maxZ;
  59984. result._width = parsedMesh.width;
  59985. result._height = parsedMesh.height;
  59986. return result;
  59987. };
  59988. return GroundMesh;
  59989. }(BABYLON.Mesh));
  59990. BABYLON.GroundMesh = GroundMesh;
  59991. })(BABYLON || (BABYLON = {}));
  59992. //# sourceMappingURL=babylon.groundMesh.js.map
  59993. var BABYLON;
  59994. (function (BABYLON) {
  59995. /**
  59996. * Creates an instance based on a source mesh.
  59997. */
  59998. var InstancedMesh = /** @class */ (function (_super) {
  59999. __extends(InstancedMesh, _super);
  60000. function InstancedMesh(name, source) {
  60001. var _this = _super.call(this, name, source.getScene()) || this;
  60002. source.instances.push(_this);
  60003. _this._sourceMesh = source;
  60004. _this.position.copyFrom(source.position);
  60005. _this.rotation.copyFrom(source.rotation);
  60006. _this.scaling.copyFrom(source.scaling);
  60007. if (source.rotationQuaternion) {
  60008. _this.rotationQuaternion = source.rotationQuaternion.clone();
  60009. }
  60010. _this.infiniteDistance = source.infiniteDistance;
  60011. _this.setPivotMatrix(source.getPivotMatrix());
  60012. _this.refreshBoundingInfo();
  60013. _this._syncSubMeshes();
  60014. return _this;
  60015. }
  60016. /**
  60017. * Returns the string "InstancedMesh".
  60018. */
  60019. InstancedMesh.prototype.getClassName = function () {
  60020. return "InstancedMesh";
  60021. };
  60022. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  60023. // Methods
  60024. get: function () {
  60025. return this._sourceMesh.receiveShadows;
  60026. },
  60027. enumerable: true,
  60028. configurable: true
  60029. });
  60030. Object.defineProperty(InstancedMesh.prototype, "material", {
  60031. get: function () {
  60032. return this._sourceMesh.material;
  60033. },
  60034. enumerable: true,
  60035. configurable: true
  60036. });
  60037. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  60038. get: function () {
  60039. return this._sourceMesh.visibility;
  60040. },
  60041. enumerable: true,
  60042. configurable: true
  60043. });
  60044. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  60045. get: function () {
  60046. return this._sourceMesh.skeleton;
  60047. },
  60048. enumerable: true,
  60049. configurable: true
  60050. });
  60051. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  60052. get: function () {
  60053. return this._sourceMesh.renderingGroupId;
  60054. },
  60055. set: function (value) {
  60056. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  60057. return;
  60058. }
  60059. //no-op with warning
  60060. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  60061. },
  60062. enumerable: true,
  60063. configurable: true
  60064. });
  60065. /**
  60066. * Returns the total number of vertices (integer).
  60067. */
  60068. InstancedMesh.prototype.getTotalVertices = function () {
  60069. return this._sourceMesh.getTotalVertices();
  60070. };
  60071. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  60072. get: function () {
  60073. return this._sourceMesh;
  60074. },
  60075. enumerable: true,
  60076. configurable: true
  60077. });
  60078. /**
  60079. * Is this node ready to be used/rendered
  60080. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  60081. * @return {boolean} is it ready
  60082. */
  60083. InstancedMesh.prototype.isReady = function (completeCheck) {
  60084. if (completeCheck === void 0) { completeCheck = false; }
  60085. return this._sourceMesh.isReady(completeCheck, true);
  60086. };
  60087. /**
  60088. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  60089. */
  60090. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  60091. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  60092. };
  60093. /**
  60094. * Sets the vertex data of the mesh geometry for the requested `kind`.
  60095. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  60096. * The `data` are either a numeric array either a Float32Array.
  60097. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  60098. * 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).
  60099. * Note that a new underlying VertexBuffer object is created each call.
  60100. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  60101. *
  60102. * Possible `kind` values :
  60103. * - BABYLON.VertexBuffer.PositionKind
  60104. * - BABYLON.VertexBuffer.UVKind
  60105. * - BABYLON.VertexBuffer.UV2Kind
  60106. * - BABYLON.VertexBuffer.UV3Kind
  60107. * - BABYLON.VertexBuffer.UV4Kind
  60108. * - BABYLON.VertexBuffer.UV5Kind
  60109. * - BABYLON.VertexBuffer.UV6Kind
  60110. * - BABYLON.VertexBuffer.ColorKind
  60111. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60112. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60113. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60114. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60115. *
  60116. * Returns the Mesh.
  60117. */
  60118. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  60119. if (this.sourceMesh) {
  60120. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  60121. }
  60122. return this.sourceMesh;
  60123. };
  60124. /**
  60125. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  60126. * If the mesh has no geometry, it is simply returned as it is.
  60127. * The `data` are either a numeric array either a Float32Array.
  60128. * No new underlying VertexBuffer object is created.
  60129. * 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.
  60130. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  60131. *
  60132. * Possible `kind` values :
  60133. * - BABYLON.VertexBuffer.PositionKind
  60134. * - BABYLON.VertexBuffer.UVKind
  60135. * - BABYLON.VertexBuffer.UV2Kind
  60136. * - BABYLON.VertexBuffer.UV3Kind
  60137. * - BABYLON.VertexBuffer.UV4Kind
  60138. * - BABYLON.VertexBuffer.UV5Kind
  60139. * - BABYLON.VertexBuffer.UV6Kind
  60140. * - BABYLON.VertexBuffer.ColorKind
  60141. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60142. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60143. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60144. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60145. *
  60146. * Returns the Mesh.
  60147. */
  60148. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  60149. if (this.sourceMesh) {
  60150. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  60151. }
  60152. return this.sourceMesh;
  60153. };
  60154. /**
  60155. * Sets the mesh indices.
  60156. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  60157. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  60158. * This method creates a new index buffer each call.
  60159. * Returns the Mesh.
  60160. */
  60161. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  60162. if (totalVertices === void 0) { totalVertices = null; }
  60163. if (this.sourceMesh) {
  60164. this.sourceMesh.setIndices(indices, totalVertices);
  60165. }
  60166. return this.sourceMesh;
  60167. };
  60168. /**
  60169. * Boolean : True if the mesh owns the requested kind of data.
  60170. */
  60171. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  60172. return this._sourceMesh.isVerticesDataPresent(kind);
  60173. };
  60174. /**
  60175. * Returns an array of indices (IndicesArray).
  60176. */
  60177. InstancedMesh.prototype.getIndices = function () {
  60178. return this._sourceMesh.getIndices();
  60179. };
  60180. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  60181. get: function () {
  60182. return this._sourceMesh._positions;
  60183. },
  60184. enumerable: true,
  60185. configurable: true
  60186. });
  60187. /**
  60188. * Sets a new updated BoundingInfo to the mesh.
  60189. * Returns the mesh.
  60190. */
  60191. InstancedMesh.prototype.refreshBoundingInfo = function () {
  60192. var meshBB = this._sourceMesh.getBoundingInfo();
  60193. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  60194. this._updateBoundingInfo();
  60195. return this;
  60196. };
  60197. /** @hidden */
  60198. InstancedMesh.prototype._preActivate = function () {
  60199. if (this._currentLOD) {
  60200. this._currentLOD._preActivate();
  60201. }
  60202. return this;
  60203. };
  60204. /** @hidden */
  60205. InstancedMesh.prototype._activate = function (renderId) {
  60206. if (this._currentLOD) {
  60207. this._currentLOD._registerInstanceForRenderId(this, renderId);
  60208. }
  60209. return this;
  60210. };
  60211. /**
  60212. * Returns the current associated LOD AbstractMesh.
  60213. */
  60214. InstancedMesh.prototype.getLOD = function (camera) {
  60215. if (!camera) {
  60216. return this;
  60217. }
  60218. var boundingInfo = this.getBoundingInfo();
  60219. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  60220. if (this._currentLOD === this.sourceMesh) {
  60221. return this;
  60222. }
  60223. return this._currentLOD;
  60224. };
  60225. /** @hidden */
  60226. InstancedMesh.prototype._syncSubMeshes = function () {
  60227. this.releaseSubMeshes();
  60228. if (this._sourceMesh.subMeshes) {
  60229. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  60230. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  60231. }
  60232. }
  60233. return this;
  60234. };
  60235. /** @hidden */
  60236. InstancedMesh.prototype._generatePointsArray = function () {
  60237. return this._sourceMesh._generatePointsArray();
  60238. };
  60239. /**
  60240. * Creates a new InstancedMesh from the current mesh.
  60241. * - name (string) : the cloned mesh name
  60242. * - newParent (optional Node) : the optional Node to parent the clone to.
  60243. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  60244. *
  60245. * Returns the clone.
  60246. */
  60247. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60248. var result = this._sourceMesh.createInstance(name);
  60249. // Deep copy
  60250. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  60251. // Bounding info
  60252. this.refreshBoundingInfo();
  60253. // Parent
  60254. if (newParent) {
  60255. result.parent = newParent;
  60256. }
  60257. if (!doNotCloneChildren) {
  60258. // Children
  60259. for (var index = 0; index < this.getScene().meshes.length; index++) {
  60260. var mesh = this.getScene().meshes[index];
  60261. if (mesh.parent === this) {
  60262. mesh.clone(mesh.name, result);
  60263. }
  60264. }
  60265. }
  60266. result.computeWorldMatrix(true);
  60267. return result;
  60268. };
  60269. /**
  60270. * Disposes the InstancedMesh.
  60271. * Returns nothing.
  60272. */
  60273. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  60274. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  60275. // Remove from mesh
  60276. var index = this._sourceMesh.instances.indexOf(this);
  60277. this._sourceMesh.instances.splice(index, 1);
  60278. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  60279. };
  60280. return InstancedMesh;
  60281. }(BABYLON.AbstractMesh));
  60282. BABYLON.InstancedMesh = InstancedMesh;
  60283. })(BABYLON || (BABYLON = {}));
  60284. //# sourceMappingURL=babylon.instancedMesh.js.map
  60285. var BABYLON;
  60286. (function (BABYLON) {
  60287. var LinesMesh = /** @class */ (function (_super) {
  60288. __extends(LinesMesh, _super);
  60289. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  60290. if (scene === void 0) { scene = null; }
  60291. if (parent === void 0) { parent = null; }
  60292. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  60293. _this.useVertexColor = useVertexColor;
  60294. _this.useVertexAlpha = useVertexAlpha;
  60295. _this.color = new BABYLON.Color3(1, 1, 1);
  60296. _this.alpha = 1;
  60297. if (source) {
  60298. _this.color = source.color.clone();
  60299. _this.alpha = source.alpha;
  60300. _this.useVertexColor = source.useVertexColor;
  60301. _this.useVertexAlpha = source.useVertexAlpha;
  60302. }
  60303. _this._intersectionThreshold = 0.1;
  60304. var defines = [];
  60305. var options = {
  60306. attributes: [BABYLON.VertexBuffer.PositionKind],
  60307. uniforms: ["world", "viewProjection"],
  60308. needAlphaBlending: true,
  60309. defines: defines
  60310. };
  60311. if (useVertexAlpha === false) {
  60312. options.needAlphaBlending = false;
  60313. }
  60314. if (!useVertexColor) {
  60315. options.uniforms.push("color");
  60316. }
  60317. else {
  60318. options.defines.push("#define VERTEXCOLOR");
  60319. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  60320. }
  60321. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  60322. return _this;
  60323. }
  60324. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  60325. /**
  60326. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60327. * This margin is expressed in world space coordinates, so its value may vary.
  60328. * Default value is 0.1
  60329. * @returns the intersection Threshold value.
  60330. */
  60331. get: function () {
  60332. return this._intersectionThreshold;
  60333. },
  60334. /**
  60335. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60336. * This margin is expressed in world space coordinates, so its value may vary.
  60337. * @param value the new threshold to apply
  60338. */
  60339. set: function (value) {
  60340. if (this._intersectionThreshold === value) {
  60341. return;
  60342. }
  60343. this._intersectionThreshold = value;
  60344. if (this.geometry) {
  60345. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  60346. }
  60347. },
  60348. enumerable: true,
  60349. configurable: true
  60350. });
  60351. /**
  60352. * Returns the string "LineMesh"
  60353. */
  60354. LinesMesh.prototype.getClassName = function () {
  60355. return "LinesMesh";
  60356. };
  60357. Object.defineProperty(LinesMesh.prototype, "material", {
  60358. /**
  60359. * @hidden
  60360. */
  60361. get: function () {
  60362. return this._colorShader;
  60363. },
  60364. /**
  60365. * @hidden
  60366. */
  60367. set: function (value) {
  60368. // Do nothing
  60369. },
  60370. enumerable: true,
  60371. configurable: true
  60372. });
  60373. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  60374. /**
  60375. * @hidden
  60376. */
  60377. get: function () {
  60378. return false;
  60379. },
  60380. enumerable: true,
  60381. configurable: true
  60382. });
  60383. LinesMesh.prototype.createInstance = function (name) {
  60384. throw new Error("LinesMeshes do not support createInstance.");
  60385. };
  60386. /** @hidden */
  60387. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  60388. if (!this._geometry) {
  60389. return this;
  60390. }
  60391. // VBOs
  60392. this._geometry._bind(this._colorShader.getEffect());
  60393. // Color
  60394. if (!this.useVertexColor) {
  60395. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  60396. }
  60397. return this;
  60398. };
  60399. /** @hidden */
  60400. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  60401. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  60402. return this;
  60403. }
  60404. var engine = this.getScene().getEngine();
  60405. // Draw order
  60406. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  60407. return this;
  60408. };
  60409. LinesMesh.prototype.dispose = function (doNotRecurse) {
  60410. this._colorShader.dispose();
  60411. _super.prototype.dispose.call(this, doNotRecurse);
  60412. };
  60413. /**
  60414. * Returns a new LineMesh object cloned from the current one.
  60415. */
  60416. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60417. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  60418. };
  60419. return LinesMesh;
  60420. }(BABYLON.Mesh));
  60421. BABYLON.LinesMesh = LinesMesh;
  60422. })(BABYLON || (BABYLON = {}));
  60423. //# sourceMappingURL=babylon.linesMesh.js.map
  60424. var BABYLON;
  60425. (function (BABYLON) {
  60426. /**
  60427. * This class implement a typical dictionary using a string as key and the generic type T as value.
  60428. * The underlying implementation relies on an associative array to ensure the best performances.
  60429. * The value can be anything including 'null' but except 'undefined'
  60430. */
  60431. var StringDictionary = /** @class */ (function () {
  60432. function StringDictionary() {
  60433. this._count = 0;
  60434. this._data = {};
  60435. }
  60436. /**
  60437. * This will clear this dictionary and copy the content from the 'source' one.
  60438. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  60439. * @param source the dictionary to take the content from and copy to this dictionary
  60440. */
  60441. StringDictionary.prototype.copyFrom = function (source) {
  60442. var _this = this;
  60443. this.clear();
  60444. source.forEach(function (t, v) { return _this.add(t, v); });
  60445. };
  60446. /**
  60447. * Get a value based from its key
  60448. * @param key the given key to get the matching value from
  60449. * @return the value if found, otherwise undefined is returned
  60450. */
  60451. StringDictionary.prototype.get = function (key) {
  60452. var val = this._data[key];
  60453. if (val !== undefined) {
  60454. return val;
  60455. }
  60456. return undefined;
  60457. };
  60458. /**
  60459. * Get a value from its key or add it if it doesn't exist.
  60460. * This method will ensure you that a given key/data will be present in the dictionary.
  60461. * @param key the given key to get the matching value from
  60462. * @param factory the factory that will create the value if the key is not present in the dictionary.
  60463. * The factory will only be invoked if there's no data for the given key.
  60464. * @return the value corresponding to the key.
  60465. */
  60466. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  60467. var val = this.get(key);
  60468. if (val !== undefined) {
  60469. return val;
  60470. }
  60471. val = factory(key);
  60472. if (val) {
  60473. this.add(key, val);
  60474. }
  60475. return val;
  60476. };
  60477. /**
  60478. * Get a value from its key if present in the dictionary otherwise add it
  60479. * @param key the key to get the value from
  60480. * @param val if there's no such key/value pair in the dictionary add it with this value
  60481. * @return the value corresponding to the key
  60482. */
  60483. StringDictionary.prototype.getOrAdd = function (key, val) {
  60484. var curVal = this.get(key);
  60485. if (curVal !== undefined) {
  60486. return curVal;
  60487. }
  60488. this.add(key, val);
  60489. return val;
  60490. };
  60491. /**
  60492. * Check if there's a given key in the dictionary
  60493. * @param key the key to check for
  60494. * @return true if the key is present, false otherwise
  60495. */
  60496. StringDictionary.prototype.contains = function (key) {
  60497. return this._data[key] !== undefined;
  60498. };
  60499. /**
  60500. * Add a new key and its corresponding value
  60501. * @param key the key to add
  60502. * @param value the value corresponding to the key
  60503. * @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
  60504. */
  60505. StringDictionary.prototype.add = function (key, value) {
  60506. if (this._data[key] !== undefined) {
  60507. return false;
  60508. }
  60509. this._data[key] = value;
  60510. ++this._count;
  60511. return true;
  60512. };
  60513. StringDictionary.prototype.set = function (key, value) {
  60514. if (this._data[key] === undefined) {
  60515. return false;
  60516. }
  60517. this._data[key] = value;
  60518. return true;
  60519. };
  60520. /**
  60521. * Get the element of the given key and remove it from the dictionary
  60522. * @param key
  60523. */
  60524. StringDictionary.prototype.getAndRemove = function (key) {
  60525. var val = this.get(key);
  60526. if (val !== undefined) {
  60527. delete this._data[key];
  60528. --this._count;
  60529. return val;
  60530. }
  60531. return null;
  60532. };
  60533. /**
  60534. * Remove a key/value from the dictionary.
  60535. * @param key the key to remove
  60536. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  60537. */
  60538. StringDictionary.prototype.remove = function (key) {
  60539. if (this.contains(key)) {
  60540. delete this._data[key];
  60541. --this._count;
  60542. return true;
  60543. }
  60544. return false;
  60545. };
  60546. /**
  60547. * Clear the whole content of the dictionary
  60548. */
  60549. StringDictionary.prototype.clear = function () {
  60550. this._data = {};
  60551. this._count = 0;
  60552. };
  60553. Object.defineProperty(StringDictionary.prototype, "count", {
  60554. get: function () {
  60555. return this._count;
  60556. },
  60557. enumerable: true,
  60558. configurable: true
  60559. });
  60560. /**
  60561. * Execute a callback on each key/val of the dictionary.
  60562. * Note that you can remove any element in this dictionary in the callback implementation
  60563. * @param callback the callback to execute on a given key/value pair
  60564. */
  60565. StringDictionary.prototype.forEach = function (callback) {
  60566. for (var cur in this._data) {
  60567. var val = this._data[cur];
  60568. callback(cur, val);
  60569. }
  60570. };
  60571. /**
  60572. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  60573. * If the callback returns null or undefined the method will iterate to the next key/value pair
  60574. * Note that you can remove any element in this dictionary in the callback implementation
  60575. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  60576. */
  60577. StringDictionary.prototype.first = function (callback) {
  60578. for (var cur in this._data) {
  60579. var val = this._data[cur];
  60580. var res = callback(cur, val);
  60581. if (res) {
  60582. return res;
  60583. }
  60584. }
  60585. return null;
  60586. };
  60587. return StringDictionary;
  60588. }());
  60589. BABYLON.StringDictionary = StringDictionary;
  60590. })(BABYLON || (BABYLON = {}));
  60591. //# sourceMappingURL=babylon.stringDictionary.js.map
  60592. var BABYLON;
  60593. (function (BABYLON) {
  60594. var Debug;
  60595. (function (Debug) {
  60596. /**
  60597. * Class used to render a debug view of a given skeleton
  60598. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  60599. */
  60600. var SkeletonViewer = /** @class */ (function () {
  60601. /**
  60602. * Creates a new SkeletonViewer
  60603. * @param skeleton defines the skeleton to render
  60604. * @param mesh defines the mesh attached to the skeleton
  60605. * @param scene defines the hosting scene
  60606. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  60607. * @param renderingGroupId defines the rendering group id to use with the viewer
  60608. */
  60609. function SkeletonViewer(
  60610. /** defines the skeleton to render */
  60611. skeleton,
  60612. /** defines the mesh attached to the skeleton */
  60613. mesh, scene,
  60614. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  60615. autoUpdateBonesMatrices,
  60616. /** defines the rendering group id to use with the viewer */
  60617. renderingGroupId) {
  60618. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  60619. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  60620. this.skeleton = skeleton;
  60621. this.mesh = mesh;
  60622. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  60623. this.renderingGroupId = renderingGroupId;
  60624. /** Gets or sets the color used to render the skeleton */
  60625. this.color = BABYLON.Color3.White();
  60626. this._debugLines = new Array();
  60627. this._isEnabled = false;
  60628. this._scene = scene;
  60629. this.update();
  60630. this._renderFunction = this.update.bind(this);
  60631. }
  60632. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  60633. get: function () {
  60634. return this._isEnabled;
  60635. },
  60636. /** Gets or sets a boolean indicating if the viewer is enabled */
  60637. set: function (value) {
  60638. if (this._isEnabled === value) {
  60639. return;
  60640. }
  60641. this._isEnabled = value;
  60642. if (value) {
  60643. this._scene.registerBeforeRender(this._renderFunction);
  60644. }
  60645. else {
  60646. this._scene.unregisterBeforeRender(this._renderFunction);
  60647. }
  60648. },
  60649. enumerable: true,
  60650. configurable: true
  60651. });
  60652. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  60653. if (x === void 0) { x = 0; }
  60654. if (y === void 0) { y = 0; }
  60655. if (z === void 0) { z = 0; }
  60656. var tmat = BABYLON.Tmp.Matrix[0];
  60657. var parentBone = bone.getParent();
  60658. tmat.copyFrom(bone.getLocalMatrix());
  60659. if (x !== 0 || y !== 0 || z !== 0) {
  60660. var tmat2 = BABYLON.Tmp.Matrix[1];
  60661. BABYLON.Matrix.IdentityToRef(tmat2);
  60662. tmat2.m[12] = x;
  60663. tmat2.m[13] = y;
  60664. tmat2.m[14] = z;
  60665. tmat2.multiplyToRef(tmat, tmat);
  60666. }
  60667. if (parentBone) {
  60668. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  60669. }
  60670. tmat.multiplyToRef(meshMat, tmat);
  60671. position.x = tmat.m[12];
  60672. position.y = tmat.m[13];
  60673. position.z = tmat.m[14];
  60674. };
  60675. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  60676. var len = bones.length;
  60677. var meshPos = this.mesh.position;
  60678. for (var i = 0; i < len; i++) {
  60679. var bone = bones[i];
  60680. var points = this._debugLines[i];
  60681. if (!points) {
  60682. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  60683. this._debugLines[i] = points;
  60684. }
  60685. this._getBonePosition(points[0], bone, meshMat);
  60686. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  60687. points[0].subtractInPlace(meshPos);
  60688. points[1].subtractInPlace(meshPos);
  60689. }
  60690. };
  60691. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  60692. var len = bones.length;
  60693. var boneNum = 0;
  60694. var meshPos = this.mesh.position;
  60695. for (var i = len - 1; i >= 0; i--) {
  60696. var childBone = bones[i];
  60697. var parentBone = childBone.getParent();
  60698. if (!parentBone) {
  60699. continue;
  60700. }
  60701. var points = this._debugLines[boneNum];
  60702. if (!points) {
  60703. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  60704. this._debugLines[boneNum] = points;
  60705. }
  60706. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  60707. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  60708. points[0].subtractInPlace(meshPos);
  60709. points[1].subtractInPlace(meshPos);
  60710. boneNum++;
  60711. }
  60712. };
  60713. /** Update the viewer to sync with current skeleton state */
  60714. SkeletonViewer.prototype.update = function () {
  60715. if (this.autoUpdateBonesMatrices) {
  60716. this.skeleton.computeAbsoluteTransforms();
  60717. }
  60718. if (this.skeleton.bones[0].length === undefined) {
  60719. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  60720. }
  60721. else {
  60722. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  60723. }
  60724. if (!this._debugMesh) {
  60725. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  60726. this._debugMesh.renderingGroupId = this.renderingGroupId;
  60727. }
  60728. else {
  60729. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  60730. }
  60731. this._debugMesh.position.copyFrom(this.mesh.position);
  60732. this._debugMesh.color = this.color;
  60733. };
  60734. /** Release associated resources */
  60735. SkeletonViewer.prototype.dispose = function () {
  60736. if (this._debugMesh) {
  60737. this.isEnabled = false;
  60738. this._debugMesh.dispose();
  60739. this._debugMesh = null;
  60740. }
  60741. };
  60742. return SkeletonViewer;
  60743. }());
  60744. Debug.SkeletonViewer = SkeletonViewer;
  60745. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  60746. })(BABYLON || (BABYLON = {}));
  60747. //# sourceMappingURL=babylon.skeletonViewer.js.map
  60748. /**
  60749. * Module Debug contains the (visual) components to debug a scene correctly
  60750. */
  60751. var BABYLON;
  60752. (function (BABYLON) {
  60753. var Debug;
  60754. (function (Debug) {
  60755. /**
  60756. * The Axes viewer will show 3 axes in a specific point in space
  60757. */
  60758. var AxesViewer = /** @class */ (function () {
  60759. /**
  60760. * Creates a new AxesViewer
  60761. * @param scene defines the hosting scene
  60762. * @param scaleLines defines a number used to scale line length (1 by default)
  60763. */
  60764. function AxesViewer(scene, scaleLines) {
  60765. if (scaleLines === void 0) { scaleLines = 1; }
  60766. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  60767. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  60768. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  60769. /**
  60770. * Gets or sets a number used to scale line length
  60771. */
  60772. this.scaleLines = 1;
  60773. this.scaleLines = scaleLines;
  60774. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  60775. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  60776. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  60777. this._xmesh.renderingGroupId = 2;
  60778. this._ymesh.renderingGroupId = 2;
  60779. this._zmesh.renderingGroupId = 2;
  60780. this._xmesh.material.checkReadyOnlyOnce = true;
  60781. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  60782. this._ymesh.material.checkReadyOnlyOnce = true;
  60783. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  60784. this._zmesh.material.checkReadyOnlyOnce = true;
  60785. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  60786. this.scene = scene;
  60787. }
  60788. /**
  60789. * Force the viewer to update
  60790. * @param position defines the position of the viewer
  60791. * @param xaxis defines the x axis of the viewer
  60792. * @param yaxis defines the y axis of the viewer
  60793. * @param zaxis defines the z axis of the viewer
  60794. */
  60795. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  60796. var scaleLines = this.scaleLines;
  60797. if (this._xmesh) {
  60798. this._xmesh.position.copyFrom(position);
  60799. }
  60800. if (this._ymesh) {
  60801. this._ymesh.position.copyFrom(position);
  60802. }
  60803. if (this._zmesh) {
  60804. this._zmesh.position.copyFrom(position);
  60805. }
  60806. var point2 = this._xline[1];
  60807. point2.x = xaxis.x * scaleLines;
  60808. point2.y = xaxis.y * scaleLines;
  60809. point2.z = xaxis.z * scaleLines;
  60810. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  60811. point2 = this._yline[1];
  60812. point2.x = yaxis.x * scaleLines;
  60813. point2.y = yaxis.y * scaleLines;
  60814. point2.z = yaxis.z * scaleLines;
  60815. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  60816. point2 = this._zline[1];
  60817. point2.x = zaxis.x * scaleLines;
  60818. point2.y = zaxis.y * scaleLines;
  60819. point2.z = zaxis.z * scaleLines;
  60820. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  60821. };
  60822. /** Releases resources */
  60823. AxesViewer.prototype.dispose = function () {
  60824. if (this._xmesh) {
  60825. this._xmesh.dispose();
  60826. }
  60827. if (this._ymesh) {
  60828. this._ymesh.dispose();
  60829. }
  60830. if (this._zmesh) {
  60831. this._zmesh.dispose();
  60832. }
  60833. this._xmesh = null;
  60834. this._ymesh = null;
  60835. this._zmesh = null;
  60836. this.scene = null;
  60837. };
  60838. return AxesViewer;
  60839. }());
  60840. Debug.AxesViewer = AxesViewer;
  60841. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  60842. })(BABYLON || (BABYLON = {}));
  60843. //# sourceMappingURL=babylon.axesViewer.js.map
  60844. var BABYLON;
  60845. (function (BABYLON) {
  60846. var Debug;
  60847. (function (Debug) {
  60848. /**
  60849. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  60850. * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
  60851. */
  60852. var BoneAxesViewer = /** @class */ (function (_super) {
  60853. __extends(BoneAxesViewer, _super);
  60854. /**
  60855. * Creates a new BoneAxesViewer
  60856. * @param scene defines the hosting scene
  60857. * @param bone defines the target bone
  60858. * @param mesh defines the target mesh
  60859. * @param scaleLines defines a scaling factor for line length (1 by default)
  60860. */
  60861. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  60862. if (scaleLines === void 0) { scaleLines = 1; }
  60863. var _this = _super.call(this, scene, scaleLines) || this;
  60864. /** Gets current position */
  60865. _this.pos = BABYLON.Vector3.Zero();
  60866. /** Gets direction of X axis */
  60867. _this.xaxis = BABYLON.Vector3.Zero();
  60868. /** Gets direction of Y axis */
  60869. _this.yaxis = BABYLON.Vector3.Zero();
  60870. /** Gets direction of Z axis */
  60871. _this.zaxis = BABYLON.Vector3.Zero();
  60872. _this.mesh = mesh;
  60873. _this.bone = bone;
  60874. return _this;
  60875. }
  60876. /**
  60877. * Force the viewer to update
  60878. */
  60879. BoneAxesViewer.prototype.update = function () {
  60880. if (!this.mesh || !this.bone) {
  60881. return;
  60882. }
  60883. var bone = this.bone;
  60884. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  60885. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  60886. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  60887. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  60888. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  60889. };
  60890. /** Releases resources */
  60891. BoneAxesViewer.prototype.dispose = function () {
  60892. if (this.mesh) {
  60893. this.mesh = null;
  60894. this.bone = null;
  60895. _super.prototype.dispose.call(this);
  60896. }
  60897. };
  60898. return BoneAxesViewer;
  60899. }(Debug.AxesViewer));
  60900. Debug.BoneAxesViewer = BoneAxesViewer;
  60901. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  60902. })(BABYLON || (BABYLON = {}));
  60903. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  60904. var BABYLON;
  60905. (function (BABYLON) {
  60906. var RayHelper = /** @class */ (function () {
  60907. function RayHelper(ray) {
  60908. this.ray = ray;
  60909. }
  60910. RayHelper.CreateAndShow = function (ray, scene, color) {
  60911. var helper = new RayHelper(ray);
  60912. helper.show(scene, color);
  60913. return helper;
  60914. };
  60915. RayHelper.prototype.show = function (scene, color) {
  60916. if (!this._renderFunction && this.ray) {
  60917. var ray = this.ray;
  60918. this._renderFunction = this._render.bind(this);
  60919. this._scene = scene;
  60920. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  60921. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  60922. if (this._renderFunction) {
  60923. this._scene.registerBeforeRender(this._renderFunction);
  60924. }
  60925. }
  60926. if (color && this._renderLine) {
  60927. this._renderLine.color.copyFrom(color);
  60928. }
  60929. };
  60930. RayHelper.prototype.hide = function () {
  60931. if (this._renderFunction && this._scene) {
  60932. this._scene.unregisterBeforeRender(this._renderFunction);
  60933. this._scene = null;
  60934. this._renderFunction = null;
  60935. if (this._renderLine) {
  60936. this._renderLine.dispose();
  60937. this._renderLine = null;
  60938. }
  60939. this._renderPoints = [];
  60940. }
  60941. };
  60942. RayHelper.prototype._render = function () {
  60943. var ray = this.ray;
  60944. if (!ray) {
  60945. return;
  60946. }
  60947. var point = this._renderPoints[1];
  60948. var len = Math.min(ray.length, 1000000);
  60949. point.copyFrom(ray.direction);
  60950. point.scaleInPlace(len);
  60951. point.addInPlace(ray.origin);
  60952. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  60953. };
  60954. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  60955. this._attachedToMesh = mesh;
  60956. var ray = this.ray;
  60957. if (!ray) {
  60958. return;
  60959. }
  60960. if (!ray.direction) {
  60961. ray.direction = BABYLON.Vector3.Zero();
  60962. }
  60963. if (!ray.origin) {
  60964. ray.origin = BABYLON.Vector3.Zero();
  60965. }
  60966. if (length) {
  60967. ray.length = length;
  60968. }
  60969. if (!meshSpaceOrigin) {
  60970. meshSpaceOrigin = BABYLON.Vector3.Zero();
  60971. }
  60972. if (!meshSpaceDirection) {
  60973. // -1 so that this will work with Mesh.lookAt
  60974. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  60975. }
  60976. if (!this._meshSpaceDirection) {
  60977. this._meshSpaceDirection = meshSpaceDirection.clone();
  60978. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  60979. }
  60980. else {
  60981. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  60982. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  60983. }
  60984. if (!this._updateToMeshFunction) {
  60985. this._updateToMeshFunction = this._updateToMesh.bind(this);
  60986. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  60987. }
  60988. this._updateToMesh();
  60989. };
  60990. RayHelper.prototype.detachFromMesh = function () {
  60991. if (this._attachedToMesh) {
  60992. if (this._updateToMeshFunction) {
  60993. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  60994. }
  60995. this._attachedToMesh = null;
  60996. this._updateToMeshFunction = null;
  60997. }
  60998. };
  60999. RayHelper.prototype._updateToMesh = function () {
  61000. var ray = this.ray;
  61001. if (!this._attachedToMesh || !ray) {
  61002. return;
  61003. }
  61004. if (this._attachedToMesh._isDisposed) {
  61005. this.detachFromMesh();
  61006. return;
  61007. }
  61008. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  61009. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  61010. };
  61011. RayHelper.prototype.dispose = function () {
  61012. this.hide();
  61013. this.detachFromMesh();
  61014. this.ray = null;
  61015. };
  61016. return RayHelper;
  61017. }());
  61018. BABYLON.RayHelper = RayHelper;
  61019. })(BABYLON || (BABYLON = {}));
  61020. //# sourceMappingURL=babylon.rayHelper.js.map
  61021. var BABYLON;
  61022. (function (BABYLON) {
  61023. Object.defineProperty(BABYLON.Scene.prototype, "debugLayer", {
  61024. get: function () {
  61025. if (!this._debugLayer) {
  61026. this._debugLayer = new DebugLayer(this);
  61027. }
  61028. return this._debugLayer;
  61029. },
  61030. enumerable: true,
  61031. configurable: true
  61032. });
  61033. var DebugLayer = /** @class */ (function () {
  61034. function DebugLayer(scene) {
  61035. var _this = this;
  61036. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  61037. this.onPropertyChangedObservable = new BABYLON.Observable();
  61038. this._scene = scene;
  61039. this._scene.onDisposeObservable.add(function () {
  61040. // Debug layer
  61041. if (_this._scene._debugLayer) {
  61042. _this._scene._debugLayer.hide();
  61043. }
  61044. });
  61045. }
  61046. /** Creates the inspector window. */
  61047. DebugLayer.prototype._createInspector = function (config) {
  61048. if (config === void 0) { config = {}; }
  61049. var popup = config.popup || false;
  61050. var initialTab = config.initialTab || 0;
  61051. var parentElement = config.parentElement || null;
  61052. if (!this._inspector) {
  61053. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  61054. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  61055. } // else nothing to do as instance is already created
  61056. };
  61057. DebugLayer.prototype.isVisible = function () {
  61058. if (!this._inspector) {
  61059. return false;
  61060. }
  61061. return true;
  61062. };
  61063. DebugLayer.prototype.hide = function () {
  61064. if (this._inspector) {
  61065. try {
  61066. this._inspector.dispose();
  61067. }
  61068. catch (e) {
  61069. // If the inspector has been removed directly from the inspector tool
  61070. }
  61071. this.onPropertyChangedObservable.clear();
  61072. this._inspector = null;
  61073. }
  61074. };
  61075. /**
  61076. *
  61077. * Launch the debugLayer.
  61078. *
  61079. * initialTab:
  61080. * | Value | Tab Name |
  61081. * | --- | --- |
  61082. * | 0 | Scene |
  61083. * | 1 | Console |
  61084. * | 2 | Stats |
  61085. * | 3 | Textures |
  61086. * | 4 | Mesh |
  61087. * | 5 | Light |
  61088. * | 6 | Material |
  61089. * | 7 | GLTF |
  61090. * | 8 | GUI |
  61091. * | 9 | Physics |
  61092. * | 10 | Camera |
  61093. * | 11 | Audio |
  61094. *
  61095. */
  61096. DebugLayer.prototype.show = function (config) {
  61097. if (config === void 0) { config = {}; }
  61098. if (typeof this.BJSINSPECTOR == 'undefined') {
  61099. // Load inspector and add it to the DOM
  61100. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  61101. }
  61102. else {
  61103. // Otherwise creates the inspector
  61104. this._createInspector(config);
  61105. }
  61106. };
  61107. /**
  61108. * Gets the active tab
  61109. * @return the index of the active tab or -1 if the inspector is hidden
  61110. */
  61111. DebugLayer.prototype.getActiveTab = function () {
  61112. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  61113. };
  61114. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  61115. return DebugLayer;
  61116. }());
  61117. BABYLON.DebugLayer = DebugLayer;
  61118. })(BABYLON || (BABYLON = {}));
  61119. //# sourceMappingURL=babylon.debugLayer.js.map
  61120. var BABYLON;
  61121. (function (BABYLON) {
  61122. var Debug;
  61123. (function (Debug) {
  61124. /**
  61125. * Used to show the physics impostor around the specific mesh
  61126. */
  61127. var PhysicsViewer = /** @class */ (function () {
  61128. /**
  61129. * Creates a new PhysicsViewer
  61130. * @param scene defines the hosting scene
  61131. */
  61132. function PhysicsViewer(scene) {
  61133. /** @hidden */
  61134. this._impostors = [];
  61135. /** @hidden */
  61136. this._meshes = [];
  61137. /** @hidden */
  61138. this._numMeshes = 0;
  61139. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  61140. var physicEngine = this._scene.getPhysicsEngine();
  61141. if (physicEngine) {
  61142. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  61143. }
  61144. }
  61145. /** @hidden */
  61146. PhysicsViewer.prototype._updateDebugMeshes = function () {
  61147. var plugin = this._physicsEnginePlugin;
  61148. for (var i = 0; i < this._numMeshes; i++) {
  61149. var impostor = this._impostors[i];
  61150. if (!impostor) {
  61151. continue;
  61152. }
  61153. if (impostor.isDisposed) {
  61154. this.hideImpostor(this._impostors[i--]);
  61155. }
  61156. else {
  61157. var mesh = this._meshes[i];
  61158. if (mesh && plugin) {
  61159. plugin.syncMeshWithImpostor(mesh, impostor);
  61160. }
  61161. }
  61162. }
  61163. };
  61164. /**
  61165. * Renders a specified physic impostor
  61166. * @param impostor defines the impostor to render
  61167. */
  61168. PhysicsViewer.prototype.showImpostor = function (impostor) {
  61169. if (!this._scene) {
  61170. return;
  61171. }
  61172. for (var i = 0; i < this._numMeshes; i++) {
  61173. if (this._impostors[i] == impostor) {
  61174. return;
  61175. }
  61176. }
  61177. var debugMesh = this._getDebugMesh(impostor, this._scene);
  61178. if (debugMesh) {
  61179. this._impostors[this._numMeshes] = impostor;
  61180. this._meshes[this._numMeshes] = debugMesh;
  61181. if (this._numMeshes === 0) {
  61182. this._renderFunction = this._updateDebugMeshes.bind(this);
  61183. this._scene.registerBeforeRender(this._renderFunction);
  61184. }
  61185. this._numMeshes++;
  61186. }
  61187. };
  61188. /**
  61189. * Hides a specified physic impostor
  61190. * @param impostor defines the impostor to hide
  61191. */
  61192. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  61193. if (!impostor || !this._scene) {
  61194. return;
  61195. }
  61196. var removed = false;
  61197. for (var i = 0; i < this._numMeshes; i++) {
  61198. if (this._impostors[i] == impostor) {
  61199. var mesh = this._meshes[i];
  61200. if (!mesh) {
  61201. continue;
  61202. }
  61203. this._scene.removeMesh(mesh);
  61204. mesh.dispose();
  61205. this._numMeshes--;
  61206. if (this._numMeshes > 0) {
  61207. this._meshes[i] = this._meshes[this._numMeshes];
  61208. this._impostors[i] = this._impostors[this._numMeshes];
  61209. this._meshes[this._numMeshes] = null;
  61210. this._impostors[this._numMeshes] = null;
  61211. }
  61212. else {
  61213. this._meshes[0] = null;
  61214. this._impostors[0] = null;
  61215. }
  61216. removed = true;
  61217. break;
  61218. }
  61219. }
  61220. if (removed && this._numMeshes === 0) {
  61221. this._scene.unregisterBeforeRender(this._renderFunction);
  61222. }
  61223. };
  61224. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  61225. if (!this._debugMaterial) {
  61226. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  61227. this._debugMaterial.wireframe = true;
  61228. }
  61229. return this._debugMaterial;
  61230. };
  61231. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  61232. if (!this._debugBoxMesh) {
  61233. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  61234. this._debugBoxMesh.renderingGroupId = 1;
  61235. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  61236. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  61237. scene.removeMesh(this._debugBoxMesh);
  61238. }
  61239. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  61240. };
  61241. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  61242. if (!this._debugSphereMesh) {
  61243. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  61244. this._debugSphereMesh.renderingGroupId = 1;
  61245. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  61246. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  61247. scene.removeMesh(this._debugSphereMesh);
  61248. }
  61249. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  61250. };
  61251. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  61252. var mesh = null;
  61253. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  61254. mesh = this._getDebugBoxMesh(scene);
  61255. impostor.getBoxSizeToRef(mesh.scaling);
  61256. }
  61257. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  61258. mesh = this._getDebugSphereMesh(scene);
  61259. var radius = impostor.getRadius();
  61260. mesh.scaling.x = radius * 2;
  61261. mesh.scaling.y = radius * 2;
  61262. mesh.scaling.z = radius * 2;
  61263. }
  61264. return mesh;
  61265. };
  61266. /** Releases all resources */
  61267. PhysicsViewer.prototype.dispose = function () {
  61268. for (var i = 0; i < this._numMeshes; i++) {
  61269. this.hideImpostor(this._impostors[i]);
  61270. }
  61271. if (this._debugBoxMesh) {
  61272. this._debugBoxMesh.dispose();
  61273. }
  61274. if (this._debugSphereMesh) {
  61275. this._debugSphereMesh.dispose();
  61276. }
  61277. if (this._debugMaterial) {
  61278. this._debugMaterial.dispose();
  61279. }
  61280. this._impostors.length = 0;
  61281. this._scene = null;
  61282. this._physicsEnginePlugin = null;
  61283. };
  61284. return PhysicsViewer;
  61285. }());
  61286. Debug.PhysicsViewer = PhysicsViewer;
  61287. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  61288. })(BABYLON || (BABYLON = {}));
  61289. //# sourceMappingURL=babylon.physicsViewer.js.map
  61290. var BABYLON;
  61291. (function (BABYLON) {
  61292. Object.defineProperty(BABYLON.Scene.prototype, "forceShowBoundingBoxes", {
  61293. get: function () {
  61294. return this._forceShowBoundingBoxes || false;
  61295. },
  61296. set: function (value) {
  61297. this._forceShowBoundingBoxes = value;
  61298. // Lazyly creates a BB renderer if needed.
  61299. if (value) {
  61300. this.getBoundingBoxRenderer();
  61301. }
  61302. },
  61303. enumerable: true,
  61304. configurable: true
  61305. });
  61306. BABYLON.Scene.prototype.getBoundingBoxRenderer = function () {
  61307. if (!this._boundingBoxRenderer) {
  61308. this._boundingBoxRenderer = new BoundingBoxRenderer(this);
  61309. }
  61310. return this._boundingBoxRenderer;
  61311. };
  61312. Object.defineProperty(BABYLON.AbstractMesh.prototype, "showBoundingBox", {
  61313. get: function () {
  61314. return this._showBoundingBox || false;
  61315. },
  61316. set: function (value) {
  61317. this._showBoundingBox = value;
  61318. // Lazyly creates a BB renderer if needed.
  61319. if (value) {
  61320. this.getScene().getBoundingBoxRenderer();
  61321. }
  61322. },
  61323. enumerable: true,
  61324. configurable: true
  61325. });
  61326. var BoundingBoxRenderer = /** @class */ (function () {
  61327. function BoundingBoxRenderer(scene) {
  61328. /**
  61329. * The component name helpfull to identify the component in the list of scene components.
  61330. */
  61331. this.name = BABYLON.SceneComponentConstants.NAME_BOUNDINGBOXRENDERER;
  61332. this.frontColor = new BABYLON.Color3(1, 1, 1);
  61333. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  61334. this.showBackLines = true;
  61335. this.renderList = new BABYLON.SmartArray(32);
  61336. this._vertexBuffers = {};
  61337. this.scene = scene;
  61338. scene._addComponent(this);
  61339. }
  61340. /**
  61341. * Registers the component in a given scene
  61342. */
  61343. BoundingBoxRenderer.prototype.register = function () {
  61344. this.scene._beforeEvaluateActiveMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER, this, this.reset);
  61345. this.scene._activeMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER, this, this._activeMesh);
  61346. this.scene._evaluateSubMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER, this, this._evaluateSubMesh);
  61347. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_BOUNDINGBOXRENDERER, this, this.render);
  61348. };
  61349. BoundingBoxRenderer.prototype._evaluateSubMesh = function (mesh, subMesh) {
  61350. if (mesh.showSubMeshesBoundingBox) {
  61351. var boundingInfo = subMesh.getBoundingInfo();
  61352. if (boundingInfo !== null && boundingInfo !== undefined) {
  61353. this.renderList.push(boundingInfo.boundingBox);
  61354. }
  61355. }
  61356. };
  61357. BoundingBoxRenderer.prototype._activeMesh = function (sourceMesh, mesh) {
  61358. if (sourceMesh.showBoundingBox || this.scene.forceShowBoundingBoxes) {
  61359. var boundingInfo = sourceMesh.getBoundingInfo();
  61360. this.renderList.push(boundingInfo.boundingBox);
  61361. }
  61362. };
  61363. BoundingBoxRenderer.prototype._prepareRessources = function () {
  61364. if (this._colorShader) {
  61365. return;
  61366. }
  61367. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this.scene, "color", {
  61368. attributes: [BABYLON.VertexBuffer.PositionKind],
  61369. uniforms: ["world", "viewProjection", "color"]
  61370. });
  61371. var engine = this.scene.getEngine();
  61372. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  61373. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  61374. this._createIndexBuffer();
  61375. };
  61376. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  61377. var engine = this.scene.getEngine();
  61378. 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]);
  61379. };
  61380. /**
  61381. * Rebuilds the elements related to this component in case of
  61382. * context lost for instance.
  61383. */
  61384. BoundingBoxRenderer.prototype.rebuild = function () {
  61385. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  61386. if (vb) {
  61387. vb._rebuild();
  61388. }
  61389. this._createIndexBuffer();
  61390. };
  61391. BoundingBoxRenderer.prototype.reset = function () {
  61392. this.renderList.reset();
  61393. };
  61394. BoundingBoxRenderer.prototype.render = function () {
  61395. if (this.renderList.length === 0) {
  61396. return;
  61397. }
  61398. this._prepareRessources();
  61399. if (!this._colorShader.isReady()) {
  61400. return;
  61401. }
  61402. var engine = this.scene.getEngine();
  61403. engine.setDepthWrite(false);
  61404. this._colorShader._preBind();
  61405. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  61406. var boundingBox = this.renderList.data[boundingBoxIndex];
  61407. var min = boundingBox.minimum;
  61408. var max = boundingBox.maximum;
  61409. var diff = max.subtract(min);
  61410. var median = min.add(diff.scale(0.5));
  61411. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  61412. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  61413. .multiply(boundingBox.getWorldMatrix());
  61414. // VBOs
  61415. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  61416. if (this.showBackLines) {
  61417. // Back
  61418. engine.setDepthFunctionToGreaterOrEqual();
  61419. this.scene.resetCachedMaterial();
  61420. this._colorShader.setColor4("color", this.backColor.toColor4());
  61421. this._colorShader.bind(worldMatrix);
  61422. // Draw order
  61423. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  61424. }
  61425. // Front
  61426. engine.setDepthFunctionToLess();
  61427. this.scene.resetCachedMaterial();
  61428. this._colorShader.setColor4("color", this.frontColor.toColor4());
  61429. this._colorShader.bind(worldMatrix);
  61430. // Draw order
  61431. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  61432. }
  61433. this._colorShader.unbind();
  61434. engine.setDepthFunctionToLessOrEqual();
  61435. engine.setDepthWrite(true);
  61436. };
  61437. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  61438. this._prepareRessources();
  61439. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  61440. return;
  61441. }
  61442. var engine = this.scene.getEngine();
  61443. engine.setDepthWrite(false);
  61444. engine.setColorWrite(false);
  61445. this._colorShader._preBind();
  61446. var boundingBox = mesh._boundingInfo.boundingBox;
  61447. var min = boundingBox.minimum;
  61448. var max = boundingBox.maximum;
  61449. var diff = max.subtract(min);
  61450. var median = min.add(diff.scale(0.5));
  61451. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  61452. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  61453. .multiply(boundingBox.getWorldMatrix());
  61454. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  61455. engine.setDepthFunctionToLess();
  61456. this.scene.resetCachedMaterial();
  61457. this._colorShader.bind(worldMatrix);
  61458. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  61459. this._colorShader.unbind();
  61460. engine.setDepthFunctionToLessOrEqual();
  61461. engine.setDepthWrite(true);
  61462. engine.setColorWrite(true);
  61463. };
  61464. BoundingBoxRenderer.prototype.dispose = function () {
  61465. if (!this._colorShader) {
  61466. return;
  61467. }
  61468. this.renderList.dispose();
  61469. this._colorShader.dispose();
  61470. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  61471. if (buffer) {
  61472. buffer.dispose();
  61473. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  61474. }
  61475. this.scene.getEngine()._releaseBuffer(this._indexBuffer);
  61476. };
  61477. return BoundingBoxRenderer;
  61478. }());
  61479. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  61480. })(BABYLON || (BABYLON = {}));
  61481. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  61482. var BABYLON;
  61483. (function (BABYLON) {
  61484. BABYLON.Engine.prototype.createTransformFeedback = function () {
  61485. return this._gl.createTransformFeedback();
  61486. };
  61487. BABYLON.Engine.prototype.deleteTransformFeedback = function (value) {
  61488. this._gl.deleteTransformFeedback(value);
  61489. };
  61490. BABYLON.Engine.prototype.bindTransformFeedback = function (value) {
  61491. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  61492. };
  61493. BABYLON.Engine.prototype.beginTransformFeedback = function (usePoints) {
  61494. if (usePoints === void 0) { usePoints = true; }
  61495. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  61496. };
  61497. BABYLON.Engine.prototype.endTransformFeedback = function () {
  61498. this._gl.endTransformFeedback();
  61499. };
  61500. BABYLON.Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  61501. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  61502. };
  61503. BABYLON.Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  61504. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  61505. };
  61506. })(BABYLON || (BABYLON = {}));
  61507. //# sourceMappingURL=babylon.engine.transformFeedback.js.map
  61508. var BABYLON;
  61509. (function (BABYLON) {
  61510. /**
  61511. * This represents a GPU particle system in Babylon
  61512. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  61513. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  61514. */
  61515. var GPUParticleSystem = /** @class */ (function (_super) {
  61516. __extends(GPUParticleSystem, _super);
  61517. /**
  61518. * Instantiates a GPU particle system.
  61519. * 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.
  61520. * @param name The name of the particle system
  61521. * @param options The options used to create the system
  61522. * @param scene The scene the particle system belongs to
  61523. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  61524. */
  61525. function GPUParticleSystem(name, options, scene, isAnimationSheetEnabled) {
  61526. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  61527. var _this = _super.call(this, name) || this;
  61528. /**
  61529. * The layer mask we are rendering the particles through.
  61530. */
  61531. _this.layerMask = 0x0FFFFFFF;
  61532. _this._accumulatedCount = 0;
  61533. _this._targetIndex = 0;
  61534. _this._currentRenderId = -1;
  61535. _this._started = false;
  61536. _this._stopped = false;
  61537. _this._timeDelta = 0;
  61538. _this._attributesStrideSize = 21;
  61539. _this._actualFrame = 0;
  61540. _this._rawTextureWidth = 256;
  61541. /**
  61542. * An event triggered when the system is disposed.
  61543. */
  61544. _this.onDisposeObservable = new BABYLON.Observable();
  61545. /**
  61546. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  61547. * to override the particles.
  61548. */
  61549. _this.forceDepthWrite = false;
  61550. _this._preWarmDone = false;
  61551. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  61552. // Setup the default processing configuration to the scene.
  61553. _this._attachImageProcessingConfiguration(null);
  61554. _this._engine = _this._scene.getEngine();
  61555. if (!options.randomTextureSize) {
  61556. delete options.randomTextureSize;
  61557. }
  61558. var fullOptions = __assign({ capacity: 50000, randomTextureSize: _this._engine.getCaps().maxTextureSize }, options);
  61559. var optionsAsNumber = options;
  61560. if (isFinite(optionsAsNumber)) {
  61561. fullOptions.capacity = optionsAsNumber;
  61562. }
  61563. _this._capacity = fullOptions.capacity;
  61564. _this._activeCount = fullOptions.capacity;
  61565. _this._currentActiveCount = 0;
  61566. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  61567. _this._scene.particleSystems.push(_this);
  61568. _this._updateEffectOptions = {
  61569. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "initialDirection", "angle", "cellIndex", "cellStartOffset"],
  61570. uniformsNames: ["currentCount", "timeDelta", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "scaleRange", "gravity", "emitPower",
  61571. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  61572. "angleRange", "radiusRange", "cellInfos", "noiseStrength", "limitVelocityDamping"],
  61573. uniformBuffersNames: [],
  61574. samplers: ["randomSampler", "randomSampler2", "sizeGradientSampler", "angularSpeedGradientSampler", "velocityGradientSampler", "limitVelocityGradientSampler", "noiseSampler", "dragGradientSampler"],
  61575. defines: "",
  61576. fallbacks: null,
  61577. onCompiled: null,
  61578. onError: null,
  61579. indexParameters: null,
  61580. maxSimultaneousLights: 0,
  61581. transformFeedbackVaryings: []
  61582. };
  61583. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  61584. // Random data
  61585. var maxTextureSize = Math.min(_this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  61586. var d = [];
  61587. for (var i = 0; i < maxTextureSize; ++i) {
  61588. d.push(Math.random());
  61589. d.push(Math.random());
  61590. d.push(Math.random());
  61591. d.push(Math.random());
  61592. }
  61593. _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);
  61594. _this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  61595. _this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  61596. d = [];
  61597. for (var i = 0; i < maxTextureSize; ++i) {
  61598. d.push(Math.random());
  61599. d.push(Math.random());
  61600. d.push(Math.random());
  61601. d.push(Math.random());
  61602. }
  61603. _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);
  61604. _this._randomTexture2.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  61605. _this._randomTexture2.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  61606. _this._randomTextureSize = maxTextureSize;
  61607. return _this;
  61608. }
  61609. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  61610. /**
  61611. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  61612. */
  61613. get: function () {
  61614. if (!BABYLON.Engine.LastCreatedEngine) {
  61615. return false;
  61616. }
  61617. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  61618. },
  61619. enumerable: true,
  61620. configurable: true
  61621. });
  61622. /**
  61623. * Gets the maximum number of particles active at the same time.
  61624. * @returns The max number of active particles.
  61625. */
  61626. GPUParticleSystem.prototype.getCapacity = function () {
  61627. return this._capacity;
  61628. };
  61629. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  61630. /**
  61631. * Gets or set the number of active particles
  61632. */
  61633. get: function () {
  61634. return this._activeCount;
  61635. },
  61636. set: function (value) {
  61637. this._activeCount = Math.min(value, this._capacity);
  61638. },
  61639. enumerable: true,
  61640. configurable: true
  61641. });
  61642. /**
  61643. * Is this system ready to be used/rendered
  61644. * @return true if the system is ready
  61645. */
  61646. GPUParticleSystem.prototype.isReady = function () {
  61647. if (!this._updateEffect) {
  61648. this._recreateUpdateEffect();
  61649. this._recreateRenderEffect();
  61650. return false;
  61651. }
  61652. if (!this.emitter || !this._updateEffect.isReady() || !this._imageProcessingConfiguration.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  61653. return false;
  61654. }
  61655. return true;
  61656. };
  61657. /**
  61658. * Gets if the system has been started. (Note: this will still be true after stop is called)
  61659. * @returns True if it has been started, otherwise false.
  61660. */
  61661. GPUParticleSystem.prototype.isStarted = function () {
  61662. return this._started;
  61663. };
  61664. /**
  61665. * Starts the particle system and begins to emit
  61666. * @param delay defines the delay in milliseconds before starting the system (0 by default)
  61667. */
  61668. GPUParticleSystem.prototype.start = function (delay) {
  61669. var _this = this;
  61670. if (delay === void 0) { delay = 0; }
  61671. if (delay) {
  61672. setTimeout(function () {
  61673. _this.start(0);
  61674. }, delay);
  61675. return;
  61676. }
  61677. this._started = true;
  61678. this._stopped = false;
  61679. this._preWarmDone = false;
  61680. };
  61681. /**
  61682. * Stops the particle system.
  61683. */
  61684. GPUParticleSystem.prototype.stop = function () {
  61685. this._stopped = true;
  61686. };
  61687. /**
  61688. * Remove all active particles
  61689. */
  61690. GPUParticleSystem.prototype.reset = function () {
  61691. this._releaseBuffers();
  61692. this._releaseVAOs();
  61693. this._currentActiveCount = 0;
  61694. this._targetIndex = 0;
  61695. };
  61696. /**
  61697. * Returns the string "GPUParticleSystem"
  61698. * @returns a string containing the class name
  61699. */
  61700. GPUParticleSystem.prototype.getClassName = function () {
  61701. return "GPUParticleSystem";
  61702. };
  61703. GPUParticleSystem.prototype._removeGradientAndTexture = function (gradient, gradients, texture) {
  61704. _super.prototype._removeGradientAndTexture.call(this, gradient, gradients, texture);
  61705. this._releaseBuffers();
  61706. return this;
  61707. };
  61708. /**
  61709. * Adds a new color gradient
  61710. * @param gradient defines the gradient to use (between 0 and 1)
  61711. * @param color defines the color to affect to the specified gradient
  61712. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  61713. * @returns the current particle system
  61714. */
  61715. GPUParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  61716. if (!this._colorGradients) {
  61717. this._colorGradients = [];
  61718. }
  61719. var colorGradient = new BABYLON.ColorGradient();
  61720. colorGradient.gradient = gradient;
  61721. colorGradient.color1 = color1;
  61722. this._colorGradients.push(colorGradient);
  61723. this._colorGradients.sort(function (a, b) {
  61724. if (a.gradient < b.gradient) {
  61725. return -1;
  61726. }
  61727. else if (a.gradient > b.gradient) {
  61728. return 1;
  61729. }
  61730. return 0;
  61731. });
  61732. if (this._colorGradientsTexture) {
  61733. this._colorGradientsTexture.dispose();
  61734. this._colorGradientsTexture = null;
  61735. }
  61736. this._releaseBuffers();
  61737. return this;
  61738. };
  61739. /**
  61740. * Remove a specific color gradient
  61741. * @param gradient defines the gradient to remove
  61742. * @returns the current particle system
  61743. */
  61744. GPUParticleSystem.prototype.removeColorGradient = function (gradient) {
  61745. this._removeGradientAndTexture(gradient, this._colorGradients, this._colorGradientsTexture);
  61746. this._colorGradientsTexture = null;
  61747. return this;
  61748. };
  61749. GPUParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor) {
  61750. var valueGradient = new BABYLON.FactorGradient();
  61751. valueGradient.gradient = gradient;
  61752. valueGradient.factor1 = factor;
  61753. factorGradients.push(valueGradient);
  61754. factorGradients.sort(function (a, b) {
  61755. if (a.gradient < b.gradient) {
  61756. return -1;
  61757. }
  61758. else if (a.gradient > b.gradient) {
  61759. return 1;
  61760. }
  61761. return 0;
  61762. });
  61763. this._releaseBuffers();
  61764. };
  61765. /**
  61766. * Adds a new size gradient
  61767. * @param gradient defines the gradient to use (between 0 and 1)
  61768. * @param factor defines the size factor to affect to the specified gradient
  61769. * @returns the current particle system
  61770. */
  61771. GPUParticleSystem.prototype.addSizeGradient = function (gradient, factor) {
  61772. if (!this._sizeGradients) {
  61773. this._sizeGradients = [];
  61774. }
  61775. this._addFactorGradient(this._sizeGradients, gradient, factor);
  61776. if (this._sizeGradientsTexture) {
  61777. this._sizeGradientsTexture.dispose();
  61778. this._sizeGradientsTexture = null;
  61779. }
  61780. this._releaseBuffers();
  61781. return this;
  61782. };
  61783. /**
  61784. * Remove a specific size gradient
  61785. * @param gradient defines the gradient to remove
  61786. * @returns the current particle system
  61787. */
  61788. GPUParticleSystem.prototype.removeSizeGradient = function (gradient) {
  61789. this._removeGradientAndTexture(gradient, this._sizeGradients, this._sizeGradientsTexture);
  61790. this._sizeGradientsTexture = null;
  61791. return this;
  61792. };
  61793. /**
  61794. * Adds a new angular speed gradient
  61795. * @param gradient defines the gradient to use (between 0 and 1)
  61796. * @param factor defines the angular speed to affect to the specified gradient
  61797. * @returns the current particle system
  61798. */
  61799. GPUParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor) {
  61800. if (!this._angularSpeedGradients) {
  61801. this._angularSpeedGradients = [];
  61802. }
  61803. this._addFactorGradient(this._angularSpeedGradients, gradient, factor);
  61804. if (this._angularSpeedGradientsTexture) {
  61805. this._angularSpeedGradientsTexture.dispose();
  61806. this._angularSpeedGradientsTexture = null;
  61807. }
  61808. this._releaseBuffers();
  61809. return this;
  61810. };
  61811. /**
  61812. * Remove a specific angular speed gradient
  61813. * @param gradient defines the gradient to remove
  61814. * @returns the current particle system
  61815. */
  61816. GPUParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  61817. this._removeGradientAndTexture(gradient, this._angularSpeedGradients, this._angularSpeedGradientsTexture);
  61818. this._angularSpeedGradientsTexture = null;
  61819. return this;
  61820. };
  61821. /**
  61822. * Adds a new velocity gradient
  61823. * @param gradient defines the gradient to use (between 0 and 1)
  61824. * @param factor defines the velocity to affect to the specified gradient
  61825. * @returns the current particle system
  61826. */
  61827. GPUParticleSystem.prototype.addVelocityGradient = function (gradient, factor) {
  61828. if (!this._velocityGradients) {
  61829. this._velocityGradients = [];
  61830. }
  61831. this._addFactorGradient(this._velocityGradients, gradient, factor);
  61832. if (this._velocityGradientsTexture) {
  61833. this._velocityGradientsTexture.dispose();
  61834. this._velocityGradientsTexture = null;
  61835. }
  61836. this._releaseBuffers();
  61837. return this;
  61838. };
  61839. /**
  61840. * Remove a specific velocity gradient
  61841. * @param gradient defines the gradient to remove
  61842. * @returns the current particle system
  61843. */
  61844. GPUParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  61845. this._removeGradientAndTexture(gradient, this._velocityGradients, this._velocityGradientsTexture);
  61846. this._velocityGradientsTexture = null;
  61847. return this;
  61848. };
  61849. /**
  61850. * Adds a new limit velocity gradient
  61851. * @param gradient defines the gradient to use (between 0 and 1)
  61852. * @param factor defines the limit velocity value to affect to the specified gradient
  61853. * @returns the current particle system
  61854. */
  61855. GPUParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor) {
  61856. if (!this._limitVelocityGradients) {
  61857. this._limitVelocityGradients = [];
  61858. }
  61859. this._addFactorGradient(this._limitVelocityGradients, gradient, factor);
  61860. if (this._limitVelocityGradientsTexture) {
  61861. this._limitVelocityGradientsTexture.dispose();
  61862. this._limitVelocityGradientsTexture = null;
  61863. }
  61864. this._releaseBuffers();
  61865. return this;
  61866. };
  61867. /**
  61868. * Remove a specific limit velocity gradient
  61869. * @param gradient defines the gradient to remove
  61870. * @returns the current particle system
  61871. */
  61872. GPUParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  61873. this._removeGradientAndTexture(gradient, this._limitVelocityGradients, this._limitVelocityGradientsTexture);
  61874. this._limitVelocityGradientsTexture = null;
  61875. return this;
  61876. };
  61877. /**
  61878. * Adds a new drag gradient
  61879. * @param gradient defines the gradient to use (between 0 and 1)
  61880. * @param factor defines the drag value to affect to the specified gradient
  61881. * @returns the current particle system
  61882. */
  61883. GPUParticleSystem.prototype.addDragGradient = function (gradient, factor) {
  61884. if (!this._dragGradients) {
  61885. this._dragGradients = [];
  61886. }
  61887. this._addFactorGradient(this._dragGradients, gradient, factor);
  61888. if (this._dragGradientsTexture) {
  61889. this._dragGradientsTexture.dispose();
  61890. this._dragGradientsTexture = null;
  61891. }
  61892. this._releaseBuffers();
  61893. return this;
  61894. };
  61895. /**
  61896. * Remove a specific drag gradient
  61897. * @param gradient defines the gradient to remove
  61898. * @returns the current particle system
  61899. */
  61900. GPUParticleSystem.prototype.removeDragGradient = function (gradient) {
  61901. this._removeGradientAndTexture(gradient, this._dragGradients, this._dragGradientsTexture);
  61902. this._dragGradientsTexture = null;
  61903. return this;
  61904. };
  61905. /**
  61906. * Not supported by GPUParticleSystem
  61907. * @param gradient defines the gradient to use (between 0 and 1)
  61908. * @param factor defines the emit rate value to affect to the specified gradient
  61909. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  61910. * @returns the current particle system
  61911. */
  61912. GPUParticleSystem.prototype.addEmitRateGradient = function (gradient, factor, factor2) {
  61913. // Do nothing as emit rate is not supported by GPUParticleSystem
  61914. return this;
  61915. };
  61916. /**
  61917. * Not supported by GPUParticleSystem
  61918. * @param gradient defines the gradient to remove
  61919. * @returns the current particle system
  61920. */
  61921. GPUParticleSystem.prototype.removeEmitRateGradient = function (gradient) {
  61922. // Do nothing as emit rate is not supported by GPUParticleSystem
  61923. return this;
  61924. };
  61925. /**
  61926. * Not supported by GPUParticleSystem
  61927. * @param gradient defines the gradient to use (between 0 and 1)
  61928. * @param factor defines the start size value to affect to the specified gradient
  61929. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  61930. * @returns the current particle system
  61931. */
  61932. GPUParticleSystem.prototype.addStartSizeGradient = function (gradient, factor, factor2) {
  61933. // Do nothing as start size is not supported by GPUParticleSystem
  61934. return this;
  61935. };
  61936. /**
  61937. * Not supported by GPUParticleSystem
  61938. * @param gradient defines the gradient to remove
  61939. * @returns the current particle system
  61940. */
  61941. GPUParticleSystem.prototype.removeStartSizeGradient = function (gradient) {
  61942. // Do nothing as start size is not supported by GPUParticleSystem
  61943. return this;
  61944. };
  61945. /**
  61946. * Not supported by GPUParticleSystem
  61947. * @param gradient defines the gradient to use (between 0 and 1)
  61948. * @param min defines the color remap minimal range
  61949. * @param max defines the color remap maximal range
  61950. * @returns the current particle system
  61951. */
  61952. GPUParticleSystem.prototype.addColorRemapGradient = function (gradient, min, max) {
  61953. // Do nothing as start size is not supported by GPUParticleSystem
  61954. return this;
  61955. };
  61956. /**
  61957. * Not supported by GPUParticleSystem
  61958. * @param gradient defines the gradient to remove
  61959. * @returns the current particle system
  61960. */
  61961. GPUParticleSystem.prototype.removeColorRemapGradient = function (gradient) {
  61962. // Do nothing as start size is not supported by GPUParticleSystem
  61963. return this;
  61964. };
  61965. /**
  61966. * Not supported by GPUParticleSystem
  61967. * @param gradient defines the gradient to use (between 0 and 1)
  61968. * @param min defines the alpha remap minimal range
  61969. * @param max defines the alpha remap maximal range
  61970. * @returns the current particle system
  61971. */
  61972. GPUParticleSystem.prototype.addAlphaRemapGradient = function (gradient, min, max) {
  61973. // Do nothing as start size is not supported by GPUParticleSystem
  61974. return this;
  61975. };
  61976. /**
  61977. * Not supported by GPUParticleSystem
  61978. * @param gradient defines the gradient to remove
  61979. * @returns the current particle system
  61980. */
  61981. GPUParticleSystem.prototype.removeAlphaRemapGradient = function (gradient) {
  61982. // Do nothing as start size is not supported by GPUParticleSystem
  61983. return this;
  61984. };
  61985. /**
  61986. * Not supported by GPUParticleSystem
  61987. * @param gradient defines the gradient to use (between 0 and 1)
  61988. * @param color defines the color to affect to the specified gradient
  61989. * @returns the current particle system
  61990. */
  61991. GPUParticleSystem.prototype.addRampGradient = function (gradient, color) {
  61992. //Not supported by GPUParticleSystem
  61993. return this;
  61994. };
  61995. /**
  61996. * Not supported by GPUParticleSystem
  61997. * @param gradient defines the gradient to remove
  61998. * @returns the current particle system
  61999. */
  62000. GPUParticleSystem.prototype.removeRampGradient = function (gradient) {
  62001. //Not supported by GPUParticleSystem
  62002. return this;
  62003. };
  62004. /**
  62005. * Not supported by GPUParticleSystem
  62006. * @returns the list of ramp gradients
  62007. */
  62008. GPUParticleSystem.prototype.getRampGradients = function () {
  62009. return null;
  62010. };
  62011. GPUParticleSystem.prototype._reset = function () {
  62012. this._releaseBuffers();
  62013. };
  62014. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  62015. var updateVertexBuffers = {};
  62016. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  62017. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  62018. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  62019. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 4);
  62020. updateVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3);
  62021. var offset = 12;
  62022. if (!this._colorGradientsTexture) {
  62023. updateVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4);
  62024. offset += 4;
  62025. }
  62026. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3);
  62027. offset += 3;
  62028. if (!this._isBillboardBased) {
  62029. updateVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3);
  62030. offset += 3;
  62031. }
  62032. if (this._angularSpeedGradientsTexture) {
  62033. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1);
  62034. offset += 1;
  62035. }
  62036. else {
  62037. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2);
  62038. offset += 2;
  62039. }
  62040. if (this._isAnimationSheetEnabled) {
  62041. updateVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1);
  62042. offset += 1;
  62043. if (this.spriteRandomStartCell) {
  62044. updateVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1);
  62045. offset += 1;
  62046. }
  62047. }
  62048. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  62049. this._engine.bindArrayBuffer(null);
  62050. return vao;
  62051. };
  62052. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  62053. var renderVertexBuffers = {};
  62054. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  62055. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  62056. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  62057. renderVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3, this._attributesStrideSize, true);
  62058. var offset = 12;
  62059. if (!this._colorGradientsTexture) {
  62060. renderVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4, this._attributesStrideSize, true);
  62061. offset += 4;
  62062. }
  62063. offset += 3; // Direction
  62064. if (!this._isBillboardBased) {
  62065. renderVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3, this._attributesStrideSize, true);
  62066. offset += 3;
  62067. }
  62068. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1, this._attributesStrideSize, true);
  62069. if (this._angularSpeedGradientsTexture) {
  62070. offset++;
  62071. }
  62072. else {
  62073. offset += 2;
  62074. }
  62075. if (this._isAnimationSheetEnabled) {
  62076. renderVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1, this._attributesStrideSize, true);
  62077. offset += 1;
  62078. if (this.spriteRandomStartCell) {
  62079. renderVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1, this._attributesStrideSize, true);
  62080. offset += 1;
  62081. }
  62082. }
  62083. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  62084. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  62085. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  62086. this._engine.bindArrayBuffer(null);
  62087. return vao;
  62088. };
  62089. GPUParticleSystem.prototype._initialize = function (force) {
  62090. if (force === void 0) { force = false; }
  62091. if (this._buffer0 && !force) {
  62092. return;
  62093. }
  62094. var engine = this._scene.getEngine();
  62095. var data = new Array();
  62096. if (!this.isBillboardBased) {
  62097. this._attributesStrideSize += 3;
  62098. }
  62099. if (this._colorGradientsTexture) {
  62100. this._attributesStrideSize -= 4;
  62101. }
  62102. if (this._angularSpeedGradientsTexture) {
  62103. this._attributesStrideSize -= 1;
  62104. }
  62105. if (this._isAnimationSheetEnabled) {
  62106. this._attributesStrideSize += 1;
  62107. if (this.spriteRandomStartCell) {
  62108. this._attributesStrideSize += 1;
  62109. }
  62110. }
  62111. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  62112. // position
  62113. data.push(0.0);
  62114. data.push(0.0);
  62115. data.push(0.0);
  62116. // Age and life
  62117. data.push(0.0); // create the particle as a dead one to create a new one at start
  62118. data.push(0.0);
  62119. // Seed
  62120. data.push(Math.random());
  62121. data.push(Math.random());
  62122. data.push(Math.random());
  62123. data.push(Math.random());
  62124. // Size
  62125. data.push(0.0);
  62126. data.push(0.0);
  62127. data.push(0.0);
  62128. if (!this._colorGradientsTexture) {
  62129. // color
  62130. data.push(0.0);
  62131. data.push(0.0);
  62132. data.push(0.0);
  62133. data.push(0.0);
  62134. }
  62135. // direction
  62136. data.push(0.0);
  62137. data.push(0.0);
  62138. data.push(0.0);
  62139. if (!this.isBillboardBased) {
  62140. // initialDirection
  62141. data.push(0.0);
  62142. data.push(0.0);
  62143. data.push(0.0);
  62144. }
  62145. // angle
  62146. data.push(0.0);
  62147. if (!this._angularSpeedGradientsTexture) {
  62148. data.push(0.0);
  62149. }
  62150. if (this._isAnimationSheetEnabled) {
  62151. data.push(0.0);
  62152. if (this.spriteRandomStartCell) {
  62153. data.push(0.0);
  62154. }
  62155. }
  62156. }
  62157. // Sprite data
  62158. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  62159. -0.5, 0.5, 0, 1,
  62160. -0.5, -0.5, 0, 0,
  62161. 0.5, -0.5, 1, 0]);
  62162. // Buffers
  62163. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  62164. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  62165. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  62166. // Update VAO
  62167. this._updateVAO = [];
  62168. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  62169. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  62170. // Render VAO
  62171. this._renderVAO = [];
  62172. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  62173. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  62174. // Links
  62175. this._sourceBuffer = this._buffer0;
  62176. this._targetBuffer = this._buffer1;
  62177. };
  62178. /** @hidden */
  62179. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  62180. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  62181. if (this._isBillboardBased) {
  62182. defines += "\n#define BILLBOARD";
  62183. }
  62184. if (this._colorGradientsTexture) {
  62185. defines += "\n#define COLORGRADIENTS";
  62186. }
  62187. if (this._sizeGradientsTexture) {
  62188. defines += "\n#define SIZEGRADIENTS";
  62189. }
  62190. if (this._angularSpeedGradientsTexture) {
  62191. defines += "\n#define ANGULARSPEEDGRADIENTS";
  62192. }
  62193. if (this._velocityGradientsTexture) {
  62194. defines += "\n#define VELOCITYGRADIENTS";
  62195. }
  62196. if (this._limitVelocityGradientsTexture) {
  62197. defines += "\n#define LIMITVELOCITYGRADIENTS";
  62198. }
  62199. if (this._dragGradientsTexture) {
  62200. defines += "\n#define DRAGGRADIENTS";
  62201. }
  62202. if (this.isAnimationSheetEnabled) {
  62203. defines += "\n#define ANIMATESHEET";
  62204. if (this.spriteRandomStartCell) {
  62205. defines += "\n#define ANIMATESHEETRANDOMSTART";
  62206. }
  62207. }
  62208. if (this.noiseTexture) {
  62209. defines += "\n#define NOISE";
  62210. }
  62211. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  62212. return;
  62213. }
  62214. this._updateEffectOptions.transformFeedbackVaryings = ["outPosition", "outAge", "outLife", "outSeed", "outSize"];
  62215. if (!this._colorGradientsTexture) {
  62216. this._updateEffectOptions.transformFeedbackVaryings.push("outColor");
  62217. }
  62218. this._updateEffectOptions.transformFeedbackVaryings.push("outDirection");
  62219. if (!this._isBillboardBased) {
  62220. this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection");
  62221. }
  62222. this._updateEffectOptions.transformFeedbackVaryings.push("outAngle");
  62223. if (this.isAnimationSheetEnabled) {
  62224. this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex");
  62225. if (this.spriteRandomStartCell) {
  62226. this._updateEffectOptions.transformFeedbackVaryings.push("outCellStartOffset");
  62227. }
  62228. }
  62229. this._updateEffectOptions.defines = defines;
  62230. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  62231. };
  62232. /** @hidden */
  62233. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  62234. var defines = "";
  62235. if (this._scene.clipPlane) {
  62236. defines = "\n#define CLIPPLANE";
  62237. }
  62238. if (this._scene.clipPlane2) {
  62239. defines = "\n#define CLIPPLANE2";
  62240. }
  62241. if (this._scene.clipPlane3) {
  62242. defines = "\n#define CLIPPLANE3";
  62243. }
  62244. if (this._scene.clipPlane4) {
  62245. defines = "\n#define CLIPPLANE4";
  62246. }
  62247. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_MULTIPLY) {
  62248. defines = "\n#define BLENDMULTIPLYMODE";
  62249. }
  62250. if (this._isBillboardBased) {
  62251. defines += "\n#define BILLBOARD";
  62252. switch (this.billboardMode) {
  62253. case BABYLON.AbstractMesh.BILLBOARDMODE_Y:
  62254. defines += "\n#define BILLBOARDY";
  62255. break;
  62256. case BABYLON.AbstractMesh.BILLBOARDMODE_ALL:
  62257. default:
  62258. break;
  62259. }
  62260. }
  62261. if (this._colorGradientsTexture) {
  62262. defines += "\n#define COLORGRADIENTS";
  62263. }
  62264. if (this.isAnimationSheetEnabled) {
  62265. defines += "\n#define ANIMATESHEET";
  62266. }
  62267. if (this._imageProcessingConfiguration) {
  62268. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  62269. defines += "\n" + this._imageProcessingConfigurationDefines.toString();
  62270. }
  62271. if (this._renderEffect && this._renderEffect.defines === defines) {
  62272. return;
  62273. }
  62274. var uniforms = ["view", "projection", "colorDead", "invView", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "sheetInfos", "translationPivot", "eyePosition"];
  62275. var samplers = ["textureSampler", "colorGradientSampler"];
  62276. if (BABYLON.ImageProcessingConfiguration) {
  62277. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._imageProcessingConfigurationDefines);
  62278. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  62279. }
  62280. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "initialDirection", "angle", "cellIndex"], uniforms, samplers, this._scene.getEngine(), defines);
  62281. };
  62282. /**
  62283. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  62284. * @param preWarm defines if we are in the pre-warmimg phase
  62285. */
  62286. GPUParticleSystem.prototype.animate = function (preWarm) {
  62287. if (preWarm === void 0) { preWarm = false; }
  62288. this._timeDelta = this.updateSpeed * (preWarm ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  62289. this._actualFrame += this._timeDelta;
  62290. if (!this._stopped) {
  62291. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  62292. this.stop();
  62293. }
  62294. }
  62295. };
  62296. GPUParticleSystem.prototype._createFactorGradientTexture = function (factorGradients, textureName) {
  62297. var texture = this[textureName];
  62298. if (!factorGradients || !factorGradients.length || texture) {
  62299. return;
  62300. }
  62301. var data = new Float32Array(this._rawTextureWidth);
  62302. for (var x = 0; x < this._rawTextureWidth; x++) {
  62303. var ratio = x / this._rawTextureWidth;
  62304. BABYLON.Tools.GetCurrentGradient(ratio, factorGradients, function (currentGradient, nextGradient, scale) {
  62305. data[x] = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  62306. });
  62307. }
  62308. this[textureName] = BABYLON.RawTexture.CreateRTexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  62309. };
  62310. GPUParticleSystem.prototype._createSizeGradientTexture = function () {
  62311. this._createFactorGradientTexture(this._sizeGradients, "_sizeGradientsTexture");
  62312. };
  62313. GPUParticleSystem.prototype._createAngularSpeedGradientTexture = function () {
  62314. this._createFactorGradientTexture(this._angularSpeedGradients, "_angularSpeedGradientsTexture");
  62315. };
  62316. GPUParticleSystem.prototype._createVelocityGradientTexture = function () {
  62317. this._createFactorGradientTexture(this._velocityGradients, "_velocityGradientsTexture");
  62318. };
  62319. GPUParticleSystem.prototype._createLimitVelocityGradientTexture = function () {
  62320. this._createFactorGradientTexture(this._limitVelocityGradients, "_limitVelocityGradientsTexture");
  62321. };
  62322. GPUParticleSystem.prototype._createDragGradientTexture = function () {
  62323. this._createFactorGradientTexture(this._dragGradients, "_dragGradientsTexture");
  62324. };
  62325. GPUParticleSystem.prototype._createColorGradientTexture = function () {
  62326. if (!this._colorGradients || !this._colorGradients.length || this._colorGradientsTexture) {
  62327. return;
  62328. }
  62329. var data = new Uint8Array(this._rawTextureWidth * 4);
  62330. var tmpColor = BABYLON.Tmp.Color4[0];
  62331. for (var x = 0; x < this._rawTextureWidth; x++) {
  62332. var ratio = x / this._rawTextureWidth;
  62333. BABYLON.Tools.GetCurrentGradient(ratio, this._colorGradients, function (currentGradient, nextGradient, scale) {
  62334. BABYLON.Color4.LerpToRef(currentGradient.color1, nextGradient.color1, scale, tmpColor);
  62335. data[x * 4] = tmpColor.r * 255;
  62336. data[x * 4 + 1] = tmpColor.g * 255;
  62337. data[x * 4 + 2] = tmpColor.b * 255;
  62338. data[x * 4 + 3] = tmpColor.a * 255;
  62339. });
  62340. }
  62341. this._colorGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  62342. };
  62343. /**
  62344. * Renders the particle system in its current state
  62345. * @param preWarm defines if the system should only update the particles but not render them
  62346. * @returns the current number of particles
  62347. */
  62348. GPUParticleSystem.prototype.render = function (preWarm) {
  62349. if (preWarm === void 0) { preWarm = false; }
  62350. if (!this._started) {
  62351. return 0;
  62352. }
  62353. this._createColorGradientTexture();
  62354. this._createSizeGradientTexture();
  62355. this._createAngularSpeedGradientTexture();
  62356. this._createVelocityGradientTexture();
  62357. this._createLimitVelocityGradientTexture();
  62358. this._createDragGradientTexture();
  62359. this._recreateUpdateEffect();
  62360. this._recreateRenderEffect();
  62361. if (!this.isReady()) {
  62362. return 0;
  62363. }
  62364. if (!preWarm) {
  62365. if (!this._preWarmDone && this.preWarmCycles) {
  62366. for (var index = 0; index < this.preWarmCycles; index++) {
  62367. this.animate(true);
  62368. this.render(true);
  62369. }
  62370. this._preWarmDone = true;
  62371. }
  62372. if (this._currentRenderId === this._scene.getRenderId()) {
  62373. return 0;
  62374. }
  62375. this._currentRenderId = this._scene.getRenderId();
  62376. }
  62377. // Get everything ready to render
  62378. this._initialize();
  62379. this._accumulatedCount += this.emitRate * this._timeDelta;
  62380. if (this._accumulatedCount > 1) {
  62381. var intPart = this._accumulatedCount | 0;
  62382. this._accumulatedCount -= intPart;
  62383. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + intPart);
  62384. }
  62385. if (!this._currentActiveCount) {
  62386. return 0;
  62387. }
  62388. // Enable update effect
  62389. this._engine.enableEffect(this._updateEffect);
  62390. this._engine.setState(false);
  62391. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  62392. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  62393. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  62394. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  62395. this._updateEffect.setTexture("randomSampler2", this._randomTexture2);
  62396. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  62397. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  62398. if (!this._colorGradientsTexture) {
  62399. this._updateEffect.setDirectColor4("color1", this.color1);
  62400. this._updateEffect.setDirectColor4("color2", this.color2);
  62401. }
  62402. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  62403. this._updateEffect.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
  62404. this._updateEffect.setFloat4("angleRange", this.minAngularSpeed, this.maxAngularSpeed, this.minInitialRotation, this.maxInitialRotation);
  62405. this._updateEffect.setVector3("gravity", this.gravity);
  62406. if (this._sizeGradientsTexture) {
  62407. this._updateEffect.setTexture("sizeGradientSampler", this._sizeGradientsTexture);
  62408. }
  62409. if (this._angularSpeedGradientsTexture) {
  62410. this._updateEffect.setTexture("angularSpeedGradientSampler", this._angularSpeedGradientsTexture);
  62411. }
  62412. if (this._velocityGradientsTexture) {
  62413. this._updateEffect.setTexture("velocityGradientSampler", this._velocityGradientsTexture);
  62414. }
  62415. if (this._limitVelocityGradientsTexture) {
  62416. this._updateEffect.setTexture("limitVelocityGradientSampler", this._limitVelocityGradientsTexture);
  62417. this._updateEffect.setFloat("limitVelocityDamping", this.limitVelocityDamping);
  62418. }
  62419. if (this._dragGradientsTexture) {
  62420. this._updateEffect.setTexture("dragGradientSampler", this._dragGradientsTexture);
  62421. }
  62422. if (this.particleEmitterType) {
  62423. this.particleEmitterType.applyToShader(this._updateEffect);
  62424. }
  62425. if (this._isAnimationSheetEnabled) {
  62426. this._updateEffect.setFloat3("cellInfos", this.startSpriteCellID, this.endSpriteCellID, this.spriteCellChangeSpeed);
  62427. }
  62428. if (this.noiseTexture) {
  62429. this._updateEffect.setTexture("noiseSampler", this.noiseTexture);
  62430. this._updateEffect.setVector3("noiseStrength", this.noiseStrength);
  62431. }
  62432. var emitterWM;
  62433. if (this.emitter.position) {
  62434. var emitterMesh = this.emitter;
  62435. emitterWM = emitterMesh.getWorldMatrix();
  62436. }
  62437. else {
  62438. var emitterPosition = this.emitter;
  62439. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  62440. }
  62441. this._updateEffect.setMatrix("emitterWM", emitterWM);
  62442. // Bind source VAO
  62443. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  62444. // Update
  62445. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  62446. this._engine.setRasterizerState(false);
  62447. this._engine.beginTransformFeedback(true);
  62448. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  62449. this._engine.endTransformFeedback();
  62450. this._engine.setRasterizerState(true);
  62451. this._engine.bindTransformFeedbackBuffer(null);
  62452. if (!preWarm) {
  62453. // Enable render effect
  62454. this._engine.enableEffect(this._renderEffect);
  62455. var viewMatrix = this._scene.getViewMatrix();
  62456. this._renderEffect.setMatrix("view", viewMatrix);
  62457. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  62458. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  62459. this._renderEffect.setVector2("translationPivot", this.translationPivot);
  62460. if (this._colorGradientsTexture) {
  62461. this._renderEffect.setTexture("colorGradientSampler", this._colorGradientsTexture);
  62462. }
  62463. else {
  62464. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  62465. }
  62466. if (this._isAnimationSheetEnabled && this.particleTexture) {
  62467. var baseSize = this.particleTexture.getBaseSize();
  62468. this._renderEffect.setFloat3("sheetInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  62469. }
  62470. if (this._isBillboardBased) {
  62471. var camera = this._scene.activeCamera;
  62472. this._renderEffect.setVector3("eyePosition", camera.globalPosition);
  62473. }
  62474. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  62475. var invView = viewMatrix.clone();
  62476. invView.invert();
  62477. this._renderEffect.setMatrix("invView", invView);
  62478. BABYLON.MaterialHelper.BindClipPlane(this._renderEffect, this._scene);
  62479. }
  62480. // image processing
  62481. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  62482. this._imageProcessingConfiguration.bind(this._renderEffect);
  62483. }
  62484. // Draw order
  62485. switch (this.blendMode) {
  62486. case BABYLON.ParticleSystem.BLENDMODE_ADD:
  62487. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  62488. break;
  62489. case BABYLON.ParticleSystem.BLENDMODE_ONEONE:
  62490. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  62491. break;
  62492. case BABYLON.ParticleSystem.BLENDMODE_STANDARD:
  62493. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  62494. break;
  62495. case BABYLON.ParticleSystem.BLENDMODE_MULTIPLY:
  62496. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_MULTIPLY);
  62497. break;
  62498. }
  62499. if (this.forceDepthWrite) {
  62500. this._engine.setDepthWrite(true);
  62501. }
  62502. // Bind source VAO
  62503. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  62504. // Render
  62505. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  62506. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  62507. }
  62508. // Switch VAOs
  62509. this._targetIndex++;
  62510. if (this._targetIndex === 2) {
  62511. this._targetIndex = 0;
  62512. }
  62513. // Switch buffers
  62514. var tmpBuffer = this._sourceBuffer;
  62515. this._sourceBuffer = this._targetBuffer;
  62516. this._targetBuffer = tmpBuffer;
  62517. return this._currentActiveCount;
  62518. };
  62519. /**
  62520. * Rebuilds the particle system
  62521. */
  62522. GPUParticleSystem.prototype.rebuild = function () {
  62523. this._initialize(true);
  62524. };
  62525. GPUParticleSystem.prototype._releaseBuffers = function () {
  62526. if (this._buffer0) {
  62527. this._buffer0.dispose();
  62528. this._buffer0 = null;
  62529. }
  62530. if (this._buffer1) {
  62531. this._buffer1.dispose();
  62532. this._buffer1 = null;
  62533. }
  62534. if (this._spriteBuffer) {
  62535. this._spriteBuffer.dispose();
  62536. this._spriteBuffer = null;
  62537. }
  62538. };
  62539. GPUParticleSystem.prototype._releaseVAOs = function () {
  62540. if (!this._updateVAO) {
  62541. return;
  62542. }
  62543. for (var index = 0; index < this._updateVAO.length; index++) {
  62544. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  62545. }
  62546. this._updateVAO = [];
  62547. for (var index = 0; index < this._renderVAO.length; index++) {
  62548. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  62549. }
  62550. this._renderVAO = [];
  62551. };
  62552. /**
  62553. * Disposes the particle system and free the associated resources
  62554. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  62555. */
  62556. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  62557. if (disposeTexture === void 0) { disposeTexture = true; }
  62558. var index = this._scene.particleSystems.indexOf(this);
  62559. if (index > -1) {
  62560. this._scene.particleSystems.splice(index, 1);
  62561. }
  62562. this._releaseBuffers();
  62563. this._releaseVAOs();
  62564. if (this._colorGradientsTexture) {
  62565. this._colorGradientsTexture.dispose();
  62566. this._colorGradientsTexture = null;
  62567. }
  62568. if (this._sizeGradientsTexture) {
  62569. this._sizeGradientsTexture.dispose();
  62570. this._sizeGradientsTexture = null;
  62571. }
  62572. if (this._angularSpeedGradientsTexture) {
  62573. this._angularSpeedGradientsTexture.dispose();
  62574. this._angularSpeedGradientsTexture = null;
  62575. }
  62576. if (this._velocityGradientsTexture) {
  62577. this._velocityGradientsTexture.dispose();
  62578. this._velocityGradientsTexture = null;
  62579. }
  62580. if (this._limitVelocityGradientsTexture) {
  62581. this._limitVelocityGradientsTexture.dispose();
  62582. this._limitVelocityGradientsTexture = null;
  62583. }
  62584. if (this._dragGradientsTexture) {
  62585. this._dragGradientsTexture.dispose();
  62586. this._dragGradientsTexture = null;
  62587. }
  62588. if (this._randomTexture) {
  62589. this._randomTexture.dispose();
  62590. this._randomTexture = null;
  62591. }
  62592. if (this._randomTexture2) {
  62593. this._randomTexture2.dispose();
  62594. this._randomTexture2 = null;
  62595. }
  62596. if (disposeTexture && this.particleTexture) {
  62597. this.particleTexture.dispose();
  62598. this.particleTexture = null;
  62599. }
  62600. if (disposeTexture && this.noiseTexture) {
  62601. this.noiseTexture.dispose();
  62602. this.noiseTexture = null;
  62603. }
  62604. // Callback
  62605. this.onDisposeObservable.notifyObservers(this);
  62606. this.onDisposeObservable.clear();
  62607. };
  62608. /**
  62609. * Clones the particle system.
  62610. * @param name The name of the cloned object
  62611. * @param newEmitter The new emitter to use
  62612. * @returns the cloned particle system
  62613. */
  62614. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  62615. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  62616. BABYLON.Tools.DeepCopy(this, result);
  62617. if (newEmitter === undefined) {
  62618. newEmitter = this.emitter;
  62619. }
  62620. result.emitter = newEmitter;
  62621. if (this.particleTexture) {
  62622. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  62623. }
  62624. return result;
  62625. };
  62626. /**
  62627. * Serializes the particle system to a JSON object.
  62628. * @returns the JSON object
  62629. */
  62630. GPUParticleSystem.prototype.serialize = function () {
  62631. var serializationObject = {};
  62632. BABYLON.ParticleSystem._Serialize(serializationObject, this);
  62633. serializationObject.activeParticleCount = this.activeParticleCount;
  62634. return serializationObject;
  62635. };
  62636. /**
  62637. * Parses a JSON object to create a GPU particle system.
  62638. * @param parsedParticleSystem The JSON object to parse
  62639. * @param scene The scene to create the particle system in
  62640. * @param rootUrl The root url to use to load external dependencies like texture
  62641. * @returns the parsed GPU particle system
  62642. */
  62643. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  62644. var name = parsedParticleSystem.name;
  62645. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  62646. if (parsedParticleSystem.activeParticleCount) {
  62647. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  62648. }
  62649. BABYLON.ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  62650. return particleSystem;
  62651. };
  62652. return GPUParticleSystem;
  62653. }(BABYLON.BaseParticleSystem));
  62654. BABYLON.GPUParticleSystem = GPUParticleSystem;
  62655. })(BABYLON || (BABYLON = {}));
  62656. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  62657. var BABYLON;
  62658. (function (BABYLON) {
  62659. /**
  62660. * Represents one particle of a solid particle system.
  62661. */
  62662. var SolidParticle = /** @class */ (function () {
  62663. /**
  62664. * Creates a Solid Particle object.
  62665. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  62666. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  62667. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  62668. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  62669. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  62670. * @param shapeId (integer) is the model shape identifier in the SPS.
  62671. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  62672. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  62673. */
  62674. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  62675. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  62676. /**
  62677. * particle global index
  62678. */
  62679. this.idx = 0;
  62680. /**
  62681. * The color of the particle
  62682. */
  62683. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  62684. /**
  62685. * The world space position of the particle.
  62686. */
  62687. this.position = BABYLON.Vector3.Zero();
  62688. /**
  62689. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  62690. */
  62691. this.rotation = BABYLON.Vector3.Zero();
  62692. /**
  62693. * The scaling of the particle.
  62694. */
  62695. this.scaling = BABYLON.Vector3.One();
  62696. /**
  62697. * The uvs of the particle.
  62698. */
  62699. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  62700. /**
  62701. * The current speed of the particle.
  62702. */
  62703. this.velocity = BABYLON.Vector3.Zero();
  62704. /**
  62705. * The pivot point in the particle local space.
  62706. */
  62707. this.pivot = BABYLON.Vector3.Zero();
  62708. /**
  62709. * Must the particle be translated from its pivot point in its local space ?
  62710. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  62711. * Default : false
  62712. */
  62713. this.translateFromPivot = false;
  62714. /**
  62715. * Is the particle active or not ?
  62716. */
  62717. this.alive = true;
  62718. /**
  62719. * Is the particle visible or not ?
  62720. */
  62721. this.isVisible = true;
  62722. /**
  62723. * Index of this particle in the global "positions" array (Internal use)
  62724. * @hidden
  62725. */
  62726. this._pos = 0;
  62727. /**
  62728. * @hidden Index of this particle in the global "indices" array (Internal use)
  62729. */
  62730. this._ind = 0;
  62731. /**
  62732. * ModelShape id of this particle
  62733. */
  62734. this.shapeId = 0;
  62735. /**
  62736. * Index of the particle in its shape id (Internal use)
  62737. */
  62738. this.idxInShape = 0;
  62739. /**
  62740. * @hidden Still set as invisible in order to skip useless computations (Internal use)
  62741. */
  62742. this._stillInvisible = false;
  62743. /**
  62744. * @hidden Last computed particle rotation matrix
  62745. */
  62746. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  62747. /**
  62748. * Parent particle Id, if any.
  62749. * Default null.
  62750. */
  62751. this.parentId = null;
  62752. /**
  62753. * @hidden Internal global position in the SPS.
  62754. */
  62755. this._globalPosition = BABYLON.Vector3.Zero();
  62756. this.idx = particleIndex;
  62757. this._pos = positionIndex;
  62758. this._ind = indiceIndex;
  62759. this._model = model;
  62760. this.shapeId = shapeId;
  62761. this.idxInShape = idxInShape;
  62762. this._sps = sps;
  62763. if (modelBoundingInfo) {
  62764. this._modelBoundingInfo = modelBoundingInfo;
  62765. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  62766. }
  62767. }
  62768. Object.defineProperty(SolidParticle.prototype, "scale", {
  62769. /**
  62770. * Legacy support, changed scale to scaling
  62771. */
  62772. get: function () {
  62773. return this.scaling;
  62774. },
  62775. /**
  62776. * Legacy support, changed scale to scaling
  62777. */
  62778. set: function (scale) {
  62779. this.scaling = scale;
  62780. },
  62781. enumerable: true,
  62782. configurable: true
  62783. });
  62784. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  62785. /**
  62786. * Legacy support, changed quaternion to rotationQuaternion
  62787. */
  62788. get: function () {
  62789. return this.rotationQuaternion;
  62790. },
  62791. /**
  62792. * Legacy support, changed quaternion to rotationQuaternion
  62793. */
  62794. set: function (q) {
  62795. this.rotationQuaternion = q;
  62796. },
  62797. enumerable: true,
  62798. configurable: true
  62799. });
  62800. /**
  62801. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  62802. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  62803. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  62804. * @returns true if it intersects
  62805. */
  62806. SolidParticle.prototype.intersectsMesh = function (target) {
  62807. if (!this._boundingInfo || !target._boundingInfo) {
  62808. return false;
  62809. }
  62810. if (this._sps._bSphereOnly) {
  62811. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  62812. }
  62813. return this._boundingInfo.intersects(target._boundingInfo, false);
  62814. };
  62815. return SolidParticle;
  62816. }());
  62817. BABYLON.SolidParticle = SolidParticle;
  62818. /**
  62819. * Represents the shape of the model used by one particle of a solid particle system.
  62820. * SPS internal tool, don't use it manually.
  62821. */
  62822. var ModelShape = /** @class */ (function () {
  62823. /**
  62824. * 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.
  62825. * SPS internal tool, don't use it manually.
  62826. * @hidden
  62827. */
  62828. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  62829. /**
  62830. * length of the shape in the model indices array (internal use)
  62831. * @hidden
  62832. */
  62833. this._indicesLength = 0;
  62834. this.shapeID = id;
  62835. this._shape = shape;
  62836. this._indicesLength = indicesLength;
  62837. this._shapeUV = shapeUV;
  62838. this._positionFunction = posFunction;
  62839. this._vertexFunction = vtxFunction;
  62840. }
  62841. return ModelShape;
  62842. }());
  62843. BABYLON.ModelShape = ModelShape;
  62844. /**
  62845. * Represents a Depth Sorted Particle in the solid particle system.
  62846. */
  62847. var DepthSortedParticle = /** @class */ (function () {
  62848. function DepthSortedParticle() {
  62849. /**
  62850. * Index of the particle in the "indices" array
  62851. */
  62852. this.ind = 0;
  62853. /**
  62854. * Length of the particle shape in the "indices" array
  62855. */
  62856. this.indicesLength = 0;
  62857. /**
  62858. * Squared distance from the particle to the camera
  62859. */
  62860. this.sqDistance = 0.0;
  62861. }
  62862. return DepthSortedParticle;
  62863. }());
  62864. BABYLON.DepthSortedParticle = DepthSortedParticle;
  62865. })(BABYLON || (BABYLON = {}));
  62866. //# sourceMappingURL=babylon.solidParticle.js.map
  62867. var BABYLON;
  62868. (function (BABYLON) {
  62869. /**
  62870. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  62871. *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.
  62872. * The SPS is also a particle system. It provides some methods to manage the particles.
  62873. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  62874. *
  62875. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  62876. */
  62877. var SolidParticleSystem = /** @class */ (function () {
  62878. /**
  62879. * Creates a SPS (Solid Particle System) object.
  62880. * @param name (String) is the SPS name, this will be the underlying mesh name.
  62881. * @param scene (Scene) is the scene in which the SPS is added.
  62882. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  62883. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  62884. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  62885. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  62886. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  62887. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  62888. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  62889. */
  62890. function SolidParticleSystem(name, scene, options) {
  62891. /**
  62892. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  62893. * Example : var p = SPS.particles[i];
  62894. */
  62895. this.particles = new Array();
  62896. /**
  62897. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  62898. */
  62899. this.nbParticles = 0;
  62900. /**
  62901. * If the particles must ever face the camera (default false). Useful for planar particles.
  62902. */
  62903. this.billboard = false;
  62904. /**
  62905. * Recompute normals when adding a shape
  62906. */
  62907. this.recomputeNormals = true;
  62908. /**
  62909. * This a counter ofr your own usage. It's not set by any SPS functions.
  62910. */
  62911. this.counter = 0;
  62912. /**
  62913. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  62914. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  62915. */
  62916. this.vars = {};
  62917. /**
  62918. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  62919. * @hidden
  62920. */
  62921. this._bSphereOnly = false;
  62922. /**
  62923. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  62924. * @hidden
  62925. */
  62926. this._bSphereRadiusFactor = 1.0;
  62927. this._positions = new Array();
  62928. this._indices = new Array();
  62929. this._normals = new Array();
  62930. this._colors = new Array();
  62931. this._uvs = new Array();
  62932. this._index = 0; // indices index
  62933. this._updatable = true;
  62934. this._pickable = false;
  62935. this._isVisibilityBoxLocked = false;
  62936. this._alwaysVisible = false;
  62937. this._depthSort = false;
  62938. this._shapeCounter = 0;
  62939. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  62940. this._color = new BABYLON.Color4(0, 0, 0, 0);
  62941. this._computeParticleColor = true;
  62942. this._computeParticleTexture = true;
  62943. this._computeParticleRotation = true;
  62944. this._computeParticleVertex = false;
  62945. this._computeBoundingBox = false;
  62946. this._depthSortParticles = true;
  62947. this._cam_axisZ = BABYLON.Vector3.Zero();
  62948. this._cam_axisY = BABYLON.Vector3.Zero();
  62949. this._cam_axisX = BABYLON.Vector3.Zero();
  62950. this._axisZ = BABYLON.Axis.Z;
  62951. this._camDir = BABYLON.Vector3.Zero();
  62952. this._camInvertedPosition = BABYLON.Vector3.Zero();
  62953. this._rotMatrix = new BABYLON.Matrix();
  62954. this._invertMatrix = new BABYLON.Matrix();
  62955. this._rotated = BABYLON.Vector3.Zero();
  62956. this._quaternion = new BABYLON.Quaternion();
  62957. this._vertex = BABYLON.Vector3.Zero();
  62958. this._normal = BABYLON.Vector3.Zero();
  62959. this._yaw = 0.0;
  62960. this._pitch = 0.0;
  62961. this._roll = 0.0;
  62962. this._halfroll = 0.0;
  62963. this._halfpitch = 0.0;
  62964. this._halfyaw = 0.0;
  62965. this._sinRoll = 0.0;
  62966. this._cosRoll = 0.0;
  62967. this._sinPitch = 0.0;
  62968. this._cosPitch = 0.0;
  62969. this._sinYaw = 0.0;
  62970. this._cosYaw = 0.0;
  62971. this._mustUnrotateFixedNormals = false;
  62972. this._minimum = BABYLON.Vector3.Zero();
  62973. this._maximum = BABYLON.Vector3.Zero();
  62974. this._minBbox = BABYLON.Vector3.Zero();
  62975. this._maxBbox = BABYLON.Vector3.Zero();
  62976. this._particlesIntersect = false;
  62977. this._depthSortFunction = function (p1, p2) {
  62978. return (p2.sqDistance - p1.sqDistance);
  62979. };
  62980. this._needs32Bits = false;
  62981. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  62982. this._scaledPivot = BABYLON.Vector3.Zero();
  62983. this._particleHasParent = false;
  62984. this.name = name;
  62985. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  62986. this._camera = scene.activeCamera;
  62987. this._pickable = options ? options.isPickable : false;
  62988. this._depthSort = options ? options.enableDepthSort : false;
  62989. this._particlesIntersect = options ? options.particleIntersection : false;
  62990. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  62991. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  62992. if (options && options.updatable !== undefined) {
  62993. this._updatable = options.updatable;
  62994. }
  62995. else {
  62996. this._updatable = true;
  62997. }
  62998. if (this._pickable) {
  62999. this.pickedParticles = [];
  63000. }
  63001. if (this._depthSort) {
  63002. this.depthSortedParticles = [];
  63003. }
  63004. }
  63005. /**
  63006. * Builds the SPS underlying mesh. Returns a standard Mesh.
  63007. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  63008. * @returns the created mesh
  63009. */
  63010. SolidParticleSystem.prototype.buildMesh = function () {
  63011. if (this.nbParticles === 0) {
  63012. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  63013. this.addShape(triangle, 1);
  63014. triangle.dispose();
  63015. }
  63016. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  63017. this._positions32 = new Float32Array(this._positions);
  63018. this._uvs32 = new Float32Array(this._uvs);
  63019. this._colors32 = new Float32Array(this._colors);
  63020. if (this.recomputeNormals) {
  63021. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  63022. }
  63023. this._normals32 = new Float32Array(this._normals);
  63024. this._fixedNormal32 = new Float32Array(this._normals);
  63025. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  63026. this._unrotateFixedNormals();
  63027. }
  63028. var vertexData = new BABYLON.VertexData();
  63029. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  63030. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  63031. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  63032. if (this._uvs32.length > 0) {
  63033. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  63034. }
  63035. if (this._colors32.length > 0) {
  63036. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  63037. }
  63038. var mesh = new BABYLON.Mesh(this.name, this._scene);
  63039. vertexData.applyToMesh(mesh, this._updatable);
  63040. this.mesh = mesh;
  63041. this.mesh.isPickable = this._pickable;
  63042. // free memory
  63043. if (!this._depthSort) {
  63044. this._indices = null;
  63045. }
  63046. this._positions = null;
  63047. this._normals = null;
  63048. this._uvs = null;
  63049. this._colors = null;
  63050. if (!this._updatable) {
  63051. this.particles.length = 0;
  63052. }
  63053. return mesh;
  63054. };
  63055. /**
  63056. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  63057. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  63058. * Thus the particles generated from `digest()` have their property `position` set yet.
  63059. * @param mesh ( Mesh ) is the mesh to be digested
  63060. * @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
  63061. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  63062. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  63063. * @returns the current SPS
  63064. */
  63065. SolidParticleSystem.prototype.digest = function (mesh, options) {
  63066. var size = (options && options.facetNb) || 1;
  63067. var number = (options && options.number) || 0;
  63068. var delta = (options && options.delta) || 0;
  63069. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  63070. var meshInd = mesh.getIndices();
  63071. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  63072. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  63073. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  63074. var f = 0; // facet counter
  63075. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  63076. // compute size from number
  63077. if (number) {
  63078. number = (number > totalFacets) ? totalFacets : number;
  63079. size = Math.round(totalFacets / number);
  63080. delta = 0;
  63081. }
  63082. else {
  63083. size = (size > totalFacets) ? totalFacets : size;
  63084. }
  63085. var facetPos = []; // submesh positions
  63086. var facetInd = []; // submesh indices
  63087. var facetUV = []; // submesh UV
  63088. var facetCol = []; // submesh colors
  63089. var barycenter = BABYLON.Vector3.Zero();
  63090. var sizeO = size;
  63091. while (f < totalFacets) {
  63092. size = sizeO + Math.floor((1 + delta) * Math.random());
  63093. if (f > totalFacets - size) {
  63094. size = totalFacets - f;
  63095. }
  63096. // reset temp arrays
  63097. facetPos.length = 0;
  63098. facetInd.length = 0;
  63099. facetUV.length = 0;
  63100. facetCol.length = 0;
  63101. // iterate over "size" facets
  63102. var fi = 0;
  63103. for (var j = f * 3; j < (f + size) * 3; j++) {
  63104. facetInd.push(fi);
  63105. var i = meshInd[j];
  63106. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  63107. if (meshUV) {
  63108. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  63109. }
  63110. if (meshCol) {
  63111. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  63112. }
  63113. fi++;
  63114. }
  63115. // create a model shape for each single particle
  63116. var idx = this.nbParticles;
  63117. var shape = this._posToShape(facetPos);
  63118. var shapeUV = this._uvsToShapeUV(facetUV);
  63119. // compute the barycenter of the shape
  63120. var v;
  63121. for (v = 0; v < shape.length; v++) {
  63122. barycenter.addInPlace(shape[v]);
  63123. }
  63124. barycenter.scaleInPlace(1 / shape.length);
  63125. // shift the shape from its barycenter to the origin
  63126. for (v = 0; v < shape.length; v++) {
  63127. shape[v].subtractInPlace(barycenter);
  63128. }
  63129. var bInfo;
  63130. if (this._particlesIntersect) {
  63131. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  63132. }
  63133. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  63134. // add the particle in the SPS
  63135. var currentPos = this._positions.length;
  63136. var currentInd = this._indices.length;
  63137. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  63138. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  63139. // initialize the particle position
  63140. this.particles[this.nbParticles].position.addInPlace(barycenter);
  63141. this._index += shape.length;
  63142. idx++;
  63143. this.nbParticles++;
  63144. this._shapeCounter++;
  63145. f += size;
  63146. }
  63147. return this;
  63148. };
  63149. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  63150. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  63151. var index = 0;
  63152. var idx = 0;
  63153. for (var p = 0; p < this.particles.length; p++) {
  63154. this._particle = this.particles[p];
  63155. this._shape = this._particle._model._shape;
  63156. if (this._particle.rotationQuaternion) {
  63157. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  63158. }
  63159. else {
  63160. this._yaw = this._particle.rotation.y;
  63161. this._pitch = this._particle.rotation.x;
  63162. this._roll = this._particle.rotation.z;
  63163. this._quaternionRotationYPR();
  63164. }
  63165. this._quaternionToRotationMatrix();
  63166. this._rotMatrix.invertToRef(this._invertMatrix);
  63167. for (var pt = 0; pt < this._shape.length; pt++) {
  63168. idx = index + pt * 3;
  63169. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  63170. this._fixedNormal32[idx] = this._normal.x;
  63171. this._fixedNormal32[idx + 1] = this._normal.y;
  63172. this._fixedNormal32[idx + 2] = this._normal.z;
  63173. }
  63174. index = idx + 3;
  63175. }
  63176. };
  63177. //reset copy
  63178. SolidParticleSystem.prototype._resetCopy = function () {
  63179. this._copy.position.x = 0;
  63180. this._copy.position.y = 0;
  63181. this._copy.position.z = 0;
  63182. this._copy.rotation.x = 0;
  63183. this._copy.rotation.y = 0;
  63184. this._copy.rotation.z = 0;
  63185. this._copy.rotationQuaternion = null;
  63186. this._copy.scaling.x = 1.0;
  63187. this._copy.scaling.y = 1.0;
  63188. this._copy.scaling.z = 1.0;
  63189. this._copy.uvs.x = 0;
  63190. this._copy.uvs.y = 0;
  63191. this._copy.uvs.z = 1.0;
  63192. this._copy.uvs.w = 1.0;
  63193. this._copy.color = null;
  63194. this._copy.translateFromPivot = false;
  63195. };
  63196. // _meshBuilder : inserts the shape model in the global SPS mesh
  63197. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  63198. var i;
  63199. var u = 0;
  63200. var c = 0;
  63201. var n = 0;
  63202. this._resetCopy();
  63203. if (options && options.positionFunction) { // call to custom positionFunction
  63204. options.positionFunction(this._copy, idx, idxInShape);
  63205. this._mustUnrotateFixedNormals = true;
  63206. }
  63207. if (this._copy.rotationQuaternion) {
  63208. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  63209. }
  63210. else {
  63211. this._yaw = this._copy.rotation.y;
  63212. this._pitch = this._copy.rotation.x;
  63213. this._roll = this._copy.rotation.z;
  63214. this._quaternionRotationYPR();
  63215. }
  63216. this._quaternionToRotationMatrix();
  63217. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  63218. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  63219. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  63220. if (this._copy.translateFromPivot) {
  63221. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  63222. }
  63223. else {
  63224. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  63225. }
  63226. for (i = 0; i < shape.length; i++) {
  63227. this._vertex.x = shape[i].x;
  63228. this._vertex.y = shape[i].y;
  63229. this._vertex.z = shape[i].z;
  63230. if (options && options.vertexFunction) {
  63231. options.vertexFunction(this._copy, this._vertex, i);
  63232. }
  63233. this._vertex.x *= this._copy.scaling.x;
  63234. this._vertex.y *= this._copy.scaling.y;
  63235. this._vertex.z *= this._copy.scaling.z;
  63236. this._vertex.x -= this._scaledPivot.x;
  63237. this._vertex.y -= this._scaledPivot.y;
  63238. this._vertex.z -= this._scaledPivot.z;
  63239. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  63240. this._rotated.addInPlace(this._pivotBackTranslation);
  63241. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  63242. if (meshUV) {
  63243. 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);
  63244. u += 2;
  63245. }
  63246. if (this._copy.color) {
  63247. this._color = this._copy.color;
  63248. }
  63249. else if (meshCol && meshCol[c] !== undefined) {
  63250. this._color.r = meshCol[c];
  63251. this._color.g = meshCol[c + 1];
  63252. this._color.b = meshCol[c + 2];
  63253. this._color.a = meshCol[c + 3];
  63254. }
  63255. else {
  63256. this._color.r = 1.0;
  63257. this._color.g = 1.0;
  63258. this._color.b = 1.0;
  63259. this._color.a = 1.0;
  63260. }
  63261. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  63262. c += 4;
  63263. if (!this.recomputeNormals && meshNor) {
  63264. this._normal.x = meshNor[n];
  63265. this._normal.y = meshNor[n + 1];
  63266. this._normal.z = meshNor[n + 2];
  63267. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  63268. normals.push(this._normal.x, this._normal.y, this._normal.z);
  63269. n += 3;
  63270. }
  63271. }
  63272. for (i = 0; i < meshInd.length; i++) {
  63273. var current_ind = p + meshInd[i];
  63274. indices.push(current_ind);
  63275. if (current_ind > 65535) {
  63276. this._needs32Bits = true;
  63277. }
  63278. }
  63279. if (this._pickable) {
  63280. var nbfaces = meshInd.length / 3;
  63281. for (i = 0; i < nbfaces; i++) {
  63282. this.pickedParticles.push({ idx: idx, faceId: i });
  63283. }
  63284. }
  63285. if (this._depthSort) {
  63286. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  63287. }
  63288. return this._copy;
  63289. };
  63290. // returns a shape array from positions array
  63291. SolidParticleSystem.prototype._posToShape = function (positions) {
  63292. var shape = [];
  63293. for (var i = 0; i < positions.length; i += 3) {
  63294. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  63295. }
  63296. return shape;
  63297. };
  63298. // returns a shapeUV array from a Vector4 uvs
  63299. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  63300. var shapeUV = [];
  63301. if (uvs) {
  63302. for (var i = 0; i < uvs.length; i++)
  63303. shapeUV.push(uvs[i]);
  63304. }
  63305. return shapeUV;
  63306. };
  63307. // adds a new particle object in the particles array
  63308. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  63309. if (bInfo === void 0) { bInfo = null; }
  63310. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  63311. this.particles.push(sp);
  63312. return sp;
  63313. };
  63314. /**
  63315. * Adds some particles to the SPS from the model shape. Returns the shape id.
  63316. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  63317. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  63318. * @param nb (positive integer) the number of particles to be created from this model
  63319. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  63320. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  63321. * @returns the number of shapes in the system
  63322. */
  63323. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  63324. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  63325. var meshInd = mesh.getIndices();
  63326. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  63327. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  63328. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  63329. var bbInfo;
  63330. if (this._particlesIntersect) {
  63331. bbInfo = mesh.getBoundingInfo();
  63332. }
  63333. var shape = this._posToShape(meshPos);
  63334. var shapeUV = this._uvsToShapeUV(meshUV);
  63335. var posfunc = options ? options.positionFunction : null;
  63336. var vtxfunc = options ? options.vertexFunction : null;
  63337. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  63338. // particles
  63339. var sp;
  63340. var currentCopy;
  63341. var idx = this.nbParticles;
  63342. for (var i = 0; i < nb; i++) {
  63343. var currentPos = this._positions.length;
  63344. var currentInd = this._indices.length;
  63345. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  63346. if (this._updatable) {
  63347. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  63348. sp.position.copyFrom(currentCopy.position);
  63349. sp.rotation.copyFrom(currentCopy.rotation);
  63350. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  63351. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  63352. }
  63353. if (currentCopy.color && sp.color) {
  63354. sp.color.copyFrom(currentCopy.color);
  63355. }
  63356. sp.scaling.copyFrom(currentCopy.scaling);
  63357. sp.uvs.copyFrom(currentCopy.uvs);
  63358. }
  63359. this._index += shape.length;
  63360. idx++;
  63361. }
  63362. this.nbParticles += nb;
  63363. this._shapeCounter++;
  63364. return this._shapeCounter - 1;
  63365. };
  63366. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  63367. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  63368. this._resetCopy();
  63369. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  63370. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  63371. }
  63372. if (this._copy.rotationQuaternion) {
  63373. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  63374. }
  63375. else {
  63376. this._yaw = this._copy.rotation.y;
  63377. this._pitch = this._copy.rotation.x;
  63378. this._roll = this._copy.rotation.z;
  63379. this._quaternionRotationYPR();
  63380. }
  63381. this._quaternionToRotationMatrix();
  63382. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  63383. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  63384. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  63385. if (this._copy.translateFromPivot) {
  63386. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  63387. }
  63388. else {
  63389. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  63390. }
  63391. this._shape = particle._model._shape;
  63392. for (var pt = 0; pt < this._shape.length; pt++) {
  63393. this._vertex.x = this._shape[pt].x;
  63394. this._vertex.y = this._shape[pt].y;
  63395. this._vertex.z = this._shape[pt].z;
  63396. if (particle._model._vertexFunction) {
  63397. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  63398. }
  63399. this._vertex.x *= this._copy.scaling.x;
  63400. this._vertex.y *= this._copy.scaling.y;
  63401. this._vertex.z *= this._copy.scaling.z;
  63402. this._vertex.x -= this._scaledPivot.x;
  63403. this._vertex.y -= this._scaledPivot.y;
  63404. this._vertex.z -= this._scaledPivot.z;
  63405. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  63406. this._rotated.addInPlace(this._pivotBackTranslation);
  63407. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  63408. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  63409. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  63410. }
  63411. particle.position.x = 0.0;
  63412. particle.position.y = 0.0;
  63413. particle.position.z = 0.0;
  63414. particle.rotation.x = 0.0;
  63415. particle.rotation.y = 0.0;
  63416. particle.rotation.z = 0.0;
  63417. particle.rotationQuaternion = null;
  63418. particle.scaling.x = 1.0;
  63419. particle.scaling.y = 1.0;
  63420. particle.scaling.z = 1.0;
  63421. particle.uvs.x = 0.0;
  63422. particle.uvs.y = 0.0;
  63423. particle.uvs.z = 1.0;
  63424. particle.uvs.w = 1.0;
  63425. particle.pivot.x = 0.0;
  63426. particle.pivot.y = 0.0;
  63427. particle.pivot.z = 0.0;
  63428. particle.translateFromPivot = false;
  63429. particle.parentId = null;
  63430. };
  63431. /**
  63432. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  63433. * @returns the SPS.
  63434. */
  63435. SolidParticleSystem.prototype.rebuildMesh = function () {
  63436. for (var p = 0; p < this.particles.length; p++) {
  63437. this._rebuildParticle(this.particles[p]);
  63438. }
  63439. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  63440. return this;
  63441. };
  63442. /**
  63443. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  63444. * This method calls `updateParticle()` for each particle of the SPS.
  63445. * For an animated SPS, it is usually called within the render loop.
  63446. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  63447. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  63448. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  63449. * @returns the SPS.
  63450. */
  63451. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  63452. if (start === void 0) { start = 0; }
  63453. if (end === void 0) { end = this.nbParticles - 1; }
  63454. if (update === void 0) { update = true; }
  63455. if (!this._updatable) {
  63456. return this;
  63457. }
  63458. // custom beforeUpdate
  63459. this.beforeUpdateParticles(start, end, update);
  63460. this._cam_axisX.x = 1.0;
  63461. this._cam_axisX.y = 0.0;
  63462. this._cam_axisX.z = 0.0;
  63463. this._cam_axisY.x = 0.0;
  63464. this._cam_axisY.y = 1.0;
  63465. this._cam_axisY.z = 0.0;
  63466. this._cam_axisZ.x = 0.0;
  63467. this._cam_axisZ.y = 0.0;
  63468. this._cam_axisZ.z = 1.0;
  63469. // cases when the World Matrix is to be computed first
  63470. if (this.billboard || this._depthSort) {
  63471. this.mesh.computeWorldMatrix(true);
  63472. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  63473. }
  63474. // if the particles will always face the camera
  63475. if (this.billboard) {
  63476. // compute the camera position and un-rotate it by the current mesh rotation
  63477. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  63478. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  63479. this._cam_axisZ.normalize();
  63480. // same for camera up vector extracted from the cam view matrix
  63481. var view = this._camera.getViewMatrix(true);
  63482. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  63483. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  63484. this._cam_axisY.normalize();
  63485. this._cam_axisX.normalize();
  63486. }
  63487. // if depthSort, compute the camera global position in the mesh local system
  63488. if (this._depthSort) {
  63489. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  63490. }
  63491. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  63492. var idx = 0; // current position index in the global array positions32
  63493. var index = 0; // position start index in the global array positions32 of the current particle
  63494. var colidx = 0; // current color index in the global array colors32
  63495. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  63496. var uvidx = 0; // current uv index in the global array uvs32
  63497. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  63498. var pt = 0; // current index in the particle model shape
  63499. if (this.mesh.isFacetDataEnabled) {
  63500. this._computeBoundingBox = true;
  63501. }
  63502. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  63503. if (this._computeBoundingBox) {
  63504. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  63505. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  63506. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  63507. }
  63508. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  63509. if (this.mesh._boundingInfo) {
  63510. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  63511. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  63512. }
  63513. }
  63514. }
  63515. // particle loop
  63516. index = this.particles[start]._pos;
  63517. var vpos = (index / 3) | 0;
  63518. colorIndex = vpos * 4;
  63519. uvIndex = vpos * 2;
  63520. for (var p = start; p <= end; p++) {
  63521. this._particle = this.particles[p];
  63522. this._shape = this._particle._model._shape;
  63523. this._shapeUV = this._particle._model._shapeUV;
  63524. // call to custom user function to update the particle properties
  63525. this.updateParticle(this._particle);
  63526. // camera-particle distance for depth sorting
  63527. if (this._depthSort && this._depthSortParticles) {
  63528. var dsp = this.depthSortedParticles[p];
  63529. dsp.ind = this._particle._ind;
  63530. dsp.indicesLength = this._particle._model._indicesLength;
  63531. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  63532. }
  63533. // skip the computations for inactive or already invisible particles
  63534. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  63535. // increment indexes for the next particle
  63536. pt = this._shape.length;
  63537. index += pt * 3;
  63538. colorIndex += pt * 4;
  63539. uvIndex += pt * 2;
  63540. continue;
  63541. }
  63542. if (this._particle.isVisible) {
  63543. this._particle._stillInvisible = false; // un-mark permanent invisibility
  63544. this._particleHasParent = (this._particle.parentId !== null);
  63545. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  63546. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  63547. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  63548. // particle rotation matrix
  63549. if (this.billboard) {
  63550. this._particle.rotation.x = 0.0;
  63551. this._particle.rotation.y = 0.0;
  63552. }
  63553. if (this._computeParticleRotation || this.billboard) {
  63554. if (this._particle.rotationQuaternion) {
  63555. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  63556. }
  63557. else {
  63558. this._yaw = this._particle.rotation.y;
  63559. this._pitch = this._particle.rotation.x;
  63560. this._roll = this._particle.rotation.z;
  63561. this._quaternionRotationYPR();
  63562. }
  63563. this._quaternionToRotationMatrix();
  63564. }
  63565. if (this._particleHasParent) {
  63566. this._parent = this.particles[this._particle.parentId];
  63567. 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];
  63568. 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];
  63569. 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];
  63570. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  63571. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  63572. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  63573. if (this._computeParticleRotation || this.billboard) {
  63574. 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];
  63575. 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];
  63576. 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];
  63577. 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];
  63578. 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];
  63579. 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];
  63580. 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];
  63581. 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];
  63582. 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];
  63583. }
  63584. }
  63585. else {
  63586. this._particle._globalPosition.x = this._particle.position.x;
  63587. this._particle._globalPosition.y = this._particle.position.y;
  63588. this._particle._globalPosition.z = this._particle.position.z;
  63589. if (this._computeParticleRotation || this.billboard) {
  63590. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  63591. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  63592. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  63593. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  63594. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  63595. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  63596. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  63597. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  63598. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  63599. }
  63600. }
  63601. if (this._particle.translateFromPivot) {
  63602. this._pivotBackTranslation.x = 0.0;
  63603. this._pivotBackTranslation.y = 0.0;
  63604. this._pivotBackTranslation.z = 0.0;
  63605. }
  63606. else {
  63607. this._pivotBackTranslation.x = this._scaledPivot.x;
  63608. this._pivotBackTranslation.y = this._scaledPivot.y;
  63609. this._pivotBackTranslation.z = this._scaledPivot.z;
  63610. }
  63611. // particle vertex loop
  63612. for (pt = 0; pt < this._shape.length; pt++) {
  63613. idx = index + pt * 3;
  63614. colidx = colorIndex + pt * 4;
  63615. uvidx = uvIndex + pt * 2;
  63616. this._vertex.x = this._shape[pt].x;
  63617. this._vertex.y = this._shape[pt].y;
  63618. this._vertex.z = this._shape[pt].z;
  63619. if (this._computeParticleVertex) {
  63620. this.updateParticleVertex(this._particle, this._vertex, pt);
  63621. }
  63622. // positions
  63623. this._vertex.x *= this._particle.scaling.x;
  63624. this._vertex.y *= this._particle.scaling.y;
  63625. this._vertex.z *= this._particle.scaling.z;
  63626. this._vertex.x -= this._scaledPivot.x;
  63627. this._vertex.y -= this._scaledPivot.y;
  63628. this._vertex.z -= this._scaledPivot.z;
  63629. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  63630. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  63631. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  63632. this._rotated.x += this._pivotBackTranslation.x;
  63633. this._rotated.y += this._pivotBackTranslation.y;
  63634. this._rotated.z += this._pivotBackTranslation.z;
  63635. 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;
  63636. 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;
  63637. 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;
  63638. if (this._computeBoundingBox) {
  63639. if (this._positions32[idx] < this._minimum.x) {
  63640. this._minimum.x = this._positions32[idx];
  63641. }
  63642. if (this._positions32[idx] > this._maximum.x) {
  63643. this._maximum.x = this._positions32[idx];
  63644. }
  63645. if (this._positions32[idx + 1] < this._minimum.y) {
  63646. this._minimum.y = this._positions32[idx + 1];
  63647. }
  63648. if (this._positions32[idx + 1] > this._maximum.y) {
  63649. this._maximum.y = this._positions32[idx + 1];
  63650. }
  63651. if (this._positions32[idx + 2] < this._minimum.z) {
  63652. this._minimum.z = this._positions32[idx + 2];
  63653. }
  63654. if (this._positions32[idx + 2] > this._maximum.z) {
  63655. this._maximum.z = this._positions32[idx + 2];
  63656. }
  63657. }
  63658. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  63659. if (!this._computeParticleVertex) {
  63660. this._normal.x = this._fixedNormal32[idx];
  63661. this._normal.y = this._fixedNormal32[idx + 1];
  63662. this._normal.z = this._fixedNormal32[idx + 2];
  63663. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  63664. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  63665. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  63666. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  63667. 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;
  63668. 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;
  63669. }
  63670. if (this._computeParticleColor && this._particle.color) {
  63671. this._colors32[colidx] = this._particle.color.r;
  63672. this._colors32[colidx + 1] = this._particle.color.g;
  63673. this._colors32[colidx + 2] = this._particle.color.b;
  63674. this._colors32[colidx + 3] = this._particle.color.a;
  63675. }
  63676. if (this._computeParticleTexture) {
  63677. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  63678. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  63679. }
  63680. }
  63681. }
  63682. // particle just set invisible : scaled to zero and positioned at the origin
  63683. else {
  63684. this._particle._stillInvisible = true; // mark the particle as invisible
  63685. for (pt = 0; pt < this._shape.length; pt++) {
  63686. idx = index + pt * 3;
  63687. colidx = colorIndex + pt * 4;
  63688. uvidx = uvIndex + pt * 2;
  63689. this._positions32[idx] = 0.0;
  63690. this._positions32[idx + 1] = 0.0;
  63691. this._positions32[idx + 2] = 0.0;
  63692. this._normals32[idx] = 0.0;
  63693. this._normals32[idx + 1] = 0.0;
  63694. this._normals32[idx + 2] = 0.0;
  63695. if (this._computeParticleColor && this._particle.color) {
  63696. this._colors32[colidx] = this._particle.color.r;
  63697. this._colors32[colidx + 1] = this._particle.color.g;
  63698. this._colors32[colidx + 2] = this._particle.color.b;
  63699. this._colors32[colidx + 3] = this._particle.color.a;
  63700. }
  63701. if (this._computeParticleTexture) {
  63702. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  63703. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  63704. }
  63705. }
  63706. }
  63707. // if the particle intersections must be computed : update the bbInfo
  63708. if (this._particlesIntersect) {
  63709. var bInfo = this._particle._boundingInfo;
  63710. var bBox = bInfo.boundingBox;
  63711. var bSphere = bInfo.boundingSphere;
  63712. if (!this._bSphereOnly) {
  63713. // place, scale and rotate the particle bbox within the SPS local system, then update it
  63714. for (var b = 0; b < bBox.vectors.length; b++) {
  63715. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  63716. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  63717. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  63718. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  63719. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  63720. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  63721. 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;
  63722. 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;
  63723. 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;
  63724. }
  63725. bBox._update(this.mesh._worldMatrix);
  63726. }
  63727. // place and scale the particle bouding sphere in the SPS local system, then update it
  63728. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  63729. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  63730. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  63731. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  63732. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  63733. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  63734. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  63735. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  63736. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  63737. 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));
  63738. bSphere._update(this.mesh._worldMatrix);
  63739. }
  63740. // increment indexes for the next particle
  63741. index = idx + 3;
  63742. colorIndex = colidx + 4;
  63743. uvIndex = uvidx + 2;
  63744. }
  63745. // if the VBO must be updated
  63746. if (update) {
  63747. if (this._computeParticleColor) {
  63748. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  63749. }
  63750. if (this._computeParticleTexture) {
  63751. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  63752. }
  63753. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  63754. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  63755. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  63756. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  63757. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  63758. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  63759. for (var i = 0; i < this._normals32.length; i++) {
  63760. this._fixedNormal32[i] = this._normals32[i];
  63761. }
  63762. }
  63763. if (!this.mesh.areNormalsFrozen) {
  63764. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  63765. }
  63766. }
  63767. if (this._depthSort && this._depthSortParticles) {
  63768. this.depthSortedParticles.sort(this._depthSortFunction);
  63769. var dspl = this.depthSortedParticles.length;
  63770. var sorted = 0;
  63771. var lind = 0;
  63772. var sind = 0;
  63773. var sid = 0;
  63774. for (sorted = 0; sorted < dspl; sorted++) {
  63775. lind = this.depthSortedParticles[sorted].indicesLength;
  63776. sind = this.depthSortedParticles[sorted].ind;
  63777. for (var i = 0; i < lind; i++) {
  63778. this._indices32[sid] = this._indices[sind + i];
  63779. sid++;
  63780. }
  63781. }
  63782. this.mesh.updateIndices(this._indices32);
  63783. }
  63784. }
  63785. if (this._computeBoundingBox) {
  63786. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  63787. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  63788. }
  63789. this.afterUpdateParticles(start, end, update);
  63790. return this;
  63791. };
  63792. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  63793. this._halfroll = this._roll * 0.5;
  63794. this._halfpitch = this._pitch * 0.5;
  63795. this._halfyaw = this._yaw * 0.5;
  63796. this._sinRoll = Math.sin(this._halfroll);
  63797. this._cosRoll = Math.cos(this._halfroll);
  63798. this._sinPitch = Math.sin(this._halfpitch);
  63799. this._cosPitch = Math.cos(this._halfpitch);
  63800. this._sinYaw = Math.sin(this._halfyaw);
  63801. this._cosYaw = Math.cos(this._halfyaw);
  63802. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  63803. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  63804. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  63805. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  63806. };
  63807. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  63808. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  63809. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  63810. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  63811. this._rotMatrix.m[3] = 0;
  63812. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  63813. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  63814. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  63815. this._rotMatrix.m[7] = 0;
  63816. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  63817. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  63818. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  63819. this._rotMatrix.m[11] = 0;
  63820. this._rotMatrix.m[12] = 0;
  63821. this._rotMatrix.m[13] = 0;
  63822. this._rotMatrix.m[14] = 0;
  63823. this._rotMatrix.m[15] = 1.0;
  63824. };
  63825. /**
  63826. * Disposes the SPS.
  63827. */
  63828. SolidParticleSystem.prototype.dispose = function () {
  63829. this.mesh.dispose();
  63830. this.vars = null;
  63831. // drop references to internal big arrays for the GC
  63832. this._positions = null;
  63833. this._indices = null;
  63834. this._normals = null;
  63835. this._uvs = null;
  63836. this._colors = null;
  63837. this._indices32 = null;
  63838. this._positions32 = null;
  63839. this._normals32 = null;
  63840. this._fixedNormal32 = null;
  63841. this._uvs32 = null;
  63842. this._colors32 = null;
  63843. this.pickedParticles = null;
  63844. };
  63845. /**
  63846. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  63847. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  63848. * @returns the SPS.
  63849. */
  63850. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  63851. if (!this._isVisibilityBoxLocked) {
  63852. this.mesh.refreshBoundingInfo();
  63853. }
  63854. return this;
  63855. };
  63856. /**
  63857. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  63858. * @param size the size (float) of the visibility box
  63859. * note : this doesn't lock the SPS mesh bounding box.
  63860. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  63861. */
  63862. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  63863. var vis = size / 2;
  63864. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  63865. };
  63866. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  63867. /**
  63868. * Gets whether the SPS as always visible or not
  63869. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  63870. */
  63871. get: function () {
  63872. return this._alwaysVisible;
  63873. },
  63874. /**
  63875. * Sets the SPS as always visible or not
  63876. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  63877. */
  63878. set: function (val) {
  63879. this._alwaysVisible = val;
  63880. this.mesh.alwaysSelectAsActiveMesh = val;
  63881. },
  63882. enumerable: true,
  63883. configurable: true
  63884. });
  63885. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  63886. /**
  63887. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  63888. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  63889. */
  63890. get: function () {
  63891. return this._isVisibilityBoxLocked;
  63892. },
  63893. /**
  63894. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  63895. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  63896. */
  63897. set: function (val) {
  63898. this._isVisibilityBoxLocked = val;
  63899. var boundingInfo = this.mesh.getBoundingInfo();
  63900. boundingInfo.isLocked = val;
  63901. },
  63902. enumerable: true,
  63903. configurable: true
  63904. });
  63905. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  63906. /**
  63907. * Gets if `setParticles()` computes the particle rotations or not.
  63908. * Default value : true. The SPS is faster when it's set to false.
  63909. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  63910. */
  63911. get: function () {
  63912. return this._computeParticleRotation;
  63913. },
  63914. /**
  63915. * Tells to `setParticles()` to compute the particle rotations or not.
  63916. * Default value : true. The SPS is faster when it's set to false.
  63917. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  63918. */
  63919. set: function (val) {
  63920. this._computeParticleRotation = val;
  63921. },
  63922. enumerable: true,
  63923. configurable: true
  63924. });
  63925. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  63926. /**
  63927. * Gets if `setParticles()` computes the particle colors or not.
  63928. * Default value : true. The SPS is faster when it's set to false.
  63929. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  63930. */
  63931. get: function () {
  63932. return this._computeParticleColor;
  63933. },
  63934. /**
  63935. * Tells to `setParticles()` to compute the particle colors or not.
  63936. * Default value : true. The SPS is faster when it's set to false.
  63937. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  63938. */
  63939. set: function (val) {
  63940. this._computeParticleColor = val;
  63941. },
  63942. enumerable: true,
  63943. configurable: true
  63944. });
  63945. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  63946. /**
  63947. * Gets if `setParticles()` computes the particle textures or not.
  63948. * Default value : true. The SPS is faster when it's set to false.
  63949. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  63950. */
  63951. get: function () {
  63952. return this._computeParticleTexture;
  63953. },
  63954. set: function (val) {
  63955. this._computeParticleTexture = val;
  63956. },
  63957. enumerable: true,
  63958. configurable: true
  63959. });
  63960. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  63961. /**
  63962. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  63963. * Default value : false. The SPS is faster when it's set to false.
  63964. * Note : the particle custom vertex positions aren't stored values.
  63965. */
  63966. get: function () {
  63967. return this._computeParticleVertex;
  63968. },
  63969. /**
  63970. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  63971. * Default value : false. The SPS is faster when it's set to false.
  63972. * Note : the particle custom vertex positions aren't stored values.
  63973. */
  63974. set: function (val) {
  63975. this._computeParticleVertex = val;
  63976. },
  63977. enumerable: true,
  63978. configurable: true
  63979. });
  63980. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  63981. /**
  63982. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  63983. */
  63984. get: function () {
  63985. return this._computeBoundingBox;
  63986. },
  63987. /**
  63988. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  63989. */
  63990. set: function (val) {
  63991. this._computeBoundingBox = val;
  63992. },
  63993. enumerable: true,
  63994. configurable: true
  63995. });
  63996. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  63997. /**
  63998. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  63999. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  64000. * Default : `true`
  64001. */
  64002. get: function () {
  64003. return this._depthSortParticles;
  64004. },
  64005. /**
  64006. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  64007. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  64008. * Default : `true`
  64009. */
  64010. set: function (val) {
  64011. this._depthSortParticles = val;
  64012. },
  64013. enumerable: true,
  64014. configurable: true
  64015. });
  64016. // =======================================================================
  64017. // Particle behavior logic
  64018. // these following methods may be overwritten by the user to fit his needs
  64019. /**
  64020. * This function does nothing. It may be overwritten to set all the particle first values.
  64021. * The SPS doesn't call this function, you may have to call it by your own.
  64022. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  64023. */
  64024. SolidParticleSystem.prototype.initParticles = function () {
  64025. };
  64026. /**
  64027. * This function does nothing. It may be overwritten to recycle a particle.
  64028. * The SPS doesn't call this function, you may have to call it by your own.
  64029. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  64030. * @param particle The particle to recycle
  64031. * @returns the recycled particle
  64032. */
  64033. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  64034. return particle;
  64035. };
  64036. /**
  64037. * Updates a particle : this function should be overwritten by the user.
  64038. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  64039. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  64040. * @example : just set a particle position or velocity and recycle conditions
  64041. * @param particle The particle to update
  64042. * @returns the updated particle
  64043. */
  64044. SolidParticleSystem.prototype.updateParticle = function (particle) {
  64045. return particle;
  64046. };
  64047. /**
  64048. * Updates a vertex of a particle : it can be overwritten by the user.
  64049. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  64050. * @param particle the current particle
  64051. * @param vertex the current index of the current particle
  64052. * @param pt the index of the current vertex in the particle shape
  64053. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  64054. * @example : just set a vertex particle position
  64055. * @returns the updated vertex
  64056. */
  64057. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  64058. return vertex;
  64059. };
  64060. /**
  64061. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  64062. * This does nothing and may be overwritten by the user.
  64063. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  64064. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  64065. * @param update the boolean update value actually passed to setParticles()
  64066. */
  64067. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  64068. };
  64069. /**
  64070. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  64071. * This will be passed three parameters.
  64072. * This does nothing and may be overwritten by the user.
  64073. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  64074. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  64075. * @param update the boolean update value actually passed to setParticles()
  64076. */
  64077. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  64078. };
  64079. return SolidParticleSystem;
  64080. }());
  64081. BABYLON.SolidParticleSystem = SolidParticleSystem;
  64082. })(BABYLON || (BABYLON = {}));
  64083. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  64084. var BABYLON;
  64085. (function (BABYLON) {
  64086. /**
  64087. * Class containing static functions to help procedurally build meshes
  64088. */
  64089. var MeshBuilder = /** @class */ (function () {
  64090. function MeshBuilder() {
  64091. }
  64092. MeshBuilder.updateSideOrientation = function (orientation) {
  64093. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  64094. return BABYLON.Mesh.DOUBLESIDE;
  64095. }
  64096. if (orientation === undefined || orientation === null) {
  64097. return BABYLON.Mesh.FRONTSIDE;
  64098. }
  64099. return orientation;
  64100. };
  64101. /**
  64102. * Creates a box mesh
  64103. * * The parameter `size` sets the size (float) of each box side (default 1)
  64104. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  64105. * * 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)
  64106. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  64107. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64108. * * 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
  64109. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64110. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  64111. * @param name defines the name of the mesh
  64112. * @param options defines the options used to create the mesh
  64113. * @param scene defines the hosting scene
  64114. * @returns the box mesh
  64115. */
  64116. MeshBuilder.CreateBox = function (name, options, scene) {
  64117. if (scene === void 0) { scene = null; }
  64118. var box = new BABYLON.Mesh(name, scene);
  64119. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64120. box._originalBuilderSideOrientation = options.sideOrientation;
  64121. var vertexData = BABYLON.VertexData.CreateBox(options);
  64122. vertexData.applyToMesh(box, options.updatable);
  64123. return box;
  64124. };
  64125. /**
  64126. * Creates a sphere mesh
  64127. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  64128. * * 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`)
  64129. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  64130. * * 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
  64131. * * 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)
  64132. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64133. * * 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
  64134. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64135. * @param name defines the name of the mesh
  64136. * @param options defines the options used to create the mesh
  64137. * @param scene defines the hosting scene
  64138. * @returns the sphere mesh
  64139. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  64140. */
  64141. MeshBuilder.CreateSphere = function (name, options, scene) {
  64142. var sphere = new BABYLON.Mesh(name, scene);
  64143. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64144. sphere._originalBuilderSideOrientation = options.sideOrientation;
  64145. var vertexData = BABYLON.VertexData.CreateSphere(options);
  64146. vertexData.applyToMesh(sphere, options.updatable);
  64147. return sphere;
  64148. };
  64149. /**
  64150. * Creates a plane polygonal mesh. By default, this is a disc
  64151. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  64152. * * 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
  64153. * * 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
  64154. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64155. * * 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
  64156. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64157. * @param name defines the name of the mesh
  64158. * @param options defines the options used to create the mesh
  64159. * @param scene defines the hosting scene
  64160. * @returns the plane polygonal mesh
  64161. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  64162. */
  64163. MeshBuilder.CreateDisc = function (name, options, scene) {
  64164. if (scene === void 0) { scene = null; }
  64165. var disc = new BABYLON.Mesh(name, scene);
  64166. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64167. disc._originalBuilderSideOrientation = options.sideOrientation;
  64168. var vertexData = BABYLON.VertexData.CreateDisc(options);
  64169. vertexData.applyToMesh(disc, options.updatable);
  64170. return disc;
  64171. };
  64172. /**
  64173. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  64174. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  64175. * * 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`)
  64176. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  64177. * * 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
  64178. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64179. * * 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
  64180. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64181. * @param name defines the name of the mesh
  64182. * @param options defines the options used to create the mesh
  64183. * @param scene defines the hosting scene
  64184. * @returns the icosahedron mesh
  64185. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  64186. */
  64187. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  64188. var sphere = new BABYLON.Mesh(name, scene);
  64189. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64190. sphere._originalBuilderSideOrientation = options.sideOrientation;
  64191. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  64192. vertexData.applyToMesh(sphere, options.updatable);
  64193. return sphere;
  64194. };
  64195. ;
  64196. /**
  64197. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  64198. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  64199. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  64200. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  64201. * * 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
  64202. * * 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
  64203. * * 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
  64204. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64205. * * 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
  64206. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  64207. * * 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
  64208. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  64209. * * 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
  64210. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  64211. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64212. * @param name defines the name of the mesh
  64213. * @param options defines the options used to create the mesh
  64214. * @param scene defines the hosting scene
  64215. * @returns the ribbon mesh
  64216. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  64217. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  64218. */
  64219. MeshBuilder.CreateRibbon = function (name, options, scene) {
  64220. if (scene === void 0) { scene = null; }
  64221. var pathArray = options.pathArray;
  64222. var closeArray = options.closeArray;
  64223. var closePath = options.closePath;
  64224. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64225. var instance = options.instance;
  64226. var updatable = options.updatable;
  64227. if (instance) { // existing ribbon instance update
  64228. // positionFunction : ribbon case
  64229. // only pathArray and sideOrientation parameters are taken into account for positions update
  64230. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  64231. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  64232. var positionFunction = function (positions) {
  64233. var minlg = pathArray[0].length;
  64234. var i = 0;
  64235. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  64236. for (var si = 1; si <= ns; si++) {
  64237. for (var p = 0; p < pathArray.length; p++) {
  64238. var path = pathArray[p];
  64239. var l = path.length;
  64240. minlg = (minlg < l) ? minlg : l;
  64241. var j = 0;
  64242. while (j < minlg) {
  64243. positions[i] = path[j].x;
  64244. positions[i + 1] = path[j].y;
  64245. positions[i + 2] = path[j].z;
  64246. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  64247. BABYLON.Tmp.Vector3[0].x = path[j].x;
  64248. }
  64249. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  64250. BABYLON.Tmp.Vector3[1].x = path[j].x;
  64251. }
  64252. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  64253. BABYLON.Tmp.Vector3[0].y = path[j].y;
  64254. }
  64255. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  64256. BABYLON.Tmp.Vector3[1].y = path[j].y;
  64257. }
  64258. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  64259. BABYLON.Tmp.Vector3[0].z = path[j].z;
  64260. }
  64261. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  64262. BABYLON.Tmp.Vector3[1].z = path[j].z;
  64263. }
  64264. j++;
  64265. i += 3;
  64266. }
  64267. if (instance._closePath) {
  64268. positions[i] = path[0].x;
  64269. positions[i + 1] = path[0].y;
  64270. positions[i + 2] = path[0].z;
  64271. i += 3;
  64272. }
  64273. }
  64274. }
  64275. };
  64276. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  64277. positionFunction(positions);
  64278. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  64279. instance._boundingInfo.update(instance._worldMatrix);
  64280. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  64281. if (options.colors) {
  64282. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  64283. for (var c = 0; c < options.colors.length; c++) {
  64284. colors[c * 4] = options.colors[c].r;
  64285. colors[c * 4 + 1] = options.colors[c].g;
  64286. colors[c * 4 + 2] = options.colors[c].b;
  64287. colors[c * 4 + 3] = options.colors[c].a;
  64288. }
  64289. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  64290. }
  64291. if (options.uvs) {
  64292. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  64293. for (var i = 0; i < options.uvs.length; i++) {
  64294. uvs[i * 2] = options.uvs[i].x;
  64295. uvs[i * 2 + 1] = options.uvs[i].y;
  64296. }
  64297. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  64298. }
  64299. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  64300. var indices = instance.getIndices();
  64301. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  64302. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  64303. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  64304. if (instance._closePath) {
  64305. var indexFirst = 0;
  64306. var indexLast = 0;
  64307. for (var p = 0; p < pathArray.length; p++) {
  64308. indexFirst = instance._idx[p] * 3;
  64309. if (p + 1 < pathArray.length) {
  64310. indexLast = (instance._idx[p + 1] - 1) * 3;
  64311. }
  64312. else {
  64313. indexLast = normals.length - 3;
  64314. }
  64315. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  64316. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  64317. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  64318. normals[indexLast] = normals[indexFirst];
  64319. normals[indexLast + 1] = normals[indexFirst + 1];
  64320. normals[indexLast + 2] = normals[indexFirst + 2];
  64321. }
  64322. }
  64323. if (!(instance.areNormalsFrozen)) {
  64324. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  64325. }
  64326. }
  64327. return instance;
  64328. }
  64329. else { // new ribbon creation
  64330. var ribbon = new BABYLON.Mesh(name, scene);
  64331. ribbon._originalBuilderSideOrientation = sideOrientation;
  64332. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  64333. if (closePath) {
  64334. ribbon._idx = vertexData._idx;
  64335. }
  64336. ribbon._closePath = closePath;
  64337. ribbon._closeArray = closeArray;
  64338. vertexData.applyToMesh(ribbon, updatable);
  64339. return ribbon;
  64340. }
  64341. };
  64342. /**
  64343. * Creates a cylinder or a cone mesh
  64344. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  64345. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  64346. * * 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.
  64347. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  64348. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  64349. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  64350. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  64351. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  64352. * * 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).
  64353. * * 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
  64354. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  64355. * * 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
  64356. * * 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.
  64357. * * If `enclose` is false, a ring surface is one element.
  64358. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  64359. * * 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
  64360. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64361. * * 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
  64362. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  64363. * @param name defines the name of the mesh
  64364. * @param options defines the options used to create the mesh
  64365. * @param scene defines the hosting scene
  64366. * @returns the cylinder mesh
  64367. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  64368. */
  64369. MeshBuilder.CreateCylinder = function (name, options, scene) {
  64370. var cylinder = new BABYLON.Mesh(name, scene);
  64371. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64372. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  64373. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  64374. vertexData.applyToMesh(cylinder, options.updatable);
  64375. return cylinder;
  64376. };
  64377. /**
  64378. * Creates a torus mesh
  64379. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  64380. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  64381. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  64382. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64383. * * 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
  64384. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  64385. * @param name defines the name of the mesh
  64386. * @param options defines the options used to create the mesh
  64387. * @param scene defines the hosting scene
  64388. * @returns the torus mesh
  64389. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  64390. */
  64391. MeshBuilder.CreateTorus = function (name, options, scene) {
  64392. var torus = new BABYLON.Mesh(name, scene);
  64393. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64394. torus._originalBuilderSideOrientation = options.sideOrientation;
  64395. var vertexData = BABYLON.VertexData.CreateTorus(options);
  64396. vertexData.applyToMesh(torus, options.updatable);
  64397. return torus;
  64398. };
  64399. /**
  64400. * Creates a torus knot mesh
  64401. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  64402. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  64403. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  64404. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  64405. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64406. * * 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
  64407. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  64408. * @param name defines the name of the mesh
  64409. * @param options defines the options used to create the mesh
  64410. * @param scene defines the hosting scene
  64411. * @returns the torus knot mesh
  64412. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  64413. */
  64414. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  64415. var torusKnot = new BABYLON.Mesh(name, scene);
  64416. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64417. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  64418. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  64419. vertexData.applyToMesh(torusKnot, options.updatable);
  64420. return torusKnot;
  64421. };
  64422. /**
  64423. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  64424. * * 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
  64425. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  64426. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  64427. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  64428. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  64429. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  64430. * * 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
  64431. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  64432. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64433. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  64434. * @param name defines the name of the new line system
  64435. * @param options defines the options used to create the line system
  64436. * @param scene defines the hosting scene
  64437. * @returns a new line system mesh
  64438. */
  64439. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  64440. var instance = options.instance;
  64441. var lines = options.lines;
  64442. var colors = options.colors;
  64443. if (instance) { // lines update
  64444. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  64445. var vertexColor;
  64446. var lineColors;
  64447. if (colors) {
  64448. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  64449. }
  64450. var i = 0;
  64451. var c = 0;
  64452. for (var l = 0; l < lines.length; l++) {
  64453. var points = lines[l];
  64454. for (var p = 0; p < points.length; p++) {
  64455. positions[i] = points[p].x;
  64456. positions[i + 1] = points[p].y;
  64457. positions[i + 2] = points[p].z;
  64458. if (colors && vertexColor) {
  64459. lineColors = colors[l];
  64460. vertexColor[c] = lineColors[p].r;
  64461. vertexColor[c + 1] = lineColors[p].g;
  64462. vertexColor[c + 2] = lineColors[p].b;
  64463. vertexColor[c + 3] = lineColors[p].a;
  64464. c += 4;
  64465. }
  64466. i += 3;
  64467. }
  64468. }
  64469. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  64470. if (colors && vertexColor) {
  64471. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  64472. }
  64473. return instance;
  64474. }
  64475. // line system creation
  64476. var useVertexColor = (colors) ? true : false;
  64477. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  64478. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  64479. vertexData.applyToMesh(lineSystem, options.updatable);
  64480. return lineSystem;
  64481. };
  64482. /**
  64483. * Creates a line mesh
  64484. * 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
  64485. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  64486. * * The parameter `points` is an array successive Vector3
  64487. * * 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
  64488. * * The optional parameter `colors` is an array of successive Color4, one per line point
  64489. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  64490. * * When updating an instance, remember that only point positions can change, not the number of points
  64491. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64492. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  64493. * @param name defines the name of the new line system
  64494. * @param options defines the options used to create the line system
  64495. * @param scene defines the hosting scene
  64496. * @returns a new line mesh
  64497. */
  64498. MeshBuilder.CreateLines = function (name, options, scene) {
  64499. if (scene === void 0) { scene = null; }
  64500. var colors = (options.colors) ? [options.colors] : null;
  64501. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  64502. return lines;
  64503. };
  64504. /**
  64505. * Creates a dashed line mesh
  64506. * * 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
  64507. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  64508. * * The parameter `points` is an array successive Vector3
  64509. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  64510. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  64511. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  64512. * * 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
  64513. * * When updating an instance, remember that only point positions can change, not the number of points
  64514. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64515. * @param name defines the name of the mesh
  64516. * @param options defines the options used to create the mesh
  64517. * @param scene defines the hosting scene
  64518. * @returns the dashed line mesh
  64519. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  64520. */
  64521. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  64522. if (scene === void 0) { scene = null; }
  64523. var points = options.points;
  64524. var instance = options.instance;
  64525. var gapSize = options.gapSize || 1;
  64526. var dashSize = options.dashSize || 3;
  64527. if (instance) { // dashed lines update
  64528. var positionFunction = function (positions) {
  64529. var curvect = BABYLON.Vector3.Zero();
  64530. var nbSeg = positions.length / 6;
  64531. var lg = 0;
  64532. var nb = 0;
  64533. var shft = 0;
  64534. var dashshft = 0;
  64535. var curshft = 0;
  64536. var p = 0;
  64537. var i = 0;
  64538. var j = 0;
  64539. for (i = 0; i < points.length - 1; i++) {
  64540. points[i + 1].subtractToRef(points[i], curvect);
  64541. lg += curvect.length();
  64542. }
  64543. shft = lg / nbSeg;
  64544. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  64545. for (i = 0; i < points.length - 1; i++) {
  64546. points[i + 1].subtractToRef(points[i], curvect);
  64547. nb = Math.floor(curvect.length() / shft);
  64548. curvect.normalize();
  64549. j = 0;
  64550. while (j < nb && p < positions.length) {
  64551. curshft = shft * j;
  64552. positions[p] = points[i].x + curshft * curvect.x;
  64553. positions[p + 1] = points[i].y + curshft * curvect.y;
  64554. positions[p + 2] = points[i].z + curshft * curvect.z;
  64555. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  64556. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  64557. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  64558. p += 6;
  64559. j++;
  64560. }
  64561. }
  64562. while (p < positions.length) {
  64563. positions[p] = points[i].x;
  64564. positions[p + 1] = points[i].y;
  64565. positions[p + 2] = points[i].z;
  64566. p += 3;
  64567. }
  64568. };
  64569. instance.updateMeshPositions(positionFunction, false);
  64570. return instance;
  64571. }
  64572. // dashed lines creation
  64573. var dashedLines = new BABYLON.LinesMesh(name, scene);
  64574. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  64575. vertexData.applyToMesh(dashedLines, options.updatable);
  64576. dashedLines.dashSize = dashSize;
  64577. dashedLines.gapSize = gapSize;
  64578. return dashedLines;
  64579. };
  64580. /**
  64581. * 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.
  64582. * * 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.
  64583. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  64584. * * 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.
  64585. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  64586. * * 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
  64587. * * 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
  64588. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  64589. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64590. * * 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
  64591. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  64592. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  64593. * @param name defines the name of the mesh
  64594. * @param options defines the options used to create the mesh
  64595. * @param scene defines the hosting scene
  64596. * @returns the extruded shape mesh
  64597. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  64598. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  64599. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  64600. */
  64601. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  64602. if (scene === void 0) { scene = null; }
  64603. var path = options.path;
  64604. var shape = options.shape;
  64605. var scale = options.scale || 1;
  64606. var rotation = options.rotation || 0;
  64607. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  64608. var updatable = options.updatable;
  64609. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64610. var instance = options.instance || null;
  64611. var invertUV = options.invertUV || false;
  64612. 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);
  64613. };
  64614. /**
  64615. * Creates an custom extruded shape mesh.
  64616. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  64617. * * 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.
  64618. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  64619. * * 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
  64620. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  64621. * * 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
  64622. * * It must returns a float value that will be the scale value applied to the shape on each path point
  64623. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  64624. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  64625. * * 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
  64626. * * 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
  64627. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  64628. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64629. * * 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
  64630. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  64631. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64632. * @param name defines the name of the mesh
  64633. * @param options defines the options used to create the mesh
  64634. * @param scene defines the hosting scene
  64635. * @returns the custom extruded shape mesh
  64636. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  64637. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  64638. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  64639. */
  64640. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  64641. var path = options.path;
  64642. var shape = options.shape;
  64643. var scaleFunction = options.scaleFunction || (function () { return 1; });
  64644. var rotationFunction = options.rotationFunction || (function () { return 0; });
  64645. var ribbonCloseArray = options.ribbonCloseArray || false;
  64646. var ribbonClosePath = options.ribbonClosePath || false;
  64647. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  64648. var updatable = options.updatable;
  64649. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64650. var instance = options.instance;
  64651. var invertUV = options.invertUV || false;
  64652. 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);
  64653. };
  64654. /**
  64655. * Creates lathe mesh.
  64656. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  64657. * * 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
  64658. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  64659. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  64660. * * The parameter `clip` (positive integer, default 0) is the number of sides to not create without effecting the general shape of the sides
  64661. * * 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
  64662. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  64663. * * 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
  64664. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64665. * * 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
  64666. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  64667. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64668. * @param name defines the name of the mesh
  64669. * @param options defines the options used to create the mesh
  64670. * @param scene defines the hosting scene
  64671. * @returns the lathe mesh
  64672. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  64673. */
  64674. MeshBuilder.CreateLathe = function (name, options, scene) {
  64675. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  64676. var closed = (options.closed === undefined) ? true : options.closed;
  64677. var shape = options.shape;
  64678. var radius = options.radius || 1;
  64679. var tessellation = options.tessellation || 64;
  64680. var clip = options.clip || 0;
  64681. var updatable = options.updatable;
  64682. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64683. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  64684. var pi2 = Math.PI * 2;
  64685. var paths = new Array();
  64686. var invertUV = options.invertUV || false;
  64687. var i = 0;
  64688. var p = 0;
  64689. var step = pi2 / tessellation * arc;
  64690. var rotated;
  64691. var path = new Array();
  64692. for (i = 0; i <= tessellation - clip; i++) {
  64693. var path = [];
  64694. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  64695. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  64696. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  64697. }
  64698. for (p = 0; p < shape.length; p++) {
  64699. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  64700. path.push(rotated);
  64701. }
  64702. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  64703. 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));
  64704. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  64705. }
  64706. paths.push(path);
  64707. }
  64708. // lathe ribbon
  64709. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  64710. return lathe;
  64711. };
  64712. /**
  64713. * Creates a plane mesh
  64714. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  64715. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  64716. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  64717. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64718. * * 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
  64719. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64720. * @param name defines the name of the mesh
  64721. * @param options defines the options used to create the mesh
  64722. * @param scene defines the hosting scene
  64723. * @returns the plane mesh
  64724. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  64725. */
  64726. MeshBuilder.CreatePlane = function (name, options, scene) {
  64727. var plane = new BABYLON.Mesh(name, scene);
  64728. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64729. plane._originalBuilderSideOrientation = options.sideOrientation;
  64730. var vertexData = BABYLON.VertexData.CreatePlane(options);
  64731. vertexData.applyToMesh(plane, options.updatable);
  64732. if (options.sourcePlane) {
  64733. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  64734. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  64735. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  64736. plane.rotate(vectorProduct, product);
  64737. }
  64738. return plane;
  64739. };
  64740. /**
  64741. * Creates a ground mesh
  64742. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  64743. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  64744. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64745. * @param name defines the name of the mesh
  64746. * @param options defines the options used to create the mesh
  64747. * @param scene defines the hosting scene
  64748. * @returns the ground mesh
  64749. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  64750. */
  64751. MeshBuilder.CreateGround = function (name, options, scene) {
  64752. var ground = new BABYLON.GroundMesh(name, scene);
  64753. ground._setReady(false);
  64754. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  64755. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  64756. ground._width = options.width || 1;
  64757. ground._height = options.height || 1;
  64758. ground._maxX = ground._width / 2;
  64759. ground._maxZ = ground._height / 2;
  64760. ground._minX = -ground._maxX;
  64761. ground._minZ = -ground._maxZ;
  64762. var vertexData = BABYLON.VertexData.CreateGround(options);
  64763. vertexData.applyToMesh(ground, options.updatable);
  64764. ground._setReady(true);
  64765. return ground;
  64766. };
  64767. /**
  64768. * Creates a tiled ground mesh
  64769. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  64770. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  64771. * * 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
  64772. * * 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
  64773. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  64774. * @param name defines the name of the mesh
  64775. * @param options defines the options used to create the mesh
  64776. * @param scene defines the hosting scene
  64777. * @returns the tiled ground mesh
  64778. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  64779. */
  64780. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  64781. var tiledGround = new BABYLON.Mesh(name, scene);
  64782. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  64783. vertexData.applyToMesh(tiledGround, options.updatable);
  64784. return tiledGround;
  64785. };
  64786. /**
  64787. * Creates a ground mesh from a height map
  64788. * * The parameter `url` sets the URL of the height map image resource.
  64789. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  64790. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  64791. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  64792. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  64793. * * 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.
  64794. * * 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).
  64795. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  64796. * @param name defines the name of the mesh
  64797. * @param url defines the url to the height map
  64798. * @param options defines the options used to create the mesh
  64799. * @param scene defines the hosting scene
  64800. * @returns the ground mesh
  64801. * @see http://doc.babylonjs.com/babylon101/height_map
  64802. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  64803. */
  64804. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  64805. var width = options.width || 10.0;
  64806. var height = options.height || 10.0;
  64807. var subdivisions = options.subdivisions || 1 | 0;
  64808. var minHeight = options.minHeight || 0.0;
  64809. var maxHeight = options.maxHeight || 1.0;
  64810. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  64811. var updatable = options.updatable;
  64812. var onReady = options.onReady;
  64813. var ground = new BABYLON.GroundMesh(name, scene);
  64814. ground._subdivisionsX = subdivisions;
  64815. ground._subdivisionsY = subdivisions;
  64816. ground._width = width;
  64817. ground._height = height;
  64818. ground._maxX = ground._width / 2.0;
  64819. ground._maxZ = ground._height / 2.0;
  64820. ground._minX = -ground._maxX;
  64821. ground._minZ = -ground._maxZ;
  64822. ground._setReady(false);
  64823. var onload = function (img) {
  64824. // Getting height map data
  64825. var canvas = document.createElement("canvas");
  64826. var context = canvas.getContext("2d");
  64827. if (!context) {
  64828. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  64829. }
  64830. if (scene.isDisposed) {
  64831. return;
  64832. }
  64833. var bufferWidth = img.width;
  64834. var bufferHeight = img.height;
  64835. canvas.width = bufferWidth;
  64836. canvas.height = bufferHeight;
  64837. context.drawImage(img, 0, 0);
  64838. // Create VertexData from map data
  64839. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  64840. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  64841. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  64842. width: width, height: height,
  64843. subdivisions: subdivisions,
  64844. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  64845. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  64846. });
  64847. vertexData.applyToMesh(ground, updatable);
  64848. //execute ready callback, if set
  64849. if (onReady) {
  64850. onReady(ground);
  64851. }
  64852. ground._setReady(true);
  64853. };
  64854. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  64855. return ground;
  64856. };
  64857. /**
  64858. * Creates a polygon mesh
  64859. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  64860. * * 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
  64861. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64862. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64863. * * 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)
  64864. * * Remember you can only change the shape positions, not their number when updating a polygon
  64865. * @param name defines the name of the mesh
  64866. * @param options defines the options used to create the mesh
  64867. * @param scene defines the hosting scene
  64868. * @returns the polygon mesh
  64869. */
  64870. MeshBuilder.CreatePolygon = function (name, options, scene) {
  64871. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64872. var shape = options.shape;
  64873. var holes = options.holes || [];
  64874. var depth = options.depth || 0;
  64875. var contours = [];
  64876. var hole = [];
  64877. for (var i = 0; i < shape.length; i++) {
  64878. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  64879. }
  64880. var epsilon = 0.00000001;
  64881. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  64882. contours.pop();
  64883. }
  64884. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  64885. for (var hNb = 0; hNb < holes.length; hNb++) {
  64886. hole = [];
  64887. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  64888. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  64889. }
  64890. polygonTriangulation.addHole(hole);
  64891. }
  64892. var polygon = polygonTriangulation.build(options.updatable, depth);
  64893. polygon._originalBuilderSideOrientation = options.sideOrientation;
  64894. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  64895. vertexData.applyToMesh(polygon, options.updatable);
  64896. return polygon;
  64897. };
  64898. ;
  64899. /**
  64900. * Creates an extruded polygon mesh, with depth in the Y direction.
  64901. * * 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)
  64902. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  64903. * @param name defines the name of the mesh
  64904. * @param options defines the options used to create the mesh
  64905. * @param scene defines the hosting scene
  64906. * @returns the polygon mesh
  64907. */
  64908. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  64909. return MeshBuilder.CreatePolygon(name, options, scene);
  64910. };
  64911. ;
  64912. /**
  64913. * Creates a tube mesh.
  64914. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  64915. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  64916. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  64917. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  64918. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  64919. * * 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)
  64920. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  64921. * * 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
  64922. * * 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
  64923. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  64924. * * 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
  64925. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  64926. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  64927. * @param name defines the name of the mesh
  64928. * @param options defines the options used to create the mesh
  64929. * @param scene defines the hosting scene
  64930. * @returns the tube mesh
  64931. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  64932. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  64933. */
  64934. MeshBuilder.CreateTube = function (name, options, scene) {
  64935. var path = options.path;
  64936. var instance = options.instance;
  64937. var radius = 1.0;
  64938. if (instance) {
  64939. radius = instance.radius;
  64940. }
  64941. if (options.radius !== undefined) {
  64942. radius = options.radius;
  64943. }
  64944. ;
  64945. var tessellation = options.tessellation || 64 | 0;
  64946. var radiusFunction = options.radiusFunction || null;
  64947. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  64948. var invertUV = options.invertUV || false;
  64949. var updatable = options.updatable;
  64950. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  64951. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  64952. // tube geometry
  64953. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  64954. var tangents = path3D.getTangents();
  64955. var normals = path3D.getNormals();
  64956. var distances = path3D.getDistances();
  64957. var pi2 = Math.PI * 2;
  64958. var step = pi2 / tessellation * arc;
  64959. var returnRadius = function () { return radius; };
  64960. var radiusFunctionFinal = radiusFunction || returnRadius;
  64961. var circlePath;
  64962. var rad;
  64963. var normal;
  64964. var rotated;
  64965. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  64966. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  64967. for (var i = 0; i < path.length; i++) {
  64968. rad = radiusFunctionFinal(i, distances[i]); // current radius
  64969. circlePath = Array(); // current circle array
  64970. normal = normals[i]; // current normal
  64971. for (var t = 0; t < tessellation; t++) {
  64972. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  64973. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  64974. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  64975. rotated.scaleInPlace(rad).addInPlace(path[i]);
  64976. circlePath[t] = rotated;
  64977. }
  64978. circlePaths[index] = circlePath;
  64979. index++;
  64980. }
  64981. // cap
  64982. var capPath = function (nbPoints, pathIndex) {
  64983. var pointCap = Array();
  64984. for (var i = 0; i < nbPoints; i++) {
  64985. pointCap.push(path[pathIndex]);
  64986. }
  64987. return pointCap;
  64988. };
  64989. switch (cap) {
  64990. case BABYLON.Mesh.NO_CAP:
  64991. break;
  64992. case BABYLON.Mesh.CAP_START:
  64993. circlePaths[0] = capPath(tessellation, 0);
  64994. circlePaths[1] = circlePaths[2].slice(0);
  64995. break;
  64996. case BABYLON.Mesh.CAP_END:
  64997. circlePaths[index] = circlePaths[index - 1].slice(0);
  64998. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  64999. break;
  65000. case BABYLON.Mesh.CAP_ALL:
  65001. circlePaths[0] = capPath(tessellation, 0);
  65002. circlePaths[1] = circlePaths[2].slice(0);
  65003. circlePaths[index] = circlePaths[index - 1].slice(0);
  65004. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  65005. break;
  65006. default:
  65007. break;
  65008. }
  65009. return circlePaths;
  65010. };
  65011. var path3D;
  65012. var pathArray;
  65013. if (instance) { // tube update
  65014. var arc = options.arc || instance.arc;
  65015. path3D = (instance.path3D).update(path);
  65016. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  65017. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  65018. instance.path3D = path3D;
  65019. instance.pathArray = pathArray;
  65020. instance.arc = arc;
  65021. instance.radius = radius;
  65022. return instance;
  65023. }
  65024. // tube creation
  65025. path3D = new BABYLON.Path3D(path);
  65026. var newPathArray = new Array();
  65027. cap = (cap < 0 || cap > 3) ? 0 : cap;
  65028. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  65029. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  65030. tube.pathArray = pathArray;
  65031. tube.path3D = path3D;
  65032. tube.tessellation = tessellation;
  65033. tube.cap = cap;
  65034. tube.arc = options.arc;
  65035. tube.radius = radius;
  65036. return tube;
  65037. };
  65038. /**
  65039. * Creates a polyhedron mesh
  65040. * * 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
  65041. * * The parameter `size` (positive float, default 1) sets the polygon size
  65042. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  65043. * * 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`
  65044. * * 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
  65045. * * 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)`)
  65046. * * 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
  65047. * * 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
  65048. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  65049. * * 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
  65050. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  65051. * @param name defines the name of the mesh
  65052. * @param options defines the options used to create the mesh
  65053. * @param scene defines the hosting scene
  65054. * @returns the polyhedron mesh
  65055. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  65056. */
  65057. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  65058. var polyhedron = new BABYLON.Mesh(name, scene);
  65059. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  65060. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  65061. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  65062. vertexData.applyToMesh(polyhedron, options.updatable);
  65063. return polyhedron;
  65064. };
  65065. /**
  65066. * Creates a decal mesh.
  65067. * 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
  65068. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  65069. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  65070. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  65071. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  65072. * @param name defines the name of the mesh
  65073. * @param sourceMesh defines the mesh where the decal must be applied
  65074. * @param options defines the options used to create the mesh
  65075. * @param scene defines the hosting scene
  65076. * @returns the decal mesh
  65077. * @see http://doc.babylonjs.com/how_to/decals
  65078. */
  65079. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  65080. var indices = sourceMesh.getIndices();
  65081. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  65082. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  65083. var position = options.position || BABYLON.Vector3.Zero();
  65084. var normal = options.normal || BABYLON.Vector3.Up();
  65085. var size = options.size || BABYLON.Vector3.One();
  65086. var angle = options.angle || 0;
  65087. // Getting correct rotation
  65088. if (!normal) {
  65089. var target = new BABYLON.Vector3(0, 0, 1);
  65090. var camera = sourceMesh.getScene().activeCamera;
  65091. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  65092. normal = camera.globalPosition.subtract(cameraWorldTarget);
  65093. }
  65094. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  65095. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  65096. var pitch = Math.atan2(normal.y, len);
  65097. // Matrix
  65098. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  65099. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  65100. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  65101. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  65102. var vertexData = new BABYLON.VertexData();
  65103. vertexData.indices = [];
  65104. vertexData.positions = [];
  65105. vertexData.normals = [];
  65106. vertexData.uvs = [];
  65107. var currentVertexDataIndex = 0;
  65108. var extractDecalVector3 = function (indexId) {
  65109. var result = new BABYLON.PositionNormalVertex();
  65110. if (!indices || !positions || !normals) {
  65111. return result;
  65112. }
  65113. var vertexId = indices[indexId];
  65114. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  65115. // Send vector to decal local world
  65116. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  65117. // Get normal
  65118. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  65119. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  65120. return result;
  65121. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  65122. var clip = function (vertices, axis) {
  65123. if (vertices.length === 0) {
  65124. return vertices;
  65125. }
  65126. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  65127. var clipVertices = function (v0, v1) {
  65128. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  65129. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  65130. };
  65131. var result = new Array();
  65132. for (var index = 0; index < vertices.length; index += 3) {
  65133. var v1Out;
  65134. var v2Out;
  65135. var v3Out;
  65136. var total = 0;
  65137. var nV1 = null;
  65138. var nV2 = null;
  65139. var nV3 = null;
  65140. var nV4 = null;
  65141. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  65142. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  65143. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  65144. v1Out = d1 > 0;
  65145. v2Out = d2 > 0;
  65146. v3Out = d3 > 0;
  65147. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  65148. switch (total) {
  65149. case 0:
  65150. result.push(vertices[index]);
  65151. result.push(vertices[index + 1]);
  65152. result.push(vertices[index + 2]);
  65153. break;
  65154. case 1:
  65155. if (v1Out) {
  65156. nV1 = vertices[index + 1];
  65157. nV2 = vertices[index + 2];
  65158. nV3 = clipVertices(vertices[index], nV1);
  65159. nV4 = clipVertices(vertices[index], nV2);
  65160. }
  65161. if (v2Out) {
  65162. nV1 = vertices[index];
  65163. nV2 = vertices[index + 2];
  65164. nV3 = clipVertices(vertices[index + 1], nV1);
  65165. nV4 = clipVertices(vertices[index + 1], nV2);
  65166. result.push(nV3);
  65167. result.push(nV2.clone());
  65168. result.push(nV1.clone());
  65169. result.push(nV2.clone());
  65170. result.push(nV3.clone());
  65171. result.push(nV4);
  65172. break;
  65173. }
  65174. if (v3Out) {
  65175. nV1 = vertices[index];
  65176. nV2 = vertices[index + 1];
  65177. nV3 = clipVertices(vertices[index + 2], nV1);
  65178. nV4 = clipVertices(vertices[index + 2], nV2);
  65179. }
  65180. if (nV1 && nV2 && nV3 && nV4) {
  65181. result.push(nV1.clone());
  65182. result.push(nV2.clone());
  65183. result.push(nV3);
  65184. result.push(nV4);
  65185. result.push(nV3.clone());
  65186. result.push(nV2.clone());
  65187. }
  65188. break;
  65189. case 2:
  65190. if (!v1Out) {
  65191. nV1 = vertices[index].clone();
  65192. nV2 = clipVertices(nV1, vertices[index + 1]);
  65193. nV3 = clipVertices(nV1, vertices[index + 2]);
  65194. result.push(nV1);
  65195. result.push(nV2);
  65196. result.push(nV3);
  65197. }
  65198. if (!v2Out) {
  65199. nV1 = vertices[index + 1].clone();
  65200. nV2 = clipVertices(nV1, vertices[index + 2]);
  65201. nV3 = clipVertices(nV1, vertices[index]);
  65202. result.push(nV1);
  65203. result.push(nV2);
  65204. result.push(nV3);
  65205. }
  65206. if (!v3Out) {
  65207. nV1 = vertices[index + 2].clone();
  65208. nV2 = clipVertices(nV1, vertices[index]);
  65209. nV3 = clipVertices(nV1, vertices[index + 1]);
  65210. result.push(nV1);
  65211. result.push(nV2);
  65212. result.push(nV3);
  65213. }
  65214. break;
  65215. case 3:
  65216. break;
  65217. }
  65218. }
  65219. return result;
  65220. };
  65221. for (var index = 0; index < indices.length; index += 3) {
  65222. var faceVertices = new Array();
  65223. faceVertices.push(extractDecalVector3(index));
  65224. faceVertices.push(extractDecalVector3(index + 1));
  65225. faceVertices.push(extractDecalVector3(index + 2));
  65226. // Clip
  65227. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  65228. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  65229. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  65230. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  65231. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  65232. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  65233. if (faceVertices.length === 0) {
  65234. continue;
  65235. }
  65236. // Add UVs and get back to world
  65237. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  65238. var vertex = faceVertices[vIndex];
  65239. //TODO check for Int32Array | Uint32Array | Uint16Array
  65240. vertexData.indices.push(currentVertexDataIndex);
  65241. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  65242. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  65243. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  65244. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  65245. currentVertexDataIndex++;
  65246. }
  65247. }
  65248. // Return mesh
  65249. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  65250. vertexData.applyToMesh(decal);
  65251. decal.position = position.clone();
  65252. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  65253. return decal;
  65254. };
  65255. // Privates
  65256. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  65257. // extrusion geometry
  65258. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  65259. var tangents = path3D.getTangents();
  65260. var normals = path3D.getNormals();
  65261. var binormals = path3D.getBinormals();
  65262. var distances = path3D.getDistances();
  65263. var angle = 0;
  65264. var returnScale = function () { return scale !== null ? scale : 1; };
  65265. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  65266. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  65267. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  65268. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  65269. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  65270. for (var i = 0; i < curve.length; i++) {
  65271. var shapePath = new Array();
  65272. var angleStep = rotate(i, distances[i]);
  65273. var scaleRatio = scl(i, distances[i]);
  65274. for (var p = 0; p < shape.length; p++) {
  65275. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  65276. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  65277. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  65278. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  65279. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  65280. shapePath[p] = rotated;
  65281. }
  65282. shapePaths[index] = shapePath;
  65283. angle += angleStep;
  65284. index++;
  65285. }
  65286. // cap
  65287. var capPath = function (shapePath) {
  65288. var pointCap = Array();
  65289. var barycenter = BABYLON.Vector3.Zero();
  65290. var i;
  65291. for (i = 0; i < shapePath.length; i++) {
  65292. barycenter.addInPlace(shapePath[i]);
  65293. }
  65294. barycenter.scaleInPlace(1.0 / shapePath.length);
  65295. for (i = 0; i < shapePath.length; i++) {
  65296. pointCap.push(barycenter);
  65297. }
  65298. return pointCap;
  65299. };
  65300. switch (cap) {
  65301. case BABYLON.Mesh.NO_CAP:
  65302. break;
  65303. case BABYLON.Mesh.CAP_START:
  65304. shapePaths[0] = capPath(shapePaths[2]);
  65305. shapePaths[1] = shapePaths[2];
  65306. break;
  65307. case BABYLON.Mesh.CAP_END:
  65308. shapePaths[index] = shapePaths[index - 1];
  65309. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  65310. break;
  65311. case BABYLON.Mesh.CAP_ALL:
  65312. shapePaths[0] = capPath(shapePaths[2]);
  65313. shapePaths[1] = shapePaths[2];
  65314. shapePaths[index] = shapePaths[index - 1];
  65315. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  65316. break;
  65317. default:
  65318. break;
  65319. }
  65320. return shapePaths;
  65321. };
  65322. var path3D;
  65323. var pathArray;
  65324. if (instance) { // instance update
  65325. path3D = (instance.path3D).update(curve);
  65326. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  65327. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  65328. return instance;
  65329. }
  65330. // extruded shape creation
  65331. path3D = new BABYLON.Path3D(curve);
  65332. var newShapePaths = new Array();
  65333. cap = (cap < 0 || cap > 3) ? 0 : cap;
  65334. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  65335. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  65336. extrudedGeneric.pathArray = pathArray;
  65337. extrudedGeneric.path3D = path3D;
  65338. extrudedGeneric.cap = cap;
  65339. return extrudedGeneric;
  65340. };
  65341. return MeshBuilder;
  65342. }());
  65343. BABYLON.MeshBuilder = MeshBuilder;
  65344. })(BABYLON || (BABYLON = {}));
  65345. //# sourceMappingURL=babylon.meshBuilder.js.map
  65346. var BABYLON;
  65347. (function (BABYLON) {
  65348. /**
  65349. * Draco compression (https://google.github.io/draco/)
  65350. *
  65351. * This class wraps the Draco module.
  65352. *
  65353. * **Encoder**
  65354. *
  65355. * The encoder is not currently implemented.
  65356. *
  65357. * **Decoder**
  65358. *
  65359. * By default, the configuration points to a copy of the Draco decoder files for glTF from https://preview.babylonjs.com.
  65360. *
  65361. * To update the configuration, use the following code:
  65362. * ```javascript
  65363. * BABYLON.DracoCompression.Configuration = {
  65364. * decoder: {
  65365. * wasmUrl: "<url to the WebAssembly library>",
  65366. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  65367. * fallbackUrl: "<url to the fallback JavaScript library>",
  65368. * }
  65369. * };
  65370. * ```
  65371. *
  65372. * 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.
  65373. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  65374. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  65375. *
  65376. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  65377. * ```javascript
  65378. * var dracoCompression = new BABYLON.DracoCompression();
  65379. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  65380. * [BABYLON.VertexBuffer.PositionKind]: 0
  65381. * });
  65382. * ```
  65383. *
  65384. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  65385. */
  65386. var DracoCompression = /** @class */ (function () {
  65387. /**
  65388. * Constructor
  65389. */
  65390. function DracoCompression() {
  65391. }
  65392. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  65393. /**
  65394. * Returns true if the decoder is available.
  65395. */
  65396. get: function () {
  65397. if (typeof DracoDecoderModule !== "undefined") {
  65398. return true;
  65399. }
  65400. var decoder = DracoCompression.Configuration.decoder;
  65401. if (decoder) {
  65402. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  65403. return true;
  65404. }
  65405. if (decoder.fallbackUrl) {
  65406. return true;
  65407. }
  65408. }
  65409. return false;
  65410. },
  65411. enumerable: true,
  65412. configurable: true
  65413. });
  65414. /**
  65415. * Stop all async operations and release resources.
  65416. */
  65417. DracoCompression.prototype.dispose = function () {
  65418. };
  65419. /**
  65420. * Decode Draco compressed mesh data to vertex data.
  65421. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  65422. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  65423. * @returns A promise that resolves with the decoded vertex data
  65424. */
  65425. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  65426. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  65427. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  65428. var module = wrappedModule.module;
  65429. var vertexData = new BABYLON.VertexData();
  65430. var buffer = new module.DecoderBuffer();
  65431. buffer.Init(dataView, dataView.byteLength);
  65432. var decoder = new module.Decoder();
  65433. var geometry;
  65434. var status;
  65435. try {
  65436. var type = decoder.GetEncodedGeometryType(buffer);
  65437. switch (type) {
  65438. case module.TRIANGULAR_MESH:
  65439. geometry = new module.Mesh();
  65440. status = decoder.DecodeBufferToMesh(buffer, geometry);
  65441. break;
  65442. case module.POINT_CLOUD:
  65443. geometry = new module.PointCloud();
  65444. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  65445. break;
  65446. default:
  65447. throw new Error("Invalid geometry type " + type);
  65448. }
  65449. if (!status.ok() || !geometry.ptr) {
  65450. throw new Error(status.error_msg());
  65451. }
  65452. var numPoints = geometry.num_points();
  65453. if (type === module.TRIANGULAR_MESH) {
  65454. var numFaces = geometry.num_faces();
  65455. var faceIndices = new module.DracoInt32Array();
  65456. try {
  65457. var indices = new Uint32Array(numFaces * 3);
  65458. for (var i = 0; i < numFaces; i++) {
  65459. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  65460. var offset = i * 3;
  65461. indices[offset + 0] = faceIndices.GetValue(0);
  65462. indices[offset + 1] = faceIndices.GetValue(1);
  65463. indices[offset + 2] = faceIndices.GetValue(2);
  65464. }
  65465. vertexData.indices = indices;
  65466. }
  65467. finally {
  65468. module.destroy(faceIndices);
  65469. }
  65470. }
  65471. for (var kind in attributes) {
  65472. var uniqueId = attributes[kind];
  65473. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  65474. var dracoData = new module.DracoFloat32Array();
  65475. try {
  65476. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  65477. var babylonData = new Float32Array(numPoints * attribute.num_components());
  65478. for (var i = 0; i < babylonData.length; i++) {
  65479. babylonData[i] = dracoData.GetValue(i);
  65480. }
  65481. vertexData.set(babylonData, kind);
  65482. }
  65483. finally {
  65484. module.destroy(dracoData);
  65485. }
  65486. }
  65487. }
  65488. finally {
  65489. if (geometry) {
  65490. module.destroy(geometry);
  65491. }
  65492. module.destroy(decoder);
  65493. module.destroy(buffer);
  65494. }
  65495. return vertexData;
  65496. });
  65497. };
  65498. DracoCompression._GetDecoderModule = function () {
  65499. if (!DracoCompression._DecoderModulePromise) {
  65500. var promise = null;
  65501. var config_1 = {};
  65502. if (typeof DracoDecoderModule !== "undefined") {
  65503. promise = Promise.resolve();
  65504. }
  65505. else {
  65506. var decoder = DracoCompression.Configuration.decoder;
  65507. if (decoder) {
  65508. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  65509. promise = Promise.all([
  65510. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  65511. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  65512. config_1.wasmBinary = data;
  65513. })
  65514. ]);
  65515. }
  65516. else if (decoder.fallbackUrl) {
  65517. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  65518. }
  65519. }
  65520. }
  65521. if (!promise) {
  65522. throw new Error("Draco decoder module is not available");
  65523. }
  65524. DracoCompression._DecoderModulePromise = promise.then(function () {
  65525. return new Promise(function (resolve) {
  65526. config_1.onModuleLoaded = function (decoderModule) {
  65527. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  65528. resolve({ module: decoderModule });
  65529. };
  65530. DracoDecoderModule(config_1);
  65531. });
  65532. });
  65533. }
  65534. return DracoCompression._DecoderModulePromise;
  65535. };
  65536. DracoCompression._LoadScriptAsync = function (url) {
  65537. return new Promise(function (resolve, reject) {
  65538. BABYLON.Tools.LoadScript(url, function () {
  65539. resolve();
  65540. }, function (message) {
  65541. reject(new Error(message));
  65542. });
  65543. });
  65544. };
  65545. DracoCompression._LoadFileAsync = function (url) {
  65546. return new Promise(function (resolve, reject) {
  65547. BABYLON.Tools.LoadFile(url, function (data) {
  65548. resolve(data);
  65549. }, undefined, undefined, true, function (request, exception) {
  65550. reject(exception);
  65551. });
  65552. });
  65553. };
  65554. /**
  65555. * The configuration. Defaults to the following urls:
  65556. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  65557. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  65558. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  65559. */
  65560. DracoCompression.Configuration = {
  65561. decoder: {
  65562. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  65563. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  65564. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  65565. }
  65566. };
  65567. return DracoCompression;
  65568. }());
  65569. BABYLON.DracoCompression = DracoCompression;
  65570. })(BABYLON || (BABYLON = {}));
  65571. //# sourceMappingURL=babylon.dracoCompression.js.map
  65572. var BABYLON;
  65573. (function (BABYLON) {
  65574. var AudioEngine = /** @class */ (function () {
  65575. function AudioEngine() {
  65576. this._audioContext = null;
  65577. this._audioContextInitialized = false;
  65578. this.canUseWebAudio = false;
  65579. this.WarnedWebAudioUnsupported = false;
  65580. this.unlocked = false;
  65581. this.isMP3supported = false;
  65582. this.isOGGsupported = false;
  65583. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  65584. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  65585. this.canUseWebAudio = true;
  65586. }
  65587. var audioElem = document.createElement('audio');
  65588. try {
  65589. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  65590. this.isMP3supported = true;
  65591. }
  65592. }
  65593. catch (e) {
  65594. // protect error during capability check.
  65595. }
  65596. try {
  65597. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  65598. this.isOGGsupported = true;
  65599. }
  65600. }
  65601. catch (e) {
  65602. // protect error during capability check.
  65603. }
  65604. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  65605. this._unlockiOSaudio();
  65606. }
  65607. else {
  65608. this.unlocked = true;
  65609. }
  65610. }
  65611. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  65612. get: function () {
  65613. if (!this._audioContextInitialized) {
  65614. this._initializeAudioContext();
  65615. }
  65616. return this._audioContext;
  65617. },
  65618. enumerable: true,
  65619. configurable: true
  65620. });
  65621. AudioEngine.prototype._unlockiOSaudio = function () {
  65622. var _this = this;
  65623. var unlockaudio = function () {
  65624. if (!_this.audioContext) {
  65625. return;
  65626. }
  65627. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  65628. var source = _this.audioContext.createBufferSource();
  65629. source.buffer = buffer;
  65630. source.connect(_this.audioContext.destination);
  65631. source.start(0);
  65632. setTimeout(function () {
  65633. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  65634. _this.unlocked = true;
  65635. window.removeEventListener('touchend', unlockaudio, false);
  65636. if (_this.onAudioUnlocked) {
  65637. _this.onAudioUnlocked();
  65638. }
  65639. }
  65640. }, 0);
  65641. };
  65642. window.addEventListener('touchend', unlockaudio, false);
  65643. };
  65644. AudioEngine.prototype._initializeAudioContext = function () {
  65645. try {
  65646. if (this.canUseWebAudio) {
  65647. this._audioContext = new AudioContext();
  65648. // create a global volume gain node
  65649. this.masterGain = this._audioContext.createGain();
  65650. this.masterGain.gain.value = 1;
  65651. this.masterGain.connect(this._audioContext.destination);
  65652. this._audioContextInitialized = true;
  65653. }
  65654. }
  65655. catch (e) {
  65656. this.canUseWebAudio = false;
  65657. BABYLON.Tools.Error("Web Audio: " + e.message);
  65658. }
  65659. };
  65660. AudioEngine.prototype.dispose = function () {
  65661. if (this.canUseWebAudio && this._audioContextInitialized) {
  65662. if (this._connectedAnalyser && this._audioContext) {
  65663. this._connectedAnalyser.stopDebugCanvas();
  65664. this._connectedAnalyser.dispose();
  65665. this.masterGain.disconnect();
  65666. this.masterGain.connect(this._audioContext.destination);
  65667. this._connectedAnalyser = null;
  65668. }
  65669. this.masterGain.gain.value = 1;
  65670. }
  65671. this.WarnedWebAudioUnsupported = false;
  65672. };
  65673. AudioEngine.prototype.getGlobalVolume = function () {
  65674. if (this.canUseWebAudio && this._audioContextInitialized) {
  65675. return this.masterGain.gain.value;
  65676. }
  65677. else {
  65678. return -1;
  65679. }
  65680. };
  65681. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  65682. if (this.canUseWebAudio && this._audioContextInitialized) {
  65683. this.masterGain.gain.value = newVolume;
  65684. }
  65685. };
  65686. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  65687. if (this._connectedAnalyser) {
  65688. this._connectedAnalyser.stopDebugCanvas();
  65689. }
  65690. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  65691. this._connectedAnalyser = analyser;
  65692. this.masterGain.disconnect();
  65693. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  65694. }
  65695. };
  65696. return AudioEngine;
  65697. }());
  65698. BABYLON.AudioEngine = AudioEngine;
  65699. })(BABYLON || (BABYLON = {}));
  65700. //# sourceMappingURL=babylon.audioEngine.js.map
  65701. var BABYLON;
  65702. (function (BABYLON) {
  65703. var Sound = /** @class */ (function () {
  65704. /**
  65705. * Create a sound and attach it to a scene
  65706. * @param name Name of your sound
  65707. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer, it also works with MediaStreams
  65708. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  65709. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  65710. */
  65711. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  65712. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  65713. var _this = this;
  65714. this.autoplay = false;
  65715. this.loop = false;
  65716. this.useCustomAttenuation = false;
  65717. this.spatialSound = false;
  65718. this.refDistance = 1;
  65719. this.rolloffFactor = 1;
  65720. this.maxDistance = 100;
  65721. this.distanceModel = "linear";
  65722. this._panningModel = "equalpower";
  65723. /**
  65724. * Observable event when the current playing sound finishes.
  65725. */
  65726. this.onEndedObservable = new BABYLON.Observable();
  65727. this._playbackRate = 1;
  65728. this._streaming = false;
  65729. this._startTime = 0;
  65730. this._startOffset = 0;
  65731. this._position = BABYLON.Vector3.Zero();
  65732. /** @hidden */
  65733. this._positionInEmitterSpace = false;
  65734. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  65735. this._volume = 1;
  65736. this._isReadyToPlay = false;
  65737. this.isPlaying = false;
  65738. this.isPaused = false;
  65739. this._isDirectional = false;
  65740. // Used if you'd like to create a directional sound.
  65741. // If not set, the sound will be omnidirectional
  65742. this._coneInnerAngle = 360;
  65743. this._coneOuterAngle = 360;
  65744. this._coneOuterGain = 0;
  65745. this._isOutputConnected = false;
  65746. this._urlType = "Unknown";
  65747. this.name = name;
  65748. this._scene = scene;
  65749. this._readyToPlayCallback = readyToPlayCallback;
  65750. // Default custom attenuation function is a linear attenuation
  65751. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  65752. if (currentDistance < maxDistance) {
  65753. return currentVolume * (1 - currentDistance / maxDistance);
  65754. }
  65755. else {
  65756. return 0;
  65757. }
  65758. };
  65759. if (options) {
  65760. this.autoplay = options.autoplay || false;
  65761. this.loop = options.loop || false;
  65762. // if volume === 0, we need another way to check this option
  65763. if (options.volume !== undefined) {
  65764. this._volume = options.volume;
  65765. }
  65766. this.spatialSound = options.spatialSound || false;
  65767. this.maxDistance = options.maxDistance || 100;
  65768. this.useCustomAttenuation = options.useCustomAttenuation || false;
  65769. this.rolloffFactor = options.rolloffFactor || 1;
  65770. this.refDistance = options.refDistance || 1;
  65771. this.distanceModel = options.distanceModel || "linear";
  65772. this._playbackRate = options.playbackRate || 1;
  65773. this._streaming = options.streaming || false;
  65774. }
  65775. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  65776. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  65777. this._soundGain.gain.value = this._volume;
  65778. this._inputAudioNode = this._soundGain;
  65779. this._outputAudioNode = this._soundGain;
  65780. if (this.spatialSound) {
  65781. this._createSpatialParameters();
  65782. }
  65783. this._scene.mainSoundTrack.AddSound(this);
  65784. var validParameter = true;
  65785. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  65786. if (urlOrArrayBuffer) {
  65787. try {
  65788. if (typeof (urlOrArrayBuffer) === "string") {
  65789. this._urlType = "String";
  65790. }
  65791. else if (urlOrArrayBuffer instanceof ArrayBuffer) {
  65792. this._urlType = "ArrayBuffer";
  65793. }
  65794. else if (urlOrArrayBuffer instanceof MediaStream) {
  65795. this._urlType = "MediaStream";
  65796. }
  65797. else if (Array.isArray(urlOrArrayBuffer)) {
  65798. this._urlType = "Array";
  65799. }
  65800. var urls = [];
  65801. var codecSupportedFound = false;
  65802. switch (this._urlType) {
  65803. case "MediaStream":
  65804. this._streaming = true;
  65805. this._isReadyToPlay = true;
  65806. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(urlOrArrayBuffer);
  65807. if (this.autoplay) {
  65808. this.play();
  65809. }
  65810. if (this._readyToPlayCallback) {
  65811. this._readyToPlayCallback();
  65812. }
  65813. break;
  65814. case "ArrayBuffer":
  65815. if (urlOrArrayBuffer.byteLength > 0) {
  65816. codecSupportedFound = true;
  65817. this._soundLoaded(urlOrArrayBuffer);
  65818. }
  65819. break;
  65820. case "String":
  65821. urls.push(urlOrArrayBuffer);
  65822. case "Array":
  65823. if (urls.length === 0)
  65824. urls = urlOrArrayBuffer;
  65825. // If we found a supported format, we load it immediately and stop the loop
  65826. for (var i = 0; i < urls.length; i++) {
  65827. var url = urls[i];
  65828. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  65829. codecSupportedFound = true;
  65830. }
  65831. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  65832. codecSupportedFound = true;
  65833. }
  65834. if (url.indexOf(".wav", url.length - 4) !== -1) {
  65835. codecSupportedFound = true;
  65836. }
  65837. if (url.indexOf("blob:") !== -1) {
  65838. codecSupportedFound = true;
  65839. }
  65840. if (codecSupportedFound) {
  65841. // Loading sound using XHR2
  65842. if (!this._streaming) {
  65843. this._scene._loadFile(url, function (data) {
  65844. _this._soundLoaded(data);
  65845. }, undefined, true, true, function (exception) {
  65846. if (exception) {
  65847. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  65848. }
  65849. BABYLON.Tools.Error("Sound creation aborted.");
  65850. _this._scene.mainSoundTrack.RemoveSound(_this);
  65851. });
  65852. }
  65853. // Streaming sound using HTML5 Audio tag
  65854. else {
  65855. this._htmlAudioElement = new Audio(url);
  65856. this._htmlAudioElement.controls = false;
  65857. this._htmlAudioElement.loop = this.loop;
  65858. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  65859. this._htmlAudioElement.preload = "auto";
  65860. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  65861. _this._isReadyToPlay = true;
  65862. if (_this.autoplay) {
  65863. _this.play();
  65864. }
  65865. if (_this._readyToPlayCallback) {
  65866. _this._readyToPlayCallback();
  65867. }
  65868. });
  65869. document.body.appendChild(this._htmlAudioElement);
  65870. }
  65871. break;
  65872. }
  65873. }
  65874. break;
  65875. default:
  65876. validParameter = false;
  65877. break;
  65878. }
  65879. if (!validParameter) {
  65880. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  65881. }
  65882. else {
  65883. if (!codecSupportedFound) {
  65884. this._isReadyToPlay = true;
  65885. // Simulating a ready to play event to avoid breaking code path
  65886. if (this._readyToPlayCallback) {
  65887. window.setTimeout(function () {
  65888. if (_this._readyToPlayCallback) {
  65889. _this._readyToPlayCallback();
  65890. }
  65891. }, 1000);
  65892. }
  65893. }
  65894. }
  65895. }
  65896. catch (ex) {
  65897. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  65898. this._scene.mainSoundTrack.RemoveSound(this);
  65899. }
  65900. }
  65901. }
  65902. else {
  65903. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  65904. this._scene.mainSoundTrack.AddSound(this);
  65905. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  65906. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  65907. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  65908. }
  65909. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  65910. if (this._readyToPlayCallback) {
  65911. window.setTimeout(function () {
  65912. if (_this._readyToPlayCallback) {
  65913. _this._readyToPlayCallback();
  65914. }
  65915. }, 1000);
  65916. }
  65917. }
  65918. }
  65919. Sound.prototype.dispose = function () {
  65920. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  65921. if (this.isPlaying) {
  65922. this.stop();
  65923. }
  65924. this._isReadyToPlay = false;
  65925. if (this.soundTrackId === -1) {
  65926. this._scene.mainSoundTrack.RemoveSound(this);
  65927. }
  65928. else {
  65929. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  65930. }
  65931. if (this._soundGain) {
  65932. this._soundGain.disconnect();
  65933. this._soundGain = null;
  65934. }
  65935. if (this._soundPanner) {
  65936. this._soundPanner.disconnect();
  65937. this._soundPanner = null;
  65938. }
  65939. if (this._soundSource) {
  65940. this._soundSource.disconnect();
  65941. this._soundSource = null;
  65942. }
  65943. this._audioBuffer = null;
  65944. if (this._htmlAudioElement) {
  65945. this._htmlAudioElement.pause();
  65946. this._htmlAudioElement.src = "";
  65947. document.body.removeChild(this._htmlAudioElement);
  65948. }
  65949. if (this._streamingSource) {
  65950. this._streamingSource.disconnect();
  65951. }
  65952. if (this._connectedMesh && this._registerFunc) {
  65953. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  65954. this._connectedMesh = null;
  65955. }
  65956. }
  65957. };
  65958. Sound.prototype.isReady = function () {
  65959. return this._isReadyToPlay;
  65960. };
  65961. Sound.prototype._soundLoaded = function (audioData) {
  65962. var _this = this;
  65963. if (!BABYLON.Engine.audioEngine.audioContext) {
  65964. return;
  65965. }
  65966. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  65967. _this._audioBuffer = buffer;
  65968. _this._isReadyToPlay = true;
  65969. if (_this.autoplay) {
  65970. _this.play();
  65971. }
  65972. if (_this._readyToPlayCallback) {
  65973. _this._readyToPlayCallback();
  65974. }
  65975. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  65976. };
  65977. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  65978. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  65979. this._audioBuffer = audioBuffer;
  65980. this._isReadyToPlay = true;
  65981. }
  65982. };
  65983. Sound.prototype.updateOptions = function (options) {
  65984. if (options) {
  65985. this.loop = options.loop || this.loop;
  65986. this.maxDistance = options.maxDistance || this.maxDistance;
  65987. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  65988. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  65989. this.refDistance = options.refDistance || this.refDistance;
  65990. this.distanceModel = options.distanceModel || this.distanceModel;
  65991. this._playbackRate = options.playbackRate || this._playbackRate;
  65992. this._updateSpatialParameters();
  65993. if (this.isPlaying) {
  65994. if (this._streaming && this._htmlAudioElement) {
  65995. this._htmlAudioElement.playbackRate = this._playbackRate;
  65996. }
  65997. else {
  65998. if (this._soundSource) {
  65999. this._soundSource.playbackRate.value = this._playbackRate;
  66000. }
  66001. }
  66002. }
  66003. }
  66004. };
  66005. Sound.prototype._createSpatialParameters = function () {
  66006. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  66007. if (this._scene.headphone) {
  66008. this._panningModel = "HRTF";
  66009. }
  66010. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  66011. this._updateSpatialParameters();
  66012. this._soundPanner.connect(this._outputAudioNode);
  66013. this._inputAudioNode = this._soundPanner;
  66014. }
  66015. };
  66016. Sound.prototype._updateSpatialParameters = function () {
  66017. if (this.spatialSound && this._soundPanner) {
  66018. if (this.useCustomAttenuation) {
  66019. // Tricks to disable in a way embedded Web Audio attenuation
  66020. this._soundPanner.distanceModel = "linear";
  66021. this._soundPanner.maxDistance = Number.MAX_VALUE;
  66022. this._soundPanner.refDistance = 1;
  66023. this._soundPanner.rolloffFactor = 1;
  66024. this._soundPanner.panningModel = this._panningModel;
  66025. }
  66026. else {
  66027. this._soundPanner.distanceModel = this.distanceModel;
  66028. this._soundPanner.maxDistance = this.maxDistance;
  66029. this._soundPanner.refDistance = this.refDistance;
  66030. this._soundPanner.rolloffFactor = this.rolloffFactor;
  66031. this._soundPanner.panningModel = this._panningModel;
  66032. }
  66033. }
  66034. };
  66035. Sound.prototype.switchPanningModelToHRTF = function () {
  66036. this._panningModel = "HRTF";
  66037. this._switchPanningModel();
  66038. };
  66039. Sound.prototype.switchPanningModelToEqualPower = function () {
  66040. this._panningModel = "equalpower";
  66041. this._switchPanningModel();
  66042. };
  66043. Sound.prototype._switchPanningModel = function () {
  66044. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  66045. this._soundPanner.panningModel = this._panningModel;
  66046. }
  66047. };
  66048. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  66049. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  66050. if (this._isOutputConnected) {
  66051. this._outputAudioNode.disconnect();
  66052. }
  66053. this._outputAudioNode.connect(soundTrackAudioNode);
  66054. this._isOutputConnected = true;
  66055. }
  66056. };
  66057. /**
  66058. * Transform this sound into a directional source
  66059. * @param coneInnerAngle Size of the inner cone in degree
  66060. * @param coneOuterAngle Size of the outer cone in degree
  66061. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  66062. */
  66063. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  66064. if (coneOuterAngle < coneInnerAngle) {
  66065. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  66066. return;
  66067. }
  66068. this._coneInnerAngle = coneInnerAngle;
  66069. this._coneOuterAngle = coneOuterAngle;
  66070. this._coneOuterGain = coneOuterGain;
  66071. this._isDirectional = true;
  66072. if (this.isPlaying && this.loop) {
  66073. this.stop();
  66074. this.play();
  66075. }
  66076. };
  66077. Object.defineProperty(Sound.prototype, "directionalConeInnerAngle", {
  66078. /**
  66079. * Gets or sets the inner angle for the directional cone.
  66080. */
  66081. get: function () {
  66082. return this._coneInnerAngle;
  66083. },
  66084. /**
  66085. * Gets or sets the inner angle for the directional cone.
  66086. */
  66087. set: function (value) {
  66088. if (value != this._coneInnerAngle) {
  66089. if (this._coneOuterAngle < value) {
  66090. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  66091. return;
  66092. }
  66093. this._coneInnerAngle = value;
  66094. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  66095. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  66096. }
  66097. }
  66098. },
  66099. enumerable: true,
  66100. configurable: true
  66101. });
  66102. Object.defineProperty(Sound.prototype, "directionalConeOuterAngle", {
  66103. /**
  66104. * Gets or sets the outer angle for the directional cone.
  66105. */
  66106. get: function () {
  66107. return this._coneOuterAngle;
  66108. },
  66109. /**
  66110. * Gets or sets the outer angle for the directional cone.
  66111. */
  66112. set: function (value) {
  66113. if (value != this._coneOuterAngle) {
  66114. if (value < this._coneInnerAngle) {
  66115. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  66116. return;
  66117. }
  66118. this._coneOuterAngle = value;
  66119. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  66120. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  66121. }
  66122. }
  66123. },
  66124. enumerable: true,
  66125. configurable: true
  66126. });
  66127. Sound.prototype.setPosition = function (newPosition) {
  66128. this._position = newPosition;
  66129. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner && !isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  66130. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  66131. }
  66132. };
  66133. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  66134. this._localDirection = newLocalDirection;
  66135. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  66136. this._updateDirection();
  66137. }
  66138. };
  66139. Sound.prototype._updateDirection = function () {
  66140. if (!this._connectedMesh || !this._soundPanner) {
  66141. return;
  66142. }
  66143. var mat = this._connectedMesh.getWorldMatrix();
  66144. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  66145. direction.normalize();
  66146. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  66147. };
  66148. Sound.prototype.updateDistanceFromListener = function () {
  66149. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  66150. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  66151. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  66152. }
  66153. };
  66154. Sound.prototype.setAttenuationFunction = function (callback) {
  66155. this._customAttenuationFunction = callback;
  66156. };
  66157. /**
  66158. * Play the sound
  66159. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  66160. * @param offset (optional) Start the sound setting it at a specific time
  66161. */
  66162. Sound.prototype.play = function (time, offset) {
  66163. var _this = this;
  66164. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  66165. try {
  66166. if (this._startOffset < 0) {
  66167. time = -this._startOffset;
  66168. this._startOffset = 0;
  66169. }
  66170. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  66171. if (!this._soundSource || !this._streamingSource) {
  66172. if (this.spatialSound && this._soundPanner) {
  66173. if (!isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  66174. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  66175. }
  66176. if (this._isDirectional) {
  66177. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  66178. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  66179. this._soundPanner.coneOuterGain = this._coneOuterGain;
  66180. if (this._connectedMesh) {
  66181. this._updateDirection();
  66182. }
  66183. else {
  66184. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  66185. }
  66186. }
  66187. }
  66188. }
  66189. if (this._streaming) {
  66190. if (!this._streamingSource) {
  66191. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  66192. this._htmlAudioElement.onended = function () { _this._onended(); };
  66193. this._htmlAudioElement.playbackRate = this._playbackRate;
  66194. }
  66195. this._streamingSource.disconnect();
  66196. this._streamingSource.connect(this._inputAudioNode);
  66197. if (this._htmlAudioElement) {
  66198. this._htmlAudioElement.play();
  66199. }
  66200. }
  66201. else {
  66202. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  66203. this._soundSource.buffer = this._audioBuffer;
  66204. this._soundSource.connect(this._inputAudioNode);
  66205. this._soundSource.loop = this.loop;
  66206. this._soundSource.playbackRate.value = this._playbackRate;
  66207. this._soundSource.onended = function () { _this._onended(); };
  66208. if (this._soundSource.buffer) {
  66209. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  66210. }
  66211. }
  66212. this._startTime = startTime;
  66213. this.isPlaying = true;
  66214. this.isPaused = false;
  66215. }
  66216. catch (ex) {
  66217. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  66218. }
  66219. }
  66220. };
  66221. Sound.prototype._onended = function () {
  66222. this.isPlaying = false;
  66223. if (this.onended) {
  66224. this.onended();
  66225. }
  66226. this.onEndedObservable.notifyObservers(this);
  66227. };
  66228. /**
  66229. * Stop the sound
  66230. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  66231. */
  66232. Sound.prototype.stop = function (time) {
  66233. if (this.isPlaying) {
  66234. if (this._streaming) {
  66235. if (this._htmlAudioElement) {
  66236. this._htmlAudioElement.pause();
  66237. // Test needed for Firefox or it will generate an Invalid State Error
  66238. if (this._htmlAudioElement.currentTime > 0) {
  66239. this._htmlAudioElement.currentTime = 0;
  66240. }
  66241. }
  66242. else {
  66243. this._streamingSource.disconnect();
  66244. }
  66245. }
  66246. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  66247. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  66248. this._soundSource.stop(stopTime);
  66249. this._soundSource.onended = function () { };
  66250. if (!this.isPaused) {
  66251. this._startOffset = 0;
  66252. }
  66253. }
  66254. this.isPlaying = false;
  66255. }
  66256. };
  66257. Sound.prototype.pause = function () {
  66258. if (this.isPlaying) {
  66259. this.isPaused = true;
  66260. if (this._streaming) {
  66261. if (this._htmlAudioElement) {
  66262. this._htmlAudioElement.pause();
  66263. }
  66264. else {
  66265. this._streamingSource.disconnect();
  66266. }
  66267. }
  66268. else if (BABYLON.Engine.audioEngine.audioContext) {
  66269. this.stop(0);
  66270. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  66271. }
  66272. }
  66273. };
  66274. Sound.prototype.setVolume = function (newVolume, time) {
  66275. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  66276. if (time && BABYLON.Engine.audioEngine.audioContext) {
  66277. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  66278. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  66279. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  66280. }
  66281. else {
  66282. this._soundGain.gain.value = newVolume;
  66283. }
  66284. }
  66285. this._volume = newVolume;
  66286. };
  66287. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  66288. this._playbackRate = newPlaybackRate;
  66289. if (this.isPlaying) {
  66290. if (this._streaming && this._htmlAudioElement) {
  66291. this._htmlAudioElement.playbackRate = this._playbackRate;
  66292. }
  66293. else if (this._soundSource) {
  66294. this._soundSource.playbackRate.value = this._playbackRate;
  66295. }
  66296. }
  66297. };
  66298. Sound.prototype.getVolume = function () {
  66299. return this._volume;
  66300. };
  66301. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  66302. var _this = this;
  66303. if (this._connectedMesh && this._registerFunc) {
  66304. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  66305. this._registerFunc = null;
  66306. }
  66307. this._connectedMesh = meshToConnectTo;
  66308. if (!this.spatialSound) {
  66309. this.spatialSound = true;
  66310. this._createSpatialParameters();
  66311. if (this.isPlaying && this.loop) {
  66312. this.stop();
  66313. this.play();
  66314. }
  66315. }
  66316. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  66317. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  66318. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  66319. };
  66320. Sound.prototype.detachFromMesh = function () {
  66321. if (this._connectedMesh && this._registerFunc) {
  66322. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  66323. this._registerFunc = null;
  66324. this._connectedMesh = null;
  66325. }
  66326. };
  66327. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  66328. if (!node.getBoundingInfo) {
  66329. return;
  66330. }
  66331. var mesh = node;
  66332. if (this._positionInEmitterSpace) {
  66333. mesh.worldMatrixFromCache.invertToRef(BABYLON.Tmp.Matrix[0]);
  66334. this.setPosition(BABYLON.Tmp.Matrix[0].getTranslation());
  66335. }
  66336. else {
  66337. var boundingInfo = mesh.getBoundingInfo();
  66338. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  66339. }
  66340. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  66341. this._updateDirection();
  66342. }
  66343. };
  66344. Sound.prototype.clone = function () {
  66345. var _this = this;
  66346. if (!this._streaming) {
  66347. var setBufferAndRun = function () {
  66348. if (_this._isReadyToPlay) {
  66349. clonedSound._audioBuffer = _this.getAudioBuffer();
  66350. clonedSound._isReadyToPlay = true;
  66351. if (clonedSound.autoplay) {
  66352. clonedSound.play();
  66353. }
  66354. }
  66355. else {
  66356. window.setTimeout(setBufferAndRun, 300);
  66357. }
  66358. };
  66359. var currentOptions = {
  66360. autoplay: this.autoplay, loop: this.loop,
  66361. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  66362. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  66363. refDistance: this.refDistance, distanceModel: this.distanceModel
  66364. };
  66365. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  66366. if (this.useCustomAttenuation) {
  66367. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  66368. }
  66369. clonedSound.setPosition(this._position);
  66370. clonedSound.setPlaybackRate(this._playbackRate);
  66371. setBufferAndRun();
  66372. return clonedSound;
  66373. }
  66374. // Can't clone a streaming sound
  66375. else {
  66376. return null;
  66377. }
  66378. };
  66379. Sound.prototype.getAudioBuffer = function () {
  66380. return this._audioBuffer;
  66381. };
  66382. Sound.prototype.serialize = function () {
  66383. var serializationObject = {
  66384. name: this.name,
  66385. url: this.name,
  66386. autoplay: this.autoplay,
  66387. loop: this.loop,
  66388. volume: this._volume,
  66389. spatialSound: this.spatialSound,
  66390. maxDistance: this.maxDistance,
  66391. rolloffFactor: this.rolloffFactor,
  66392. refDistance: this.refDistance,
  66393. distanceModel: this.distanceModel,
  66394. playbackRate: this._playbackRate,
  66395. panningModel: this._panningModel,
  66396. soundTrackId: this.soundTrackId
  66397. };
  66398. if (this.spatialSound) {
  66399. if (this._connectedMesh)
  66400. serializationObject.connectedMeshId = this._connectedMesh.id;
  66401. serializationObject.position = this._position.asArray();
  66402. serializationObject.refDistance = this.refDistance;
  66403. serializationObject.distanceModel = this.distanceModel;
  66404. serializationObject.isDirectional = this._isDirectional;
  66405. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  66406. serializationObject.coneInnerAngle = this._coneInnerAngle;
  66407. serializationObject.coneOuterAngle = this._coneOuterAngle;
  66408. serializationObject.coneOuterGain = this._coneOuterGain;
  66409. }
  66410. return serializationObject;
  66411. };
  66412. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  66413. var soundName = parsedSound.name;
  66414. var soundUrl;
  66415. if (parsedSound.url) {
  66416. soundUrl = rootUrl + parsedSound.url;
  66417. }
  66418. else {
  66419. soundUrl = rootUrl + soundName;
  66420. }
  66421. var options = {
  66422. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  66423. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  66424. rolloffFactor: parsedSound.rolloffFactor,
  66425. refDistance: parsedSound.refDistance,
  66426. distanceModel: parsedSound.distanceModel,
  66427. playbackRate: parsedSound.playbackRate
  66428. };
  66429. var newSound;
  66430. if (!sourceSound) {
  66431. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  66432. scene._addPendingData(newSound);
  66433. }
  66434. else {
  66435. var setBufferAndRun = function () {
  66436. if (sourceSound._isReadyToPlay) {
  66437. newSound._audioBuffer = sourceSound.getAudioBuffer();
  66438. newSound._isReadyToPlay = true;
  66439. if (newSound.autoplay) {
  66440. newSound.play();
  66441. }
  66442. }
  66443. else {
  66444. window.setTimeout(setBufferAndRun, 300);
  66445. }
  66446. };
  66447. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  66448. setBufferAndRun();
  66449. }
  66450. if (parsedSound.position) {
  66451. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  66452. newSound.setPosition(soundPosition);
  66453. }
  66454. if (parsedSound.isDirectional) {
  66455. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  66456. if (parsedSound.localDirectionToMesh) {
  66457. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  66458. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  66459. }
  66460. }
  66461. if (parsedSound.connectedMeshId) {
  66462. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  66463. if (connectedMesh) {
  66464. newSound.attachToMesh(connectedMesh);
  66465. }
  66466. }
  66467. return newSound;
  66468. };
  66469. return Sound;
  66470. }());
  66471. BABYLON.Sound = Sound;
  66472. })(BABYLON || (BABYLON = {}));
  66473. //# sourceMappingURL=babylon.sound.js.map
  66474. var BABYLON;
  66475. (function (BABYLON) {
  66476. var SoundTrack = /** @class */ (function () {
  66477. function SoundTrack(scene, options) {
  66478. this.id = -1;
  66479. this._isMainTrack = false;
  66480. this._isInitialized = false;
  66481. this._scene = scene;
  66482. this.soundCollection = new Array();
  66483. this._options = options;
  66484. if (!this._isMainTrack) {
  66485. this._scene.soundTracks.push(this);
  66486. this.id = this._scene.soundTracks.length - 1;
  66487. }
  66488. }
  66489. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  66490. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  66491. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  66492. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  66493. if (this._options) {
  66494. if (this._options.volume) {
  66495. this._outputAudioNode.gain.value = this._options.volume;
  66496. }
  66497. if (this._options.mainTrack) {
  66498. this._isMainTrack = this._options.mainTrack;
  66499. }
  66500. }
  66501. this._isInitialized = true;
  66502. }
  66503. };
  66504. SoundTrack.prototype.dispose = function () {
  66505. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  66506. if (this._connectedAnalyser) {
  66507. this._connectedAnalyser.stopDebugCanvas();
  66508. }
  66509. while (this.soundCollection.length) {
  66510. this.soundCollection[0].dispose();
  66511. }
  66512. if (this._outputAudioNode) {
  66513. this._outputAudioNode.disconnect();
  66514. }
  66515. this._outputAudioNode = null;
  66516. }
  66517. };
  66518. SoundTrack.prototype.AddSound = function (sound) {
  66519. if (!this._isInitialized) {
  66520. this._initializeSoundTrackAudioGraph();
  66521. }
  66522. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  66523. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  66524. }
  66525. if (sound.soundTrackId) {
  66526. if (sound.soundTrackId === -1) {
  66527. this._scene.mainSoundTrack.RemoveSound(sound);
  66528. }
  66529. else {
  66530. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  66531. }
  66532. }
  66533. this.soundCollection.push(sound);
  66534. sound.soundTrackId = this.id;
  66535. };
  66536. SoundTrack.prototype.RemoveSound = function (sound) {
  66537. var index = this.soundCollection.indexOf(sound);
  66538. if (index !== -1) {
  66539. this.soundCollection.splice(index, 1);
  66540. }
  66541. };
  66542. SoundTrack.prototype.setVolume = function (newVolume) {
  66543. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  66544. this._outputAudioNode.gain.value = newVolume;
  66545. }
  66546. };
  66547. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  66548. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  66549. for (var i = 0; i < this.soundCollection.length; i++) {
  66550. this.soundCollection[i].switchPanningModelToHRTF();
  66551. }
  66552. }
  66553. };
  66554. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  66555. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  66556. for (var i = 0; i < this.soundCollection.length; i++) {
  66557. this.soundCollection[i].switchPanningModelToEqualPower();
  66558. }
  66559. }
  66560. };
  66561. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  66562. if (this._connectedAnalyser) {
  66563. this._connectedAnalyser.stopDebugCanvas();
  66564. }
  66565. this._connectedAnalyser = analyser;
  66566. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  66567. this._outputAudioNode.disconnect();
  66568. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  66569. }
  66570. };
  66571. return SoundTrack;
  66572. }());
  66573. BABYLON.SoundTrack = SoundTrack;
  66574. })(BABYLON || (BABYLON = {}));
  66575. //# sourceMappingURL=babylon.soundtrack.js.map
  66576. var BABYLON;
  66577. (function (BABYLON) {
  66578. /**
  66579. * Class used to work with sound analyzer using fast fourier transform (FFT)
  66580. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  66581. */
  66582. var Analyser = /** @class */ (function () {
  66583. /**
  66584. * Creates a new analyser
  66585. * @param scene defines hosting scene
  66586. */
  66587. function Analyser(scene) {
  66588. /**
  66589. * Gets or sets the smoothing
  66590. * @ignorenaming
  66591. */
  66592. this.SMOOTHING = 0.75;
  66593. /**
  66594. * Gets or sets the FFT table size
  66595. * @ignorenaming
  66596. */
  66597. this.FFT_SIZE = 512;
  66598. /**
  66599. * Gets or sets the bar graph amplitude
  66600. * @ignorenaming
  66601. */
  66602. this.BARGRAPHAMPLITUDE = 256;
  66603. /**
  66604. * Gets or sets the position of the debug canvas
  66605. * @ignorenaming
  66606. */
  66607. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  66608. /**
  66609. * Gets or sets the debug canvas size
  66610. * @ignorenaming
  66611. */
  66612. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  66613. this._scene = scene;
  66614. this._audioEngine = BABYLON.Engine.audioEngine;
  66615. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  66616. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  66617. this._webAudioAnalyser.minDecibels = -140;
  66618. this._webAudioAnalyser.maxDecibels = 0;
  66619. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  66620. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  66621. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  66622. }
  66623. }
  66624. /**
  66625. * Get the number of data values you will have to play with for the visualization
  66626. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  66627. * @returns a number
  66628. */
  66629. Analyser.prototype.getFrequencyBinCount = function () {
  66630. if (this._audioEngine.canUseWebAudio) {
  66631. return this._webAudioAnalyser.frequencyBinCount;
  66632. }
  66633. else {
  66634. return 0;
  66635. }
  66636. };
  66637. /**
  66638. * Gets the current frequency data as a byte array
  66639. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  66640. * @returns a Uint8Array
  66641. */
  66642. Analyser.prototype.getByteFrequencyData = function () {
  66643. if (this._audioEngine.canUseWebAudio) {
  66644. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  66645. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  66646. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  66647. }
  66648. return this._byteFreqs;
  66649. };
  66650. /**
  66651. * Gets the current waveform as a byte array
  66652. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  66653. * @returns a Uint8Array
  66654. */
  66655. Analyser.prototype.getByteTimeDomainData = function () {
  66656. if (this._audioEngine.canUseWebAudio) {
  66657. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  66658. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  66659. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  66660. }
  66661. return this._byteTime;
  66662. };
  66663. /**
  66664. * Gets the current frequency data as a float array
  66665. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  66666. * @returns a Float32Array
  66667. */
  66668. Analyser.prototype.getFloatFrequencyData = function () {
  66669. if (this._audioEngine.canUseWebAudio) {
  66670. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  66671. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  66672. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  66673. }
  66674. return this._floatFreqs;
  66675. };
  66676. /**
  66677. * Renders the debug canvas
  66678. */
  66679. Analyser.prototype.drawDebugCanvas = function () {
  66680. var _this = this;
  66681. if (this._audioEngine.canUseWebAudio) {
  66682. if (!this._debugCanvas) {
  66683. this._debugCanvas = document.createElement("canvas");
  66684. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  66685. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  66686. this._debugCanvas.style.position = "absolute";
  66687. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  66688. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  66689. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  66690. document.body.appendChild(this._debugCanvas);
  66691. this._registerFunc = function () {
  66692. _this.drawDebugCanvas();
  66693. };
  66694. this._scene.registerBeforeRender(this._registerFunc);
  66695. }
  66696. if (this._registerFunc && this._debugCanvasContext) {
  66697. var workingArray = this.getByteFrequencyData();
  66698. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  66699. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  66700. // Draw the frequency domain chart.
  66701. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  66702. var value = workingArray[i];
  66703. var percent = value / this.BARGRAPHAMPLITUDE;
  66704. var height = this.DEBUGCANVASSIZE.height * percent;
  66705. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  66706. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  66707. var hue = i / this.getFrequencyBinCount() * 360;
  66708. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  66709. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  66710. }
  66711. }
  66712. }
  66713. };
  66714. /**
  66715. * Stops rendering the debug canvas and removes it
  66716. */
  66717. Analyser.prototype.stopDebugCanvas = function () {
  66718. if (this._debugCanvas) {
  66719. if (this._registerFunc) {
  66720. this._scene.unregisterBeforeRender(this._registerFunc);
  66721. this._registerFunc = null;
  66722. }
  66723. document.body.removeChild(this._debugCanvas);
  66724. this._debugCanvas = null;
  66725. this._debugCanvasContext = null;
  66726. }
  66727. };
  66728. /**
  66729. * Connects two audio nodes
  66730. * @param inputAudioNode defines first node to connect
  66731. * @param outputAudioNode defines second node to connect
  66732. */
  66733. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  66734. if (this._audioEngine.canUseWebAudio) {
  66735. inputAudioNode.connect(this._webAudioAnalyser);
  66736. this._webAudioAnalyser.connect(outputAudioNode);
  66737. }
  66738. };
  66739. /**
  66740. * Releases all associated resources
  66741. */
  66742. Analyser.prototype.dispose = function () {
  66743. if (this._audioEngine.canUseWebAudio) {
  66744. this._webAudioAnalyser.disconnect();
  66745. }
  66746. };
  66747. return Analyser;
  66748. }());
  66749. BABYLON.Analyser = Analyser;
  66750. })(BABYLON || (BABYLON = {}));
  66751. //# sourceMappingURL=babylon.analyser.js.map
  66752. var BABYLON;
  66753. (function (BABYLON) {
  66754. /**
  66755. * Wraps one or more Sound objects and selects one with random weight for playback.
  66756. */
  66757. var WeightedSound = /** @class */ (function () {
  66758. /**
  66759. * Creates a new WeightedSound from the list of sounds given.
  66760. * @param loop When true a Sound will be selected and played when the current playing Sound completes.
  66761. * @param sounds Array of Sounds that will be selected from.
  66762. * @param weights Array of number values for selection weights; length must equal sounds, values will be normalized to 1
  66763. */
  66764. function WeightedSound(loop, sounds, weights) {
  66765. var _this = this;
  66766. /** When true a Sound will be selected and played when the current playing Sound completes. */
  66767. this.loop = false;
  66768. this._coneInnerAngle = 360;
  66769. this._coneOuterAngle = 360;
  66770. this._volume = 1;
  66771. /** A Sound is currently playing. */
  66772. this.isPlaying = false;
  66773. /** A Sound is currently paused. */
  66774. this.isPaused = false;
  66775. this._sounds = [];
  66776. this._weights = [];
  66777. if (sounds.length !== weights.length) {
  66778. throw new Error('Sounds length does not equal weights length');
  66779. }
  66780. this.loop = loop;
  66781. this._weights = weights;
  66782. // Normalize the weights
  66783. var weightSum = 0;
  66784. for (var _i = 0, weights_1 = weights; _i < weights_1.length; _i++) {
  66785. var weight = weights_1[_i];
  66786. weightSum += weight;
  66787. }
  66788. var invWeightSum = weightSum > 0 ? 1 / weightSum : 0;
  66789. for (var i = 0; i < this._weights.length; i++) {
  66790. this._weights[i] *= invWeightSum;
  66791. }
  66792. this._sounds = sounds;
  66793. for (var _a = 0, _b = this._sounds; _a < _b.length; _a++) {
  66794. var sound = _b[_a];
  66795. sound.onEndedObservable.add(function () { _this._onended(); });
  66796. }
  66797. }
  66798. Object.defineProperty(WeightedSound.prototype, "directionalConeInnerAngle", {
  66799. /**
  66800. * The size of cone in degrees for a directional sound in which there will be no attenuation.
  66801. */
  66802. get: function () {
  66803. return this._coneInnerAngle;
  66804. },
  66805. /**
  66806. * The size of cone in degress for a directional sound in which there will be no attenuation.
  66807. */
  66808. set: function (value) {
  66809. if (value !== this._coneInnerAngle) {
  66810. if (this._coneOuterAngle < value) {
  66811. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  66812. return;
  66813. }
  66814. this._coneInnerAngle = value;
  66815. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  66816. var sound = _a[_i];
  66817. sound.directionalConeInnerAngle = value;
  66818. }
  66819. }
  66820. },
  66821. enumerable: true,
  66822. configurable: true
  66823. });
  66824. Object.defineProperty(WeightedSound.prototype, "directionalConeOuterAngle", {
  66825. /**
  66826. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  66827. * Listener angles between innerAngle and outerAngle will falloff linearly.
  66828. */
  66829. get: function () {
  66830. return this._coneOuterAngle;
  66831. },
  66832. /**
  66833. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  66834. * Listener angles between innerAngle and outerAngle will falloff linearly.
  66835. */
  66836. set: function (value) {
  66837. if (value !== this._coneOuterAngle) {
  66838. if (value < this._coneInnerAngle) {
  66839. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  66840. return;
  66841. }
  66842. this._coneOuterAngle = value;
  66843. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  66844. var sound = _a[_i];
  66845. sound.directionalConeOuterAngle = value;
  66846. }
  66847. }
  66848. },
  66849. enumerable: true,
  66850. configurable: true
  66851. });
  66852. Object.defineProperty(WeightedSound.prototype, "volume", {
  66853. /**
  66854. * Playback volume.
  66855. */
  66856. get: function () {
  66857. return this._volume;
  66858. },
  66859. /**
  66860. * Playback volume.
  66861. */
  66862. set: function (value) {
  66863. if (value !== this._volume) {
  66864. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  66865. var sound = _a[_i];
  66866. sound.setVolume(value);
  66867. }
  66868. }
  66869. },
  66870. enumerable: true,
  66871. configurable: true
  66872. });
  66873. WeightedSound.prototype._onended = function () {
  66874. if (this._currentIndex !== undefined) {
  66875. this._sounds[this._currentIndex].autoplay = false;
  66876. }
  66877. if (this.loop && this.isPlaying) {
  66878. this.play();
  66879. }
  66880. else {
  66881. this.isPlaying = false;
  66882. }
  66883. };
  66884. /**
  66885. * Suspend playback
  66886. */
  66887. WeightedSound.prototype.pause = function () {
  66888. this.isPaused = true;
  66889. if (this._currentIndex !== undefined) {
  66890. this._sounds[this._currentIndex].pause();
  66891. }
  66892. };
  66893. /**
  66894. * Stop playback
  66895. */
  66896. WeightedSound.prototype.stop = function () {
  66897. this.isPlaying = false;
  66898. if (this._currentIndex !== undefined) {
  66899. this._sounds[this._currentIndex].stop();
  66900. }
  66901. };
  66902. /**
  66903. * Start playback.
  66904. * @param startOffset Position the clip head at a specific time in seconds.
  66905. */
  66906. WeightedSound.prototype.play = function (startOffset) {
  66907. if (!this.isPaused) {
  66908. this.stop();
  66909. var randomValue = Math.random();
  66910. var total = 0;
  66911. for (var i = 0; i < this._weights.length; i++) {
  66912. total += this._weights[i];
  66913. if (randomValue <= total) {
  66914. this._currentIndex = i;
  66915. break;
  66916. }
  66917. }
  66918. }
  66919. var sound = this._sounds[this._currentIndex];
  66920. if (sound.isReady()) {
  66921. sound.play(0, this.isPaused ? undefined : startOffset);
  66922. }
  66923. else {
  66924. sound.autoplay = true;
  66925. }
  66926. this.isPlaying = true;
  66927. this.isPaused = false;
  66928. };
  66929. return WeightedSound;
  66930. }());
  66931. BABYLON.WeightedSound = WeightedSound;
  66932. })(BABYLON || (BABYLON = {}));
  66933. //# sourceMappingURL=babylon.weightedsound.js.map
  66934. var BABYLON;
  66935. (function (BABYLON) {
  66936. var CubeTexture = /** @class */ (function (_super) {
  66937. __extends(CubeTexture, _super);
  66938. /**
  66939. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  66940. * as prefiltered data.
  66941. * @param rootUrl defines the url of the texture or the root name of the six images
  66942. * @param scene defines the scene the texture is attached to
  66943. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  66944. * @param noMipmap defines if mipmaps should be created or not
  66945. * @param files defines the six files to load for the different faces
  66946. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  66947. * @param onError defines a callback triggered in case of error during load
  66948. * @param format defines the internal format to use for the texture once loaded
  66949. * @param prefiltered defines whether or not the texture is created from prefiltered data
  66950. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  66951. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  66952. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  66953. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  66954. * @return the cube texture
  66955. */
  66956. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) {
  66957. if (extensions === void 0) { extensions = null; }
  66958. if (noMipmap === void 0) { noMipmap = false; }
  66959. if (files === void 0) { files = null; }
  66960. if (onLoad === void 0) { onLoad = null; }
  66961. if (onError === void 0) { onError = null; }
  66962. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  66963. if (prefiltered === void 0) { prefiltered = false; }
  66964. if (forcedExtension === void 0) { forcedExtension = null; }
  66965. if (createPolynomials === void 0) { createPolynomials = false; }
  66966. if (lodScale === void 0) { lodScale = 0.8; }
  66967. if (lodOffset === void 0) { lodOffset = 0; }
  66968. var _this = _super.call(this, scene) || this;
  66969. /**
  66970. * Gets or sets the center of the bounding box associated with the cube texture
  66971. * It must define where the camera used to render the texture was set
  66972. */
  66973. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  66974. _this._rotationY = 0;
  66975. /** @hidden */
  66976. _this._prefiltered = false;
  66977. _this.name = rootUrl;
  66978. _this.url = rootUrl;
  66979. _this._noMipmap = noMipmap;
  66980. _this.hasAlpha = false;
  66981. _this._format = format;
  66982. _this.isCube = true;
  66983. _this._textureMatrix = BABYLON.Matrix.Identity();
  66984. _this._createPolynomials = createPolynomials;
  66985. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  66986. if (!rootUrl && !files) {
  66987. return _this;
  66988. }
  66989. var lastDot = rootUrl.lastIndexOf(".");
  66990. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  66991. var isDDS = (extension === ".dds");
  66992. var isEnv = (extension === ".env");
  66993. if (isEnv) {
  66994. _this.gammaSpace = false;
  66995. _this._prefiltered = false;
  66996. }
  66997. else {
  66998. _this._prefiltered = prefiltered;
  66999. if (prefiltered) {
  67000. _this.gammaSpace = false;
  67001. }
  67002. }
  67003. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  67004. if (!files) {
  67005. if (!isEnv && !isDDS && !extensions) {
  67006. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  67007. }
  67008. files = [];
  67009. if (extensions) {
  67010. for (var index = 0; index < extensions.length; index++) {
  67011. files.push(rootUrl + extensions[index]);
  67012. }
  67013. }
  67014. }
  67015. _this._files = files;
  67016. if (!_this._texture) {
  67017. if (!scene.useDelayedTextureLoading) {
  67018. if (prefiltered) {
  67019. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  67020. }
  67021. else {
  67022. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset);
  67023. }
  67024. }
  67025. else {
  67026. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  67027. }
  67028. }
  67029. else if (onLoad) {
  67030. if (_this._texture.isReady) {
  67031. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  67032. }
  67033. else {
  67034. _this._texture.onLoadedObservable.add(onLoad);
  67035. }
  67036. }
  67037. return _this;
  67038. }
  67039. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  67040. get: function () {
  67041. return this._boundingBoxSize;
  67042. },
  67043. /**
  67044. * Gets or sets the size of the bounding box associated with the cube texture
  67045. * When defined, the cubemap will switch to local mode
  67046. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  67047. * @example https://www.babylonjs-playground.com/#RNASML
  67048. */
  67049. set: function (value) {
  67050. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  67051. return;
  67052. }
  67053. this._boundingBoxSize = value;
  67054. var scene = this.getScene();
  67055. if (scene) {
  67056. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  67057. }
  67058. },
  67059. enumerable: true,
  67060. configurable: true
  67061. });
  67062. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  67063. /**
  67064. * Gets texture matrix rotation angle around Y axis radians.
  67065. */
  67066. get: function () {
  67067. return this._rotationY;
  67068. },
  67069. /**
  67070. * Sets texture matrix rotation angle around Y axis in radians.
  67071. */
  67072. set: function (value) {
  67073. this._rotationY = value;
  67074. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  67075. },
  67076. enumerable: true,
  67077. configurable: true
  67078. });
  67079. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  67080. var rootUrlKey = "";
  67081. files.forEach(function (url) { return rootUrlKey += url; });
  67082. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  67083. };
  67084. /**
  67085. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  67086. * @param url defines the url of the prefiltered texture
  67087. * @param scene defines the scene the texture is attached to
  67088. * @param forcedExtension defines the extension of the file if different from the url
  67089. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  67090. * @return the prefiltered texture
  67091. */
  67092. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  67093. if (forcedExtension === void 0) { forcedExtension = null; }
  67094. if (createPolynomials === void 0) { createPolynomials = true; }
  67095. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  67096. };
  67097. // Methods
  67098. CubeTexture.prototype.delayLoad = function () {
  67099. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  67100. return;
  67101. }
  67102. var scene = this.getScene();
  67103. if (!scene) {
  67104. return;
  67105. }
  67106. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  67107. this._texture = this._getFromCache(this.url, this._noMipmap);
  67108. if (!this._texture) {
  67109. if (this._prefiltered) {
  67110. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  67111. }
  67112. else {
  67113. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  67114. }
  67115. }
  67116. };
  67117. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  67118. return this._textureMatrix;
  67119. };
  67120. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  67121. this._textureMatrix = value;
  67122. };
  67123. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  67124. var texture = BABYLON.SerializationHelper.Parse(function () {
  67125. var prefiltered = false;
  67126. if (parsedTexture.prefiltered) {
  67127. prefiltered = parsedTexture.prefiltered;
  67128. }
  67129. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  67130. }, parsedTexture, scene);
  67131. // Local Cubemaps
  67132. if (parsedTexture.boundingBoxPosition) {
  67133. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  67134. }
  67135. if (parsedTexture.boundingBoxSize) {
  67136. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  67137. }
  67138. // Animations
  67139. if (parsedTexture.animations) {
  67140. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  67141. var parsedAnimation = parsedTexture.animations[animationIndex];
  67142. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  67143. }
  67144. }
  67145. return texture;
  67146. };
  67147. CubeTexture.prototype.clone = function () {
  67148. var _this = this;
  67149. return BABYLON.SerializationHelper.Clone(function () {
  67150. var scene = _this.getScene();
  67151. if (!scene) {
  67152. return _this;
  67153. }
  67154. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  67155. }, this);
  67156. };
  67157. __decorate([
  67158. BABYLON.serialize("rotationY")
  67159. ], CubeTexture.prototype, "rotationY", null);
  67160. return CubeTexture;
  67161. }(BABYLON.BaseTexture));
  67162. BABYLON.CubeTexture = CubeTexture;
  67163. })(BABYLON || (BABYLON = {}));
  67164. //# sourceMappingURL=babylon.cubeTexture.js.map
  67165. var BABYLON;
  67166. (function (BABYLON) {
  67167. /**
  67168. * Raw cube texture where the raw buffers are passed in
  67169. */
  67170. var RawCubeTexture = /** @class */ (function (_super) {
  67171. __extends(RawCubeTexture, _super);
  67172. /**
  67173. * Creates a cube texture where the raw buffers are passed in.
  67174. * @param scene defines the scene the texture is attached to
  67175. * @param data defines the array of data to use to create each face
  67176. * @param size defines the size of the textures
  67177. * @param format defines the format of the data
  67178. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  67179. * @param generateMipMaps defines if the engine should generate the mip levels
  67180. * @param invertY defines if data must be stored with Y axis inverted
  67181. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  67182. * @param compression defines the compression used (null by default)
  67183. */
  67184. function RawCubeTexture(scene, data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  67185. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  67186. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67187. if (generateMipMaps === void 0) { generateMipMaps = false; }
  67188. if (invertY === void 0) { invertY = false; }
  67189. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67190. if (compression === void 0) { compression = null; }
  67191. var _this = _super.call(this, "", scene) || this;
  67192. _this._texture = scene.getEngine().createRawCubeTexture(data, size, format, type, generateMipMaps, invertY, samplingMode, compression);
  67193. return _this;
  67194. }
  67195. /**
  67196. * Updates the raw cube texture.
  67197. * @param data defines the data to store
  67198. * @param format defines the data format
  67199. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  67200. * @param invertY defines if data must be stored with Y axis inverted
  67201. * @param compression defines the compression used (null by default)
  67202. * @param level defines which level of the texture to update
  67203. */
  67204. RawCubeTexture.prototype.update = function (data, format, type, invertY, compression, level) {
  67205. if (compression === void 0) { compression = null; }
  67206. if (level === void 0) { level = 0; }
  67207. this._texture.getEngine().updateRawCubeTexture(this._texture, data, format, type, invertY, compression);
  67208. };
  67209. /**
  67210. * Updates a raw cube texture with RGBD encoded data.
  67211. * @param data defines the array of data [mipmap][face] to use to create each face
  67212. * @param sphericalPolynomial defines the spherical polynomial for irradiance
  67213. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  67214. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  67215. * @returns a promsie that resolves when the operation is complete
  67216. */
  67217. RawCubeTexture.prototype.updateRGBDAsync = function (data, sphericalPolynomial, lodScale, lodOffset) {
  67218. if (sphericalPolynomial === void 0) { sphericalPolynomial = null; }
  67219. if (lodScale === void 0) { lodScale = 0.8; }
  67220. if (lodOffset === void 0) { lodOffset = 0; }
  67221. return RawCubeTexture._UpdateRGBDAsync(this._texture, data, sphericalPolynomial, lodScale, lodOffset);
  67222. };
  67223. /**
  67224. * Clones the raw cube texture.
  67225. * @return a new cube texture
  67226. */
  67227. RawCubeTexture.prototype.clone = function () {
  67228. var _this = this;
  67229. return BABYLON.SerializationHelper.Clone(function () {
  67230. var scene = _this.getScene();
  67231. var internalTexture = _this._texture;
  67232. var texture = new RawCubeTexture(scene, internalTexture._bufferViewArray, internalTexture.width, internalTexture.format, internalTexture.type, internalTexture.generateMipMaps, internalTexture.invertY, internalTexture.samplingMode, internalTexture._compression);
  67233. if (internalTexture.dataSource === BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD) {
  67234. texture.updateRGBDAsync(internalTexture._bufferViewArrayArray, internalTexture._sphericalPolynomial, internalTexture._lodGenerationScale, internalTexture._lodGenerationOffset);
  67235. }
  67236. return texture;
  67237. }, this);
  67238. };
  67239. /** @hidden */
  67240. RawCubeTexture._UpdateRGBDAsync = function (internalTexture, data, sphericalPolynomial, lodScale, lodOffset) {
  67241. internalTexture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD;
  67242. internalTexture._bufferViewArrayArray = data;
  67243. internalTexture._lodGenerationScale = lodScale;
  67244. internalTexture._lodGenerationOffset = lodOffset;
  67245. internalTexture._sphericalPolynomial = sphericalPolynomial;
  67246. return BABYLON.EnvironmentTextureTools.UploadLevelsAsync(internalTexture, data).then(function () {
  67247. internalTexture.isReady = true;
  67248. });
  67249. };
  67250. return RawCubeTexture;
  67251. }(BABYLON.CubeTexture));
  67252. BABYLON.RawCubeTexture = RawCubeTexture;
  67253. })(BABYLON || (BABYLON = {}));
  67254. //# sourceMappingURL=babylon.rawCubeTexture.js.map
  67255. var BABYLON;
  67256. (function (BABYLON) {
  67257. var RenderTargetTexture = /** @class */ (function (_super) {
  67258. __extends(RenderTargetTexture, _super);
  67259. /**
  67260. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  67261. * or used a shadow, depth texture...
  67262. * @param name The friendly name of the texture
  67263. * @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)
  67264. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  67265. * @param generateMipMaps True if mip maps need to be generated after render.
  67266. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  67267. * @param type The type of the buffer in the RTT (int, half float, float...)
  67268. * @param isCube True if a cube texture needs to be created
  67269. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  67270. * @param generateDepthBuffer True to generate a depth buffer
  67271. * @param generateStencilBuffer True to generate a stencil buffer
  67272. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  67273. * @param format The internal format of the buffer in the RTT (RED, RG, RGB, RGBA, ALPHA...)
  67274. */
  67275. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti, format) {
  67276. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  67277. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67278. if (isCube === void 0) { isCube = false; }
  67279. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67280. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  67281. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  67282. if (isMulti === void 0) { isMulti = false; }
  67283. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  67284. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  67285. _this.isCube = isCube;
  67286. _this.renderParticles = true;
  67287. _this.renderSprites = false;
  67288. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  67289. _this.ignoreCameraViewport = false;
  67290. // Events
  67291. /**
  67292. * An event triggered when the texture is unbind.
  67293. */
  67294. _this.onBeforeBindObservable = new BABYLON.Observable();
  67295. /**
  67296. * An event triggered when the texture is unbind.
  67297. */
  67298. _this.onAfterUnbindObservable = new BABYLON.Observable();
  67299. /**
  67300. * An event triggered before rendering the texture
  67301. */
  67302. _this.onBeforeRenderObservable = new BABYLON.Observable();
  67303. /**
  67304. * An event triggered after rendering the texture
  67305. */
  67306. _this.onAfterRenderObservable = new BABYLON.Observable();
  67307. /**
  67308. * An event triggered after the texture clear
  67309. */
  67310. _this.onClearObservable = new BABYLON.Observable();
  67311. _this._currentRefreshId = -1;
  67312. _this._refreshRate = 1;
  67313. _this._samples = 1;
  67314. /**
  67315. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  67316. * It must define where the camera used to render the texture is set
  67317. */
  67318. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  67319. scene = _this.getScene();
  67320. if (!scene) {
  67321. return _this;
  67322. }
  67323. _this.renderList = new Array();
  67324. _this._engine = scene.getEngine();
  67325. _this.name = name;
  67326. _this.isRenderTarget = true;
  67327. _this._initialSizeParameter = size;
  67328. _this._processSizeParameter(size);
  67329. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  67330. });
  67331. _this._generateMipMaps = generateMipMaps ? true : false;
  67332. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  67333. // Rendering groups
  67334. _this._renderingManager = new BABYLON.RenderingManager(scene);
  67335. _this._renderingManager._useSceneAutoClearSetup = true;
  67336. if (isMulti) {
  67337. return _this;
  67338. }
  67339. _this._renderTargetOptions = {
  67340. generateMipMaps: generateMipMaps,
  67341. type: type,
  67342. format: format,
  67343. samplingMode: samplingMode,
  67344. generateDepthBuffer: generateDepthBuffer,
  67345. generateStencilBuffer: generateStencilBuffer
  67346. };
  67347. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  67348. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67349. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67350. }
  67351. if (isCube) {
  67352. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  67353. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  67354. _this._textureMatrix = BABYLON.Matrix.Identity();
  67355. }
  67356. else {
  67357. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  67358. }
  67359. return _this;
  67360. }
  67361. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  67362. get: function () {
  67363. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  67364. },
  67365. enumerable: true,
  67366. configurable: true
  67367. });
  67368. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  67369. get: function () {
  67370. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  67371. },
  67372. enumerable: true,
  67373. configurable: true
  67374. });
  67375. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  67376. get: function () {
  67377. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  67378. },
  67379. enumerable: true,
  67380. configurable: true
  67381. });
  67382. Object.defineProperty(RenderTargetTexture.prototype, "renderList", {
  67383. /**
  67384. * Use this list to define the list of mesh you want to render.
  67385. */
  67386. get: function () {
  67387. return this._renderList;
  67388. },
  67389. set: function (value) {
  67390. this._renderList = value;
  67391. if (this._renderList) {
  67392. this._hookArray(this._renderList);
  67393. }
  67394. },
  67395. enumerable: true,
  67396. configurable: true
  67397. });
  67398. RenderTargetTexture.prototype._hookArray = function (array) {
  67399. var _this = this;
  67400. var oldPush = array.push;
  67401. array.push = function () {
  67402. var items = [];
  67403. for (var _i = 0; _i < arguments.length; _i++) {
  67404. items[_i] = arguments[_i];
  67405. }
  67406. var result = oldPush.apply(array, items);
  67407. _this.getScene().meshes.forEach(function (mesh) {
  67408. mesh._markSubMeshesAsLightDirty();
  67409. });
  67410. return result;
  67411. };
  67412. var oldSplice = array.splice;
  67413. array.splice = function (index, deleteCount) {
  67414. var deleted = oldSplice.apply(array, [index, deleteCount]);
  67415. _this.getScene().meshes.forEach(function (mesh) {
  67416. mesh._markSubMeshesAsLightDirty();
  67417. });
  67418. return deleted;
  67419. };
  67420. };
  67421. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  67422. set: function (callback) {
  67423. if (this._onAfterUnbindObserver) {
  67424. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  67425. }
  67426. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  67427. },
  67428. enumerable: true,
  67429. configurable: true
  67430. });
  67431. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  67432. set: function (callback) {
  67433. if (this._onBeforeRenderObserver) {
  67434. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  67435. }
  67436. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  67437. },
  67438. enumerable: true,
  67439. configurable: true
  67440. });
  67441. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  67442. set: function (callback) {
  67443. if (this._onAfterRenderObserver) {
  67444. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  67445. }
  67446. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  67447. },
  67448. enumerable: true,
  67449. configurable: true
  67450. });
  67451. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  67452. set: function (callback) {
  67453. if (this._onClearObserver) {
  67454. this.onClearObservable.remove(this._onClearObserver);
  67455. }
  67456. this._onClearObserver = this.onClearObservable.add(callback);
  67457. },
  67458. enumerable: true,
  67459. configurable: true
  67460. });
  67461. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  67462. get: function () {
  67463. return this._renderTargetOptions;
  67464. },
  67465. enumerable: true,
  67466. configurable: true
  67467. });
  67468. RenderTargetTexture.prototype._onRatioRescale = function () {
  67469. if (this._sizeRatio) {
  67470. this.resize(this._initialSizeParameter);
  67471. }
  67472. };
  67473. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  67474. get: function () {
  67475. return this._boundingBoxSize;
  67476. },
  67477. /**
  67478. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  67479. * When defined, the cubemap will switch to local mode
  67480. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  67481. * @example https://www.babylonjs-playground.com/#RNASML
  67482. */
  67483. set: function (value) {
  67484. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  67485. return;
  67486. }
  67487. this._boundingBoxSize = value;
  67488. var scene = this.getScene();
  67489. if (scene) {
  67490. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  67491. }
  67492. },
  67493. enumerable: true,
  67494. configurable: true
  67495. });
  67496. /**
  67497. * Creates a depth stencil texture.
  67498. * This is only available in WebGL 2 or with the depth texture extension available.
  67499. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  67500. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  67501. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  67502. */
  67503. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  67504. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  67505. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  67506. if (generateStencil === void 0) { generateStencil = false; }
  67507. if (!this.getScene()) {
  67508. return;
  67509. }
  67510. var engine = this.getScene().getEngine();
  67511. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  67512. bilinearFiltering: bilinearFiltering,
  67513. comparisonFunction: comparisonFunction,
  67514. generateStencil: generateStencil,
  67515. isCube: this.isCube
  67516. });
  67517. engine.setFrameBufferDepthStencilTexture(this);
  67518. };
  67519. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  67520. if (size.ratio) {
  67521. this._sizeRatio = size.ratio;
  67522. this._size = {
  67523. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  67524. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  67525. };
  67526. }
  67527. else {
  67528. this._size = size;
  67529. }
  67530. };
  67531. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  67532. get: function () {
  67533. return this._samples;
  67534. },
  67535. set: function (value) {
  67536. if (this._samples === value) {
  67537. return;
  67538. }
  67539. var scene = this.getScene();
  67540. if (!scene) {
  67541. return;
  67542. }
  67543. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  67544. },
  67545. enumerable: true,
  67546. configurable: true
  67547. });
  67548. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  67549. this._currentRefreshId = -1;
  67550. };
  67551. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  67552. get: function () {
  67553. return this._refreshRate;
  67554. },
  67555. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  67556. set: function (value) {
  67557. this._refreshRate = value;
  67558. this.resetRefreshCounter();
  67559. },
  67560. enumerable: true,
  67561. configurable: true
  67562. });
  67563. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  67564. if (!this._postProcessManager) {
  67565. var scene = this.getScene();
  67566. if (!scene) {
  67567. return;
  67568. }
  67569. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  67570. this._postProcesses = new Array();
  67571. }
  67572. this._postProcesses.push(postProcess);
  67573. this._postProcesses[0].autoClear = false;
  67574. };
  67575. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  67576. if (!this._postProcesses) {
  67577. return;
  67578. }
  67579. if (dispose) {
  67580. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  67581. var postProcess = _a[_i];
  67582. postProcess.dispose();
  67583. }
  67584. }
  67585. this._postProcesses = [];
  67586. };
  67587. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  67588. if (!this._postProcesses) {
  67589. return;
  67590. }
  67591. var index = this._postProcesses.indexOf(postProcess);
  67592. if (index === -1) {
  67593. return;
  67594. }
  67595. this._postProcesses.splice(index, 1);
  67596. if (this._postProcesses.length > 0) {
  67597. this._postProcesses[0].autoClear = false;
  67598. }
  67599. };
  67600. /** @hidden */
  67601. RenderTargetTexture.prototype._shouldRender = function () {
  67602. if (this._currentRefreshId === -1) { // At least render once
  67603. this._currentRefreshId = 1;
  67604. return true;
  67605. }
  67606. if (this.refreshRate === this._currentRefreshId) {
  67607. this._currentRefreshId = 1;
  67608. return true;
  67609. }
  67610. this._currentRefreshId++;
  67611. return false;
  67612. };
  67613. RenderTargetTexture.prototype.getRenderSize = function () {
  67614. if (this._size.width) {
  67615. return this._size.width;
  67616. }
  67617. return this._size;
  67618. };
  67619. RenderTargetTexture.prototype.getRenderWidth = function () {
  67620. if (this._size.width) {
  67621. return this._size.width;
  67622. }
  67623. return this._size;
  67624. };
  67625. RenderTargetTexture.prototype.getRenderHeight = function () {
  67626. if (this._size.width) {
  67627. return this._size.height;
  67628. }
  67629. return this._size;
  67630. };
  67631. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  67632. get: function () {
  67633. return true;
  67634. },
  67635. enumerable: true,
  67636. configurable: true
  67637. });
  67638. RenderTargetTexture.prototype.scale = function (ratio) {
  67639. var newSize = this.getRenderSize() * ratio;
  67640. this.resize(newSize);
  67641. };
  67642. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  67643. if (this.isCube) {
  67644. return this._textureMatrix;
  67645. }
  67646. return _super.prototype.getReflectionTextureMatrix.call(this);
  67647. };
  67648. RenderTargetTexture.prototype.resize = function (size) {
  67649. this.releaseInternalTexture();
  67650. var scene = this.getScene();
  67651. if (!scene) {
  67652. return;
  67653. }
  67654. this._processSizeParameter(size);
  67655. if (this.isCube) {
  67656. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  67657. }
  67658. else {
  67659. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  67660. }
  67661. };
  67662. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  67663. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  67664. if (dumpForDebug === void 0) { dumpForDebug = false; }
  67665. var scene = this.getScene();
  67666. if (!scene) {
  67667. return;
  67668. }
  67669. var engine = scene.getEngine();
  67670. if (this.useCameraPostProcesses !== undefined) {
  67671. useCameraPostProcess = this.useCameraPostProcesses;
  67672. }
  67673. if (this._waitingRenderList) {
  67674. this.renderList = [];
  67675. for (var index = 0; index < this._waitingRenderList.length; index++) {
  67676. var id = this._waitingRenderList[index];
  67677. var mesh_1 = scene.getMeshByID(id);
  67678. if (mesh_1) {
  67679. this.renderList.push(mesh_1);
  67680. }
  67681. }
  67682. delete this._waitingRenderList;
  67683. }
  67684. // Is predicate defined?
  67685. if (this.renderListPredicate) {
  67686. if (this.renderList) {
  67687. this.renderList.splice(0); // Clear previous renderList
  67688. }
  67689. else {
  67690. this.renderList = [];
  67691. }
  67692. var scene = this.getScene();
  67693. if (!scene) {
  67694. return;
  67695. }
  67696. var sceneMeshes = scene.meshes;
  67697. for (var index = 0; index < sceneMeshes.length; index++) {
  67698. var mesh = sceneMeshes[index];
  67699. if (this.renderListPredicate(mesh)) {
  67700. this.renderList.push(mesh);
  67701. }
  67702. }
  67703. }
  67704. this.onBeforeBindObservable.notifyObservers(this);
  67705. // Set custom projection.
  67706. // Needs to be before binding to prevent changing the aspect ratio.
  67707. var camera;
  67708. if (this.activeCamera) {
  67709. camera = this.activeCamera;
  67710. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  67711. if (this.activeCamera !== scene.activeCamera) {
  67712. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  67713. }
  67714. }
  67715. else {
  67716. camera = scene.activeCamera;
  67717. if (camera) {
  67718. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  67719. }
  67720. }
  67721. // Prepare renderingManager
  67722. this._renderingManager.reset();
  67723. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  67724. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  67725. var sceneRenderId = scene.getRenderId();
  67726. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  67727. var mesh = currentRenderList[meshIndex];
  67728. if (mesh) {
  67729. if (!mesh.isReady(this.refreshRate === 0)) {
  67730. this.resetRefreshCounter();
  67731. continue;
  67732. }
  67733. mesh._preActivateForIntermediateRendering(sceneRenderId);
  67734. var isMasked = void 0;
  67735. if (!this.renderList && camera) {
  67736. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  67737. }
  67738. else {
  67739. isMasked = false;
  67740. }
  67741. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  67742. mesh._activate(sceneRenderId);
  67743. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  67744. var subMesh = mesh.subMeshes[subIndex];
  67745. scene._activeIndices.addCount(subMesh.indexCount, false);
  67746. this._renderingManager.dispatch(subMesh, mesh);
  67747. }
  67748. }
  67749. }
  67750. }
  67751. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  67752. var particleSystem = scene.particleSystems[particleIndex];
  67753. var emitter = particleSystem.emitter;
  67754. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  67755. continue;
  67756. }
  67757. if (currentRenderList.indexOf(emitter) >= 0) {
  67758. this._renderingManager.dispatchParticles(particleSystem);
  67759. }
  67760. }
  67761. if (this.isCube) {
  67762. for (var face = 0; face < 6; face++) {
  67763. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  67764. scene.incrementRenderId();
  67765. scene.resetCachedMaterial();
  67766. }
  67767. }
  67768. else {
  67769. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  67770. }
  67771. this.onAfterUnbindObservable.notifyObservers(this);
  67772. if (scene.activeCamera) {
  67773. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  67774. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  67775. }
  67776. engine.setViewport(scene.activeCamera.viewport);
  67777. }
  67778. scene.resetCachedMaterial();
  67779. };
  67780. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  67781. var minimum = 128;
  67782. var x = renderDimension * scale;
  67783. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  67784. // Ensure we don't exceed the render dimension (while staying POT)
  67785. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  67786. };
  67787. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  67788. var _this = this;
  67789. if (!this._texture) {
  67790. return;
  67791. }
  67792. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  67793. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  67794. });
  67795. };
  67796. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  67797. var scene = this.getScene();
  67798. if (!scene) {
  67799. return;
  67800. }
  67801. var engine = scene.getEngine();
  67802. if (!this._texture) {
  67803. return;
  67804. }
  67805. // Bind
  67806. if (this._postProcessManager) {
  67807. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  67808. }
  67809. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  67810. if (this._texture) {
  67811. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  67812. }
  67813. }
  67814. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  67815. // Clear
  67816. if (this.onClearObservable.hasObservers()) {
  67817. this.onClearObservable.notifyObservers(engine);
  67818. }
  67819. else {
  67820. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  67821. }
  67822. if (!this._doNotChangeAspectRatio) {
  67823. scene.updateTransformMatrix(true);
  67824. }
  67825. // Render
  67826. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  67827. if (this._postProcessManager) {
  67828. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  67829. }
  67830. else if (useCameraPostProcess) {
  67831. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  67832. }
  67833. if (!this._doNotChangeAspectRatio) {
  67834. scene.updateTransformMatrix(true);
  67835. }
  67836. // Dump ?
  67837. if (dumpForDebug) {
  67838. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  67839. }
  67840. // Unbind
  67841. if (!this.isCube || faceIndex === 5) {
  67842. if (this.isCube) {
  67843. if (faceIndex === 5) {
  67844. engine.generateMipMapsForCubemap(this._texture);
  67845. }
  67846. }
  67847. this.unbindFrameBuffer(engine, faceIndex);
  67848. }
  67849. else {
  67850. this.onAfterRenderObservable.notifyObservers(faceIndex);
  67851. }
  67852. };
  67853. /**
  67854. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  67855. * This allowed control for front to back rendering or reversly depending of the special needs.
  67856. *
  67857. * @param renderingGroupId The rendering group id corresponding to its index
  67858. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  67859. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  67860. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  67861. */
  67862. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  67863. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  67864. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  67865. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  67866. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  67867. };
  67868. /**
  67869. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  67870. *
  67871. * @param renderingGroupId The rendering group id corresponding to its index
  67872. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  67873. */
  67874. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  67875. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  67876. this._renderingManager._useSceneAutoClearSetup = false;
  67877. };
  67878. RenderTargetTexture.prototype.clone = function () {
  67879. var textureSize = this.getSize();
  67880. 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);
  67881. // Base texture
  67882. newTexture.hasAlpha = this.hasAlpha;
  67883. newTexture.level = this.level;
  67884. // RenderTarget Texture
  67885. newTexture.coordinatesMode = this.coordinatesMode;
  67886. if (this.renderList) {
  67887. newTexture.renderList = this.renderList.slice(0);
  67888. }
  67889. return newTexture;
  67890. };
  67891. RenderTargetTexture.prototype.serialize = function () {
  67892. if (!this.name) {
  67893. return null;
  67894. }
  67895. var serializationObject = _super.prototype.serialize.call(this);
  67896. serializationObject.renderTargetSize = this.getRenderSize();
  67897. serializationObject.renderList = [];
  67898. if (this.renderList) {
  67899. for (var index = 0; index < this.renderList.length; index++) {
  67900. serializationObject.renderList.push(this.renderList[index].id);
  67901. }
  67902. }
  67903. return serializationObject;
  67904. };
  67905. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  67906. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  67907. var objBuffer = this.getInternalTexture();
  67908. var scene = this.getScene();
  67909. if (objBuffer && scene) {
  67910. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  67911. }
  67912. };
  67913. RenderTargetTexture.prototype.dispose = function () {
  67914. if (this._postProcessManager) {
  67915. this._postProcessManager.dispose();
  67916. this._postProcessManager = null;
  67917. }
  67918. this.clearPostProcesses(true);
  67919. if (this._resizeObserver) {
  67920. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  67921. this._resizeObserver = null;
  67922. }
  67923. this.renderList = null;
  67924. // Remove from custom render targets
  67925. var scene = this.getScene();
  67926. if (!scene) {
  67927. return;
  67928. }
  67929. var index = scene.customRenderTargets.indexOf(this);
  67930. if (index >= 0) {
  67931. scene.customRenderTargets.splice(index, 1);
  67932. }
  67933. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  67934. var camera = _a[_i];
  67935. index = camera.customRenderTargets.indexOf(this);
  67936. if (index >= 0) {
  67937. camera.customRenderTargets.splice(index, 1);
  67938. }
  67939. }
  67940. _super.prototype.dispose.call(this);
  67941. };
  67942. /** @hidden */
  67943. RenderTargetTexture.prototype._rebuild = function () {
  67944. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  67945. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  67946. }
  67947. if (this._postProcessManager) {
  67948. this._postProcessManager._rebuild();
  67949. }
  67950. };
  67951. /**
  67952. * Clear the info related to rendering groups preventing retention point in material dispose.
  67953. */
  67954. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  67955. if (this._renderingManager) {
  67956. this._renderingManager.freeRenderingGroups();
  67957. }
  67958. };
  67959. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  67960. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  67961. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  67962. return RenderTargetTexture;
  67963. }(BABYLON.Texture));
  67964. BABYLON.RenderTargetTexture = RenderTargetTexture;
  67965. })(BABYLON || (BABYLON = {}));
  67966. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  67967. var BABYLON;
  67968. (function (BABYLON) {
  67969. ;
  67970. var MultiRenderTarget = /** @class */ (function (_super) {
  67971. __extends(MultiRenderTarget, _super);
  67972. function MultiRenderTarget(name, size, count, scene, options) {
  67973. var _this = this;
  67974. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  67975. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  67976. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  67977. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  67978. _this._engine = scene.getEngine();
  67979. if (!_this.isSupported) {
  67980. _this.dispose();
  67981. return;
  67982. }
  67983. var types = [];
  67984. var samplingModes = [];
  67985. for (var i = 0; i < count; i++) {
  67986. if (options && options.types && options.types[i] !== undefined) {
  67987. types.push(options.types[i]);
  67988. }
  67989. else {
  67990. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  67991. }
  67992. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  67993. samplingModes.push(options.samplingModes[i]);
  67994. }
  67995. else {
  67996. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  67997. }
  67998. }
  67999. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  68000. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  68001. _this._size = size;
  68002. _this._multiRenderTargetOptions = {
  68003. samplingModes: samplingModes,
  68004. generateMipMaps: generateMipMaps,
  68005. generateDepthBuffer: generateDepthBuffer,
  68006. generateStencilBuffer: generateStencilBuffer,
  68007. generateDepthTexture: generateDepthTexture,
  68008. types: types,
  68009. textureCount: count
  68010. };
  68011. _this._createInternalTextures();
  68012. _this._createTextures();
  68013. return _this;
  68014. }
  68015. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  68016. get: function () {
  68017. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  68018. },
  68019. enumerable: true,
  68020. configurable: true
  68021. });
  68022. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  68023. get: function () {
  68024. return this._textures;
  68025. },
  68026. enumerable: true,
  68027. configurable: true
  68028. });
  68029. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  68030. get: function () {
  68031. return this._textures[this._textures.length - 1];
  68032. },
  68033. enumerable: true,
  68034. configurable: true
  68035. });
  68036. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  68037. set: function (wrap) {
  68038. if (this._textures) {
  68039. for (var i = 0; i < this._textures.length; i++) {
  68040. this._textures[i].wrapU = wrap;
  68041. }
  68042. }
  68043. },
  68044. enumerable: true,
  68045. configurable: true
  68046. });
  68047. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  68048. set: function (wrap) {
  68049. if (this._textures) {
  68050. for (var i = 0; i < this._textures.length; i++) {
  68051. this._textures[i].wrapV = wrap;
  68052. }
  68053. }
  68054. },
  68055. enumerable: true,
  68056. configurable: true
  68057. });
  68058. /** @hidden */
  68059. MultiRenderTarget.prototype._rebuild = function () {
  68060. this.releaseInternalTextures();
  68061. this._createInternalTextures();
  68062. for (var i = 0; i < this._internalTextures.length; i++) {
  68063. var texture = this._textures[i];
  68064. texture._texture = this._internalTextures[i];
  68065. }
  68066. // Keeps references to frame buffer and stencil/depth buffer
  68067. this._texture = this._internalTextures[0];
  68068. };
  68069. MultiRenderTarget.prototype._createInternalTextures = function () {
  68070. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  68071. };
  68072. MultiRenderTarget.prototype._createTextures = function () {
  68073. this._textures = [];
  68074. for (var i = 0; i < this._internalTextures.length; i++) {
  68075. var texture = new BABYLON.Texture(null, this.getScene());
  68076. texture._texture = this._internalTextures[i];
  68077. this._textures.push(texture);
  68078. }
  68079. // Keeps references to frame buffer and stencil/depth buffer
  68080. this._texture = this._internalTextures[0];
  68081. };
  68082. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  68083. get: function () {
  68084. return this._samples;
  68085. },
  68086. set: function (value) {
  68087. if (this._samples === value) {
  68088. return;
  68089. }
  68090. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  68091. },
  68092. enumerable: true,
  68093. configurable: true
  68094. });
  68095. MultiRenderTarget.prototype.resize = function (size) {
  68096. this.releaseInternalTextures();
  68097. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  68098. this._createInternalTextures();
  68099. };
  68100. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  68101. var _this = this;
  68102. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  68103. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  68104. });
  68105. };
  68106. MultiRenderTarget.prototype.dispose = function () {
  68107. this.releaseInternalTextures();
  68108. _super.prototype.dispose.call(this);
  68109. };
  68110. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  68111. if (!this._internalTextures) {
  68112. return;
  68113. }
  68114. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  68115. if (this._internalTextures[i] !== undefined) {
  68116. this._internalTextures[i].dispose();
  68117. this._internalTextures.splice(i, 1);
  68118. }
  68119. }
  68120. };
  68121. return MultiRenderTarget;
  68122. }(BABYLON.RenderTargetTexture));
  68123. BABYLON.MultiRenderTarget = MultiRenderTarget;
  68124. })(BABYLON || (BABYLON = {}));
  68125. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  68126. var BABYLON;
  68127. (function (BABYLON) {
  68128. var MirrorTexture = /** @class */ (function (_super) {
  68129. __extends(MirrorTexture, _super);
  68130. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  68131. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68132. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  68133. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  68134. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  68135. _this.scene = scene;
  68136. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  68137. _this._transformMatrix = BABYLON.Matrix.Zero();
  68138. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  68139. _this._adaptiveBlurKernel = 0;
  68140. _this._blurKernelX = 0;
  68141. _this._blurKernelY = 0;
  68142. _this._blurRatio = 1.0;
  68143. _this.ignoreCameraViewport = true;
  68144. _this._updateGammaSpace();
  68145. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  68146. _this._updateGammaSpace;
  68147. });
  68148. _this.onBeforeRenderObservable.add(function () {
  68149. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  68150. _this._savedViewMatrix = scene.getViewMatrix();
  68151. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  68152. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  68153. scene.clipPlane = _this.mirrorPlane;
  68154. scene.getEngine().cullBackFaces = false;
  68155. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  68156. });
  68157. _this.onAfterRenderObservable.add(function () {
  68158. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  68159. scene.getEngine().cullBackFaces = true;
  68160. scene._mirroredCameraPosition = null;
  68161. delete scene.clipPlane;
  68162. });
  68163. return _this;
  68164. }
  68165. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  68166. get: function () {
  68167. return this._blurRatio;
  68168. },
  68169. set: function (value) {
  68170. if (this._blurRatio === value) {
  68171. return;
  68172. }
  68173. this._blurRatio = value;
  68174. this._preparePostProcesses();
  68175. },
  68176. enumerable: true,
  68177. configurable: true
  68178. });
  68179. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  68180. set: function (value) {
  68181. this._adaptiveBlurKernel = value;
  68182. this._autoComputeBlurKernel();
  68183. },
  68184. enumerable: true,
  68185. configurable: true
  68186. });
  68187. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  68188. set: function (value) {
  68189. this.blurKernelX = value;
  68190. this.blurKernelY = value;
  68191. },
  68192. enumerable: true,
  68193. configurable: true
  68194. });
  68195. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  68196. get: function () {
  68197. return this._blurKernelX;
  68198. },
  68199. set: function (value) {
  68200. if (this._blurKernelX === value) {
  68201. return;
  68202. }
  68203. this._blurKernelX = value;
  68204. this._preparePostProcesses();
  68205. },
  68206. enumerable: true,
  68207. configurable: true
  68208. });
  68209. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  68210. get: function () {
  68211. return this._blurKernelY;
  68212. },
  68213. set: function (value) {
  68214. if (this._blurKernelY === value) {
  68215. return;
  68216. }
  68217. this._blurKernelY = value;
  68218. this._preparePostProcesses();
  68219. },
  68220. enumerable: true,
  68221. configurable: true
  68222. });
  68223. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  68224. var engine = this.getScene().getEngine();
  68225. var dw = this.getRenderWidth() / engine.getRenderWidth();
  68226. var dh = this.getRenderHeight() / engine.getRenderHeight();
  68227. this.blurKernelX = this._adaptiveBlurKernel * dw;
  68228. this.blurKernelY = this._adaptiveBlurKernel * dh;
  68229. };
  68230. MirrorTexture.prototype._onRatioRescale = function () {
  68231. if (this._sizeRatio) {
  68232. this.resize(this._initialSizeParameter);
  68233. if (!this._adaptiveBlurKernel) {
  68234. this._preparePostProcesses();
  68235. }
  68236. }
  68237. if (this._adaptiveBlurKernel) {
  68238. this._autoComputeBlurKernel();
  68239. }
  68240. };
  68241. MirrorTexture.prototype._updateGammaSpace = function () {
  68242. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  68243. };
  68244. MirrorTexture.prototype._preparePostProcesses = function () {
  68245. this.clearPostProcesses(true);
  68246. if (this._blurKernelX && this._blurKernelY) {
  68247. var engine = this.getScene().getEngine();
  68248. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  68249. 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);
  68250. this._blurX.autoClear = false;
  68251. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  68252. this._blurX.inputTexture = this._texture;
  68253. }
  68254. else {
  68255. this._blurX.alwaysForcePOT = true;
  68256. }
  68257. 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);
  68258. this._blurY.autoClear = false;
  68259. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  68260. this.addPostProcess(this._blurX);
  68261. this.addPostProcess(this._blurY);
  68262. }
  68263. else {
  68264. if (this._blurY) {
  68265. this.removePostProcess(this._blurY);
  68266. this._blurY.dispose();
  68267. this._blurY = null;
  68268. }
  68269. if (this._blurX) {
  68270. this.removePostProcess(this._blurX);
  68271. this._blurX.dispose();
  68272. this._blurX = null;
  68273. }
  68274. }
  68275. };
  68276. MirrorTexture.prototype.clone = function () {
  68277. var scene = this.getScene();
  68278. if (!scene) {
  68279. return this;
  68280. }
  68281. var textureSize = this.getSize();
  68282. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  68283. // Base texture
  68284. newTexture.hasAlpha = this.hasAlpha;
  68285. newTexture.level = this.level;
  68286. // Mirror Texture
  68287. newTexture.mirrorPlane = this.mirrorPlane.clone();
  68288. if (this.renderList) {
  68289. newTexture.renderList = this.renderList.slice(0);
  68290. }
  68291. return newTexture;
  68292. };
  68293. MirrorTexture.prototype.serialize = function () {
  68294. if (!this.name) {
  68295. return null;
  68296. }
  68297. var serializationObject = _super.prototype.serialize.call(this);
  68298. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  68299. return serializationObject;
  68300. };
  68301. MirrorTexture.prototype.dispose = function () {
  68302. _super.prototype.dispose.call(this);
  68303. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  68304. };
  68305. return MirrorTexture;
  68306. }(BABYLON.RenderTargetTexture));
  68307. BABYLON.MirrorTexture = MirrorTexture;
  68308. })(BABYLON || (BABYLON = {}));
  68309. //# sourceMappingURL=babylon.mirrorTexture.js.map
  68310. var BABYLON;
  68311. (function (BABYLON) {
  68312. /**
  68313. * Creates a refraction texture used by refraction channel of the standard material.
  68314. * @param name the texture name
  68315. * @param size size of the underlying texture
  68316. * @param scene root scene
  68317. */
  68318. var RefractionTexture = /** @class */ (function (_super) {
  68319. __extends(RefractionTexture, _super);
  68320. function RefractionTexture(name, size, scene, generateMipMaps) {
  68321. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  68322. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  68323. _this.depth = 2.0;
  68324. _this.onBeforeRenderObservable.add(function () {
  68325. scene.clipPlane = _this.refractionPlane;
  68326. });
  68327. _this.onAfterRenderObservable.add(function () {
  68328. delete scene.clipPlane;
  68329. });
  68330. return _this;
  68331. }
  68332. RefractionTexture.prototype.clone = function () {
  68333. var scene = this.getScene();
  68334. if (!scene) {
  68335. return this;
  68336. }
  68337. var textureSize = this.getSize();
  68338. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  68339. // Base texture
  68340. newTexture.hasAlpha = this.hasAlpha;
  68341. newTexture.level = this.level;
  68342. // Refraction Texture
  68343. newTexture.refractionPlane = this.refractionPlane.clone();
  68344. if (this.renderList) {
  68345. newTexture.renderList = this.renderList.slice(0);
  68346. }
  68347. newTexture.depth = this.depth;
  68348. return newTexture;
  68349. };
  68350. RefractionTexture.prototype.serialize = function () {
  68351. if (!this.name) {
  68352. return null;
  68353. }
  68354. var serializationObject = _super.prototype.serialize.call(this);
  68355. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  68356. serializationObject.depth = this.depth;
  68357. return serializationObject;
  68358. };
  68359. return RefractionTexture;
  68360. }(BABYLON.RenderTargetTexture));
  68361. BABYLON.RefractionTexture = RefractionTexture;
  68362. })(BABYLON || (BABYLON = {}));
  68363. //# sourceMappingURL=babylon.refractionTexture.js.map
  68364. var BABYLON;
  68365. (function (BABYLON) {
  68366. /**
  68367. * A class extending {BABYLON.Texture} allowing drawing on a texture
  68368. * @see http://doc.babylonjs.com/how_to/dynamictexture
  68369. */
  68370. var DynamicTexture = /** @class */ (function (_super) {
  68371. __extends(DynamicTexture, _super);
  68372. /**
  68373. * Creates a {BABYLON.DynamicTexture}
  68374. * @param name defines the name of the texture
  68375. * @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
  68376. * @param scene defines the scene where you want the texture
  68377. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  68378. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  68379. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  68380. */
  68381. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  68382. if (scene === void 0) { scene = null; }
  68383. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68384. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  68385. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  68386. _this.name = name;
  68387. _this._engine = _this.getScene().getEngine();
  68388. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68389. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68390. _this._generateMipMaps = generateMipMaps;
  68391. if (options.getContext) {
  68392. _this._canvas = options;
  68393. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  68394. }
  68395. else {
  68396. _this._canvas = document.createElement("canvas");
  68397. if (options.width || options.width === 0) {
  68398. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  68399. }
  68400. else {
  68401. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  68402. }
  68403. }
  68404. var textureSize = _this.getSize();
  68405. _this._canvas.width = textureSize.width;
  68406. _this._canvas.height = textureSize.height;
  68407. _this._context = _this._canvas.getContext("2d");
  68408. return _this;
  68409. }
  68410. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  68411. /**
  68412. * Gets the current state of canRescale
  68413. */
  68414. get: function () {
  68415. return true;
  68416. },
  68417. enumerable: true,
  68418. configurable: true
  68419. });
  68420. DynamicTexture.prototype._recreate = function (textureSize) {
  68421. this._canvas.width = textureSize.width;
  68422. this._canvas.height = textureSize.height;
  68423. this.releaseInternalTexture();
  68424. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  68425. };
  68426. /**
  68427. * Scales the texture
  68428. * @param ratio the scale factor to apply to both width and height
  68429. */
  68430. DynamicTexture.prototype.scale = function (ratio) {
  68431. var textureSize = this.getSize();
  68432. textureSize.width *= ratio;
  68433. textureSize.height *= ratio;
  68434. this._recreate(textureSize);
  68435. };
  68436. /**
  68437. * Resizes the texture
  68438. * @param width the new width
  68439. * @param height the new height
  68440. */
  68441. DynamicTexture.prototype.scaleTo = function (width, height) {
  68442. var textureSize = this.getSize();
  68443. textureSize.width = width;
  68444. textureSize.height = height;
  68445. this._recreate(textureSize);
  68446. };
  68447. /**
  68448. * Gets the context of the canvas used by the texture
  68449. * @returns the canvas context of the dynamic texture
  68450. */
  68451. DynamicTexture.prototype.getContext = function () {
  68452. return this._context;
  68453. };
  68454. /**
  68455. * Clears the texture
  68456. */
  68457. DynamicTexture.prototype.clear = function () {
  68458. var size = this.getSize();
  68459. this._context.fillRect(0, 0, size.width, size.height);
  68460. };
  68461. /**
  68462. * Updates the texture
  68463. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  68464. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  68465. */
  68466. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  68467. if (premulAlpha === void 0) { premulAlpha = false; }
  68468. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  68469. };
  68470. /**
  68471. * Draws text onto the texture
  68472. * @param text defines the text to be drawn
  68473. * @param x defines the placement of the text from the left
  68474. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  68475. * @param font defines the font to be used with font-style, font-size, font-name
  68476. * @param color defines the color used for the text
  68477. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  68478. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  68479. * @param update defines whether texture is immediately update (default is true)
  68480. */
  68481. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  68482. if (update === void 0) { update = true; }
  68483. var size = this.getSize();
  68484. if (clearColor) {
  68485. this._context.fillStyle = clearColor;
  68486. this._context.fillRect(0, 0, size.width, size.height);
  68487. }
  68488. this._context.font = font;
  68489. if (x === null || x === undefined) {
  68490. var textSize = this._context.measureText(text);
  68491. x = (size.width - textSize.width) / 2;
  68492. }
  68493. if (y === null || y === undefined) {
  68494. var fontSize = parseInt((font.replace(/\D/g, '')));
  68495. y = (size.height / 2) + (fontSize / 3.65);
  68496. }
  68497. this._context.fillStyle = color;
  68498. this._context.fillText(text, x, y);
  68499. if (update) {
  68500. this.update(invertY);
  68501. }
  68502. };
  68503. /**
  68504. * Clones the texture
  68505. * @returns the clone of the texture.
  68506. */
  68507. DynamicTexture.prototype.clone = function () {
  68508. var scene = this.getScene();
  68509. if (!scene) {
  68510. return this;
  68511. }
  68512. var textureSize = this.getSize();
  68513. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  68514. // Base texture
  68515. newTexture.hasAlpha = this.hasAlpha;
  68516. newTexture.level = this.level;
  68517. // Dynamic Texture
  68518. newTexture.wrapU = this.wrapU;
  68519. newTexture.wrapV = this.wrapV;
  68520. return newTexture;
  68521. };
  68522. /**
  68523. * Serializes the dynamic texture. The scene should be ready before the dynamic texture is serialized
  68524. * @returns a serialized dynamic texture object
  68525. */
  68526. DynamicTexture.prototype.serialize = function () {
  68527. var scene = this.getScene();
  68528. if (scene && !scene.isReady()) {
  68529. BABYLON.Tools.Warn("The scene must be ready before serializing the dynamic texture");
  68530. }
  68531. var serializationObject = _super.prototype.serialize.call(this);
  68532. serializationObject.base64String = this._canvas.toDataURL();
  68533. serializationObject.invertY = this._invertY;
  68534. serializationObject.samplingMode = this.samplingMode;
  68535. return serializationObject;
  68536. };
  68537. /** @hidden */
  68538. DynamicTexture.prototype._rebuild = function () {
  68539. this.update();
  68540. };
  68541. return DynamicTexture;
  68542. }(BABYLON.Texture));
  68543. BABYLON.DynamicTexture = DynamicTexture;
  68544. })(BABYLON || (BABYLON = {}));
  68545. //# sourceMappingURL=babylon.dynamicTexture.js.map
  68546. var BABYLON;
  68547. (function (BABYLON) {
  68548. var VideoTexture = /** @class */ (function (_super) {
  68549. __extends(VideoTexture, _super);
  68550. /**
  68551. * Creates a video texture.
  68552. * Sample : https://doc.babylonjs.com/how_to/video_texture
  68553. * @param {string | null} name optional name, will detect from video source, if not defined
  68554. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  68555. * @param {BABYLON.Scene} scene is obviously the current scene.
  68556. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  68557. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  68558. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  68559. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  68560. */
  68561. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  68562. if (generateMipMaps === void 0) { generateMipMaps = false; }
  68563. if (invertY === void 0) { invertY = false; }
  68564. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68565. if (settings === void 0) { settings = {
  68566. autoPlay: true,
  68567. loop: true,
  68568. autoUpdateTexture: true,
  68569. }; }
  68570. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  68571. _this._onUserActionRequestedObservable = null;
  68572. _this._stillImageCaptured = false;
  68573. _this._poster = false;
  68574. _this._createInternalTexture = function () {
  68575. if (_this._texture != null) {
  68576. if (_this._poster) {
  68577. _this._texture.dispose();
  68578. _this._poster = false;
  68579. }
  68580. else {
  68581. return;
  68582. }
  68583. }
  68584. if (!_this._engine.needPOTTextures ||
  68585. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  68586. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  68587. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  68588. }
  68589. else {
  68590. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68591. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68592. _this._generateMipMaps = false;
  68593. }
  68594. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  68595. if (!_this.video.autoplay) {
  68596. var oldHandler_1 = _this.video.onplaying;
  68597. var error_1 = false;
  68598. _this.video.onplaying = function () {
  68599. _this.video.onplaying = oldHandler_1;
  68600. _this._texture.isReady = true;
  68601. _this._updateInternalTexture();
  68602. if (!error_1) {
  68603. _this.video.pause();
  68604. }
  68605. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  68606. _this.onLoadObservable.notifyObservers(_this);
  68607. }
  68608. };
  68609. var playing = _this.video.play();
  68610. if (playing) {
  68611. playing.then(function () {
  68612. // Everything is good.
  68613. })
  68614. .catch(function () {
  68615. error_1 = true;
  68616. // On Chrome for instance, new policies might prevent playing without user interaction.
  68617. if (_this._onUserActionRequestedObservable && _this._onUserActionRequestedObservable.hasObservers()) {
  68618. _this._onUserActionRequestedObservable.notifyObservers(_this);
  68619. }
  68620. });
  68621. }
  68622. else {
  68623. _this.video.onplaying = oldHandler_1;
  68624. _this._texture.isReady = true;
  68625. _this._updateInternalTexture();
  68626. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  68627. _this.onLoadObservable.notifyObservers(_this);
  68628. }
  68629. }
  68630. }
  68631. else {
  68632. _this._texture.isReady = true;
  68633. _this._updateInternalTexture();
  68634. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  68635. _this.onLoadObservable.notifyObservers(_this);
  68636. }
  68637. }
  68638. };
  68639. _this.reset = function () {
  68640. if (_this._texture == null) {
  68641. return;
  68642. }
  68643. if (!_this._poster) {
  68644. _this._texture.dispose();
  68645. _this._texture = null;
  68646. }
  68647. };
  68648. _this._updateInternalTexture = function (e) {
  68649. if (_this._texture == null || !_this._texture.isReady) {
  68650. return;
  68651. }
  68652. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  68653. return;
  68654. }
  68655. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  68656. };
  68657. _this._engine = _this.getScene().getEngine();
  68658. _this._generateMipMaps = generateMipMaps;
  68659. _this._samplingMode = samplingMode;
  68660. _this.autoUpdateTexture = settings.autoUpdateTexture;
  68661. _this.name = name || _this._getName(src);
  68662. _this.video = _this._getVideo(src);
  68663. if (settings.poster) {
  68664. _this.video.poster = settings.poster;
  68665. }
  68666. if (settings.autoPlay !== undefined) {
  68667. _this.video.autoplay = settings.autoPlay;
  68668. }
  68669. if (settings.loop !== undefined) {
  68670. _this.video.loop = settings.loop;
  68671. }
  68672. _this.video.setAttribute("playsinline", "");
  68673. _this.video.addEventListener("canplay", _this._createInternalTexture);
  68674. _this.video.addEventListener("paused", _this._updateInternalTexture);
  68675. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  68676. _this.video.addEventListener("emptied", _this.reset);
  68677. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  68678. _this._createInternalTexture();
  68679. }
  68680. if (settings.poster) {
  68681. _this._texture = _this._engine.createTexture(settings.poster, false, true, scene);
  68682. _this._poster = true;
  68683. }
  68684. return _this;
  68685. }
  68686. Object.defineProperty(VideoTexture.prototype, "onUserActionRequestedObservable", {
  68687. get: function () {
  68688. if (!this._onUserActionRequestedObservable) {
  68689. this._onUserActionRequestedObservable = new BABYLON.Observable();
  68690. }
  68691. return this._onUserActionRequestedObservable;
  68692. },
  68693. enumerable: true,
  68694. configurable: true
  68695. });
  68696. VideoTexture.prototype._getName = function (src) {
  68697. if (src instanceof HTMLVideoElement) {
  68698. return src.currentSrc;
  68699. }
  68700. if (typeof src === "object") {
  68701. return src.toString();
  68702. }
  68703. return src;
  68704. };
  68705. ;
  68706. VideoTexture.prototype._getVideo = function (src) {
  68707. if (src instanceof HTMLVideoElement) {
  68708. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  68709. return src;
  68710. }
  68711. var video = document.createElement("video");
  68712. if (typeof src === "string") {
  68713. BABYLON.Tools.SetCorsBehavior(src, video);
  68714. video.src = src;
  68715. }
  68716. else {
  68717. BABYLON.Tools.SetCorsBehavior(src[0], video);
  68718. src.forEach(function (url) {
  68719. var source = document.createElement("source");
  68720. source.src = url;
  68721. video.appendChild(source);
  68722. });
  68723. }
  68724. return video;
  68725. };
  68726. ;
  68727. /**
  68728. * @hidden Internal method to initiate `update`.
  68729. */
  68730. VideoTexture.prototype._rebuild = function () {
  68731. this.update();
  68732. };
  68733. /**
  68734. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  68735. */
  68736. VideoTexture.prototype.update = function () {
  68737. if (!this.autoUpdateTexture) {
  68738. // Expecting user to call `updateTexture` manually
  68739. return;
  68740. }
  68741. this.updateTexture(true);
  68742. };
  68743. /**
  68744. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  68745. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  68746. */
  68747. VideoTexture.prototype.updateTexture = function (isVisible) {
  68748. if (!isVisible) {
  68749. return;
  68750. }
  68751. if (this.video.paused && this._stillImageCaptured) {
  68752. return;
  68753. }
  68754. this._stillImageCaptured = true;
  68755. this._updateInternalTexture();
  68756. };
  68757. /**
  68758. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  68759. * @param url New url.
  68760. */
  68761. VideoTexture.prototype.updateURL = function (url) {
  68762. this.video.src = url;
  68763. };
  68764. VideoTexture.prototype.dispose = function () {
  68765. _super.prototype.dispose.call(this);
  68766. if (this._onUserActionRequestedObservable) {
  68767. this._onUserActionRequestedObservable.clear();
  68768. this._onUserActionRequestedObservable = null;
  68769. }
  68770. this.video.removeEventListener("canplay", this._createInternalTexture);
  68771. this.video.removeEventListener("paused", this._updateInternalTexture);
  68772. this.video.removeEventListener("seeked", this._updateInternalTexture);
  68773. this.video.removeEventListener("emptied", this.reset);
  68774. this.video.pause();
  68775. };
  68776. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  68777. var video = document.createElement("video");
  68778. video.setAttribute('autoplay', '');
  68779. video.setAttribute('muted', '');
  68780. video.setAttribute('playsinline', '');
  68781. var constraintsDeviceId;
  68782. if (constraints && constraints.deviceId) {
  68783. constraintsDeviceId = {
  68784. exact: constraints.deviceId,
  68785. };
  68786. }
  68787. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  68788. if (navigator.mediaDevices) {
  68789. navigator.mediaDevices.getUserMedia({ video: constraints })
  68790. .then(function (stream) {
  68791. if (video.mozSrcObject !== undefined) {
  68792. // hack for Firefox < 19
  68793. video.mozSrcObject = stream;
  68794. }
  68795. else {
  68796. video.srcObject = stream;
  68797. }
  68798. var onPlaying = function () {
  68799. if (onReady) {
  68800. onReady(new VideoTexture("video", video, scene, true, true));
  68801. }
  68802. video.removeEventListener("playing", onPlaying);
  68803. };
  68804. video.addEventListener("playing", onPlaying);
  68805. video.play();
  68806. })
  68807. .catch(function (err) {
  68808. BABYLON.Tools.Error(err.name);
  68809. });
  68810. }
  68811. else {
  68812. navigator.getUserMedia =
  68813. navigator.getUserMedia ||
  68814. navigator.webkitGetUserMedia ||
  68815. navigator.mozGetUserMedia ||
  68816. navigator.msGetUserMedia;
  68817. if (navigator.getUserMedia) {
  68818. navigator.getUserMedia({
  68819. video: {
  68820. deviceId: constraintsDeviceId,
  68821. width: {
  68822. min: (constraints && constraints.minWidth) || 256,
  68823. max: (constraints && constraints.maxWidth) || 640,
  68824. },
  68825. height: {
  68826. min: (constraints && constraints.minHeight) || 256,
  68827. max: (constraints && constraints.maxHeight) || 480,
  68828. },
  68829. },
  68830. }, function (stream) {
  68831. if (video.mozSrcObject !== undefined) {
  68832. // hack for Firefox < 19
  68833. video.mozSrcObject = stream;
  68834. }
  68835. else {
  68836. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  68837. }
  68838. video.play();
  68839. if (onReady) {
  68840. onReady(new VideoTexture("video", video, scene, true, true));
  68841. }
  68842. }, function (e) {
  68843. BABYLON.Tools.Error(e.name);
  68844. });
  68845. }
  68846. }
  68847. };
  68848. return VideoTexture;
  68849. }(BABYLON.Texture));
  68850. BABYLON.VideoTexture = VideoTexture;
  68851. })(BABYLON || (BABYLON = {}));
  68852. //# sourceMappingURL=babylon.videoTexture.js.map
  68853. var BABYLON;
  68854. (function (BABYLON) {
  68855. var RawTexture = /** @class */ (function (_super) {
  68856. __extends(RawTexture, _super);
  68857. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  68858. if (generateMipMaps === void 0) { generateMipMaps = true; }
  68859. if (invertY === void 0) { invertY = false; }
  68860. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68861. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68862. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  68863. _this.format = format;
  68864. _this._engine = scene.getEngine();
  68865. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  68866. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68867. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68868. return _this;
  68869. }
  68870. RawTexture.prototype.update = function (data) {
  68871. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  68872. };
  68873. // Statics
  68874. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  68875. if (generateMipMaps === void 0) { generateMipMaps = true; }
  68876. if (invertY === void 0) { invertY = false; }
  68877. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68878. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  68879. };
  68880. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  68881. if (generateMipMaps === void 0) { generateMipMaps = true; }
  68882. if (invertY === void 0) { invertY = false; }
  68883. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68884. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  68885. };
  68886. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  68887. if (generateMipMaps === void 0) { generateMipMaps = true; }
  68888. if (invertY === void 0) { invertY = false; }
  68889. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68890. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  68891. };
  68892. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  68893. if (generateMipMaps === void 0) { generateMipMaps = true; }
  68894. if (invertY === void 0) { invertY = false; }
  68895. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68896. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68897. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  68898. };
  68899. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  68900. if (generateMipMaps === void 0) { generateMipMaps = true; }
  68901. if (invertY === void 0) { invertY = false; }
  68902. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68903. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68904. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  68905. };
  68906. RawTexture.CreateRTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  68907. if (generateMipMaps === void 0) { generateMipMaps = true; }
  68908. if (invertY === void 0) { invertY = false; }
  68909. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68910. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  68911. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_R, scene, generateMipMaps, invertY, samplingMode, type);
  68912. };
  68913. return RawTexture;
  68914. }(BABYLON.Texture));
  68915. BABYLON.RawTexture = RawTexture;
  68916. })(BABYLON || (BABYLON = {}));
  68917. //# sourceMappingURL=babylon.rawTexture.js.map
  68918. var BABYLON;
  68919. (function (BABYLON) {
  68920. /**
  68921. * Class used to store 3D textures containing user data
  68922. */
  68923. var RawTexture3D = /** @class */ (function (_super) {
  68924. __extends(RawTexture3D, _super);
  68925. /**
  68926. * Create a new RawTexture3D
  68927. * @param data defines the data of the texture
  68928. * @param width defines the width of the texture
  68929. * @param height defines the height of the texture
  68930. * @param depth defines the depth of the texture
  68931. * @param format defines the texture format to use
  68932. * @param scene defines the hosting scene
  68933. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  68934. * @param invertY defines if texture must be stored with Y axis inverted
  68935. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  68936. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  68937. */
  68938. function RawTexture3D(data, width, height, depth,
  68939. /** Gets or sets the texture format to use */
  68940. format, scene, generateMipMaps, invertY, samplingMode, textureType) {
  68941. if (generateMipMaps === void 0) { generateMipMaps = true; }
  68942. if (invertY === void 0) { invertY = false; }
  68943. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68944. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68945. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  68946. _this.format = format;
  68947. _this._engine = scene.getEngine();
  68948. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);
  68949. _this.is3D = true;
  68950. return _this;
  68951. }
  68952. /**
  68953. * Update the texture with new data
  68954. * @param data defines the data to store in the texture
  68955. */
  68956. RawTexture3D.prototype.update = function (data) {
  68957. if (!this._texture) {
  68958. return;
  68959. }
  68960. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  68961. };
  68962. return RawTexture3D;
  68963. }(BABYLON.Texture));
  68964. BABYLON.RawTexture3D = RawTexture3D;
  68965. })(BABYLON || (BABYLON = {}));
  68966. //# sourceMappingURL=babylon.rawTexture3D.js.map
  68967. var BABYLON;
  68968. (function (BABYLON) {
  68969. /**
  68970. * PostProcessManager is used to manage one or more post processes or post process pipelines
  68971. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  68972. */
  68973. var PostProcessManager = /** @class */ (function () {
  68974. /**
  68975. * Creates a new instance PostProcess
  68976. * @param scene The scene that the post process is associated with.
  68977. */
  68978. function PostProcessManager(scene) {
  68979. this._vertexBuffers = {};
  68980. this._scene = scene;
  68981. }
  68982. PostProcessManager.prototype._prepareBuffers = function () {
  68983. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  68984. return;
  68985. }
  68986. // VBO
  68987. var vertices = [];
  68988. vertices.push(1, 1);
  68989. vertices.push(-1, 1);
  68990. vertices.push(-1, -1);
  68991. vertices.push(1, -1);
  68992. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  68993. this._buildIndexBuffer();
  68994. };
  68995. PostProcessManager.prototype._buildIndexBuffer = function () {
  68996. // Indices
  68997. var indices = [];
  68998. indices.push(0);
  68999. indices.push(1);
  69000. indices.push(2);
  69001. indices.push(0);
  69002. indices.push(2);
  69003. indices.push(3);
  69004. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  69005. };
  69006. /**
  69007. * Rebuilds the vertex buffers of the manager.
  69008. * @hidden
  69009. */
  69010. PostProcessManager.prototype._rebuild = function () {
  69011. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69012. if (!vb) {
  69013. return;
  69014. }
  69015. vb._rebuild();
  69016. this._buildIndexBuffer();
  69017. };
  69018. // Methods
  69019. /**
  69020. * Prepares a frame to be run through a post process.
  69021. * @param sourceTexture The input texture to the post procesess. (default: null)
  69022. * @param postProcesses An array of post processes to be run. (default: null)
  69023. * @returns True if the post processes were able to be run.
  69024. * @hidden
  69025. */
  69026. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  69027. if (sourceTexture === void 0) { sourceTexture = null; }
  69028. if (postProcesses === void 0) { postProcesses = null; }
  69029. var camera = this._scene.activeCamera;
  69030. if (!camera) {
  69031. return false;
  69032. }
  69033. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  69034. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  69035. return false;
  69036. }
  69037. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  69038. return true;
  69039. };
  69040. /**
  69041. * Manually render a set of post processes to a texture.
  69042. * @param postProcesses An array of post processes to be run.
  69043. * @param targetTexture The target texture to render to.
  69044. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  69045. * @param faceIndex defines the face to render to if a cubemap is defined as the target
  69046. * @param lodLevel defines which lod of the texture to render to
  69047. */
  69048. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) {
  69049. if (targetTexture === void 0) { targetTexture = null; }
  69050. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  69051. if (faceIndex === void 0) { faceIndex = 0; }
  69052. if (lodLevel === void 0) { lodLevel = 0; }
  69053. var engine = this._scene.getEngine();
  69054. for (var index = 0; index < postProcesses.length; index++) {
  69055. if (index < postProcesses.length - 1) {
  69056. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  69057. }
  69058. else {
  69059. if (targetTexture) {
  69060. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, undefined, lodLevel);
  69061. }
  69062. else {
  69063. engine.restoreDefaultFramebuffer();
  69064. }
  69065. }
  69066. var pp = postProcesses[index];
  69067. var effect = pp.apply();
  69068. if (effect) {
  69069. pp.onBeforeRenderObservable.notifyObservers(effect);
  69070. // VBOs
  69071. this._prepareBuffers();
  69072. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  69073. // Draw order
  69074. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  69075. pp.onAfterRenderObservable.notifyObservers(effect);
  69076. }
  69077. }
  69078. // Restore depth buffer
  69079. engine.setDepthBuffer(true);
  69080. engine.setDepthWrite(true);
  69081. };
  69082. /**
  69083. * Finalize the result of the output of the postprocesses.
  69084. * @param doNotPresent If true the result will not be displayed to the screen.
  69085. * @param targetTexture The target texture to render to.
  69086. * @param faceIndex The index of the face to bind the target texture to.
  69087. * @param postProcesses The array of post processes to render.
  69088. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  69089. * @hidden
  69090. */
  69091. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  69092. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  69093. var camera = this._scene.activeCamera;
  69094. if (!camera) {
  69095. return;
  69096. }
  69097. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  69098. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  69099. return;
  69100. }
  69101. var engine = this._scene.getEngine();
  69102. for (var index = 0, len = postProcesses.length; index < len; index++) {
  69103. var pp = postProcesses[index];
  69104. if (index < len - 1) {
  69105. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  69106. }
  69107. else {
  69108. if (targetTexture) {
  69109. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  69110. pp._outputTexture = targetTexture;
  69111. }
  69112. else {
  69113. engine.restoreDefaultFramebuffer();
  69114. pp._outputTexture = null;
  69115. }
  69116. }
  69117. if (doNotPresent) {
  69118. break;
  69119. }
  69120. var effect = pp.apply();
  69121. if (effect) {
  69122. pp.onBeforeRenderObservable.notifyObservers(effect);
  69123. // VBOs
  69124. this._prepareBuffers();
  69125. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  69126. // Draw order
  69127. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  69128. pp.onAfterRenderObservable.notifyObservers(effect);
  69129. }
  69130. }
  69131. // Restore states
  69132. engine.setDepthBuffer(true);
  69133. engine.setDepthWrite(true);
  69134. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  69135. };
  69136. /**
  69137. * Disposes of the post process manager.
  69138. */
  69139. PostProcessManager.prototype.dispose = function () {
  69140. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69141. if (buffer) {
  69142. buffer.dispose();
  69143. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  69144. }
  69145. if (this._indexBuffer) {
  69146. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  69147. this._indexBuffer = null;
  69148. }
  69149. };
  69150. return PostProcessManager;
  69151. }());
  69152. BABYLON.PostProcessManager = PostProcessManager;
  69153. })(BABYLON || (BABYLON = {}));
  69154. //# sourceMappingURL=babylon.postProcessManager.js.map
  69155. var BABYLON;
  69156. (function (BABYLON) {
  69157. /**
  69158. * PostProcess can be used to apply a shader to a texture after it has been rendered
  69159. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  69160. */
  69161. var PostProcess = /** @class */ (function () {
  69162. /**
  69163. * Creates a new instance PostProcess
  69164. * @param name The name of the PostProcess.
  69165. * @param fragmentUrl The url of the fragment shader to be used.
  69166. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  69167. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  69168. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  69169. * @param camera The camera to apply the render pass to.
  69170. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69171. * @param engine The engine which the post process will be applied. (default: current engine)
  69172. * @param reusable If the post process can be reused on the same frame. (default: false)
  69173. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  69174. * @param textureType Type of textures used when performing the post process. (default: 0)
  69175. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  69176. * @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
  69177. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  69178. */
  69179. function PostProcess(
  69180. /** Name of the PostProcess. */
  69181. name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  69182. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  69183. if (defines === void 0) { defines = null; }
  69184. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69185. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  69186. if (blockCompilation === void 0) { blockCompilation = false; }
  69187. this.name = name;
  69188. /**
  69189. * Width of the texture to apply the post process on
  69190. */
  69191. this.width = -1;
  69192. /**
  69193. * Height of the texture to apply the post process on
  69194. */
  69195. this.height = -1;
  69196. /**
  69197. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  69198. * @hidden
  69199. */
  69200. this._outputTexture = null;
  69201. /**
  69202. * If the buffer needs to be cleared before applying the post process. (default: true)
  69203. * Should be set to false if shader will overwrite all previous pixels.
  69204. */
  69205. this.autoClear = true;
  69206. /**
  69207. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  69208. */
  69209. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  69210. /**
  69211. * Animations to be used for the post processing
  69212. */
  69213. this.animations = new Array();
  69214. /**
  69215. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  69216. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  69217. */
  69218. this.enablePixelPerfectMode = false;
  69219. /**
  69220. * Force the postprocess to be applied without taking in account viewport
  69221. */
  69222. this.forceFullscreenViewport = true;
  69223. /**
  69224. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  69225. *
  69226. * | Value | Type | Description |
  69227. * | ----- | ----------------------------------- | ----------- |
  69228. * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
  69229. * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
  69230. * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
  69231. *
  69232. */
  69233. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  69234. /**
  69235. * Force textures to be a power of two (default: false)
  69236. */
  69237. this.alwaysForcePOT = false;
  69238. this._samples = 1;
  69239. /**
  69240. * Modify the scale of the post process to be the same as the viewport (default: false)
  69241. */
  69242. this.adaptScaleToCurrentViewport = false;
  69243. this._reusable = false;
  69244. /**
  69245. * Smart array of input and output textures for the post process.
  69246. * @hidden
  69247. */
  69248. this._textures = new BABYLON.SmartArray(2);
  69249. /**
  69250. * The index in _textures that corresponds to the output texture.
  69251. * @hidden
  69252. */
  69253. this._currentRenderTextureInd = 0;
  69254. this._scaleRatio = new BABYLON.Vector2(1, 1);
  69255. this._texelSize = BABYLON.Vector2.Zero();
  69256. // Events
  69257. /**
  69258. * An event triggered when the postprocess is activated.
  69259. */
  69260. this.onActivateObservable = new BABYLON.Observable();
  69261. /**
  69262. * An event triggered when the postprocess changes its size.
  69263. */
  69264. this.onSizeChangedObservable = new BABYLON.Observable();
  69265. /**
  69266. * An event triggered when the postprocess applies its effect.
  69267. */
  69268. this.onApplyObservable = new BABYLON.Observable();
  69269. /**
  69270. * An event triggered before rendering the postprocess
  69271. */
  69272. this.onBeforeRenderObservable = new BABYLON.Observable();
  69273. /**
  69274. * An event triggered after rendering the postprocess
  69275. */
  69276. this.onAfterRenderObservable = new BABYLON.Observable();
  69277. if (camera != null) {
  69278. this._camera = camera;
  69279. this._scene = camera.getScene();
  69280. camera.attachPostProcess(this);
  69281. this._engine = this._scene.getEngine();
  69282. this._scene.postProcesses.push(this);
  69283. }
  69284. else if (engine) {
  69285. this._engine = engine;
  69286. this._engine.postProcesses.push(this);
  69287. }
  69288. this._options = options;
  69289. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  69290. this._reusable = reusable || false;
  69291. this._textureType = textureType;
  69292. this._samplers = samplers || [];
  69293. this._samplers.push("textureSampler");
  69294. this._fragmentUrl = fragmentUrl;
  69295. this._vertexUrl = vertexUrl;
  69296. this._parameters = parameters || [];
  69297. this._parameters.push("scale");
  69298. this._indexParameters = indexParameters;
  69299. if (!blockCompilation) {
  69300. this.updateEffect(defines);
  69301. }
  69302. }
  69303. Object.defineProperty(PostProcess.prototype, "samples", {
  69304. /**
  69305. * Number of sample textures (default: 1)
  69306. */
  69307. get: function () {
  69308. return this._samples;
  69309. },
  69310. set: function (n) {
  69311. var _this = this;
  69312. this._samples = n;
  69313. this._textures.forEach(function (texture) {
  69314. if (texture.samples !== _this._samples) {
  69315. _this._engine.updateRenderTargetTextureSampleCount(texture, _this._samples);
  69316. }
  69317. });
  69318. },
  69319. enumerable: true,
  69320. configurable: true
  69321. });
  69322. Object.defineProperty(PostProcess.prototype, "onActivate", {
  69323. /**
  69324. * A function that is added to the onActivateObservable
  69325. */
  69326. set: function (callback) {
  69327. if (this._onActivateObserver) {
  69328. this.onActivateObservable.remove(this._onActivateObserver);
  69329. }
  69330. if (callback) {
  69331. this._onActivateObserver = this.onActivateObservable.add(callback);
  69332. }
  69333. },
  69334. enumerable: true,
  69335. configurable: true
  69336. });
  69337. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  69338. /**
  69339. * A function that is added to the onSizeChangedObservable
  69340. */
  69341. set: function (callback) {
  69342. if (this._onSizeChangedObserver) {
  69343. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  69344. }
  69345. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  69346. },
  69347. enumerable: true,
  69348. configurable: true
  69349. });
  69350. Object.defineProperty(PostProcess.prototype, "onApply", {
  69351. /**
  69352. * A function that is added to the onApplyObservable
  69353. */
  69354. set: function (callback) {
  69355. if (this._onApplyObserver) {
  69356. this.onApplyObservable.remove(this._onApplyObserver);
  69357. }
  69358. this._onApplyObserver = this.onApplyObservable.add(callback);
  69359. },
  69360. enumerable: true,
  69361. configurable: true
  69362. });
  69363. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  69364. /**
  69365. * A function that is added to the onBeforeRenderObservable
  69366. */
  69367. set: function (callback) {
  69368. if (this._onBeforeRenderObserver) {
  69369. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  69370. }
  69371. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  69372. },
  69373. enumerable: true,
  69374. configurable: true
  69375. });
  69376. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  69377. /**
  69378. * A function that is added to the onAfterRenderObservable
  69379. */
  69380. set: function (callback) {
  69381. if (this._onAfterRenderObserver) {
  69382. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  69383. }
  69384. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  69385. },
  69386. enumerable: true,
  69387. configurable: true
  69388. });
  69389. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  69390. /**
  69391. * 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
  69392. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  69393. */
  69394. get: function () {
  69395. return this._textures.data[this._currentRenderTextureInd];
  69396. },
  69397. set: function (value) {
  69398. this._forcedOutputTexture = value;
  69399. },
  69400. enumerable: true,
  69401. configurable: true
  69402. });
  69403. /**
  69404. * Gets the camera which post process is applied to.
  69405. * @returns The camera the post process is applied to.
  69406. */
  69407. PostProcess.prototype.getCamera = function () {
  69408. return this._camera;
  69409. };
  69410. Object.defineProperty(PostProcess.prototype, "texelSize", {
  69411. /**
  69412. * Gets the texel size of the postprocess.
  69413. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  69414. */
  69415. get: function () {
  69416. if (this._shareOutputWithPostProcess) {
  69417. return this._shareOutputWithPostProcess.texelSize;
  69418. }
  69419. if (this._forcedOutputTexture) {
  69420. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  69421. }
  69422. return this._texelSize;
  69423. },
  69424. enumerable: true,
  69425. configurable: true
  69426. });
  69427. /**
  69428. * Gets the engine which this post process belongs to.
  69429. * @returns The engine the post process was enabled with.
  69430. */
  69431. PostProcess.prototype.getEngine = function () {
  69432. return this._engine;
  69433. };
  69434. /**
  69435. * The effect that is created when initializing the post process.
  69436. * @returns The created effect corrisponding the the postprocess.
  69437. */
  69438. PostProcess.prototype.getEffect = function () {
  69439. return this._effect;
  69440. };
  69441. /**
  69442. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  69443. * @param postProcess The post process to share the output with.
  69444. * @returns This post process.
  69445. */
  69446. PostProcess.prototype.shareOutputWith = function (postProcess) {
  69447. this._disposeTextures();
  69448. this._shareOutputWithPostProcess = postProcess;
  69449. return this;
  69450. };
  69451. /**
  69452. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  69453. * This should be called if the post process that shares output with this post process is disabled/disposed.
  69454. */
  69455. PostProcess.prototype.useOwnOutput = function () {
  69456. if (this._textures.length == 0) {
  69457. this._textures = new BABYLON.SmartArray(2);
  69458. }
  69459. this._shareOutputWithPostProcess = null;
  69460. };
  69461. /**
  69462. * Updates the effect with the current post process compile time values and recompiles the shader.
  69463. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  69464. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  69465. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  69466. * @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
  69467. * @param onCompiled Called when the shader has been compiled.
  69468. * @param onError Called if there is an error when compiling a shader.
  69469. */
  69470. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  69471. if (defines === void 0) { defines = null; }
  69472. if (uniforms === void 0) { uniforms = null; }
  69473. if (samplers === void 0) { samplers = null; }
  69474. 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);
  69475. };
  69476. /**
  69477. * The post process is reusable if it can be used multiple times within one frame.
  69478. * @returns If the post process is reusable
  69479. */
  69480. PostProcess.prototype.isReusable = function () {
  69481. return this._reusable;
  69482. };
  69483. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  69484. PostProcess.prototype.markTextureDirty = function () {
  69485. this.width = -1;
  69486. };
  69487. /**
  69488. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  69489. * 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.
  69490. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  69491. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  69492. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  69493. * @returns The target texture that was bound to be written to.
  69494. */
  69495. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  69496. var _this = this;
  69497. if (sourceTexture === void 0) { sourceTexture = null; }
  69498. camera = camera || this._camera;
  69499. var scene = camera.getScene();
  69500. var engine = scene.getEngine();
  69501. var maxSize = engine.getCaps().maxTextureSize;
  69502. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  69503. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  69504. // 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
  69505. var webVRCamera = camera.parent;
  69506. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  69507. requiredWidth /= 2;
  69508. }
  69509. var desiredWidth = (this._options.width || requiredWidth);
  69510. var desiredHeight = this._options.height || requiredHeight;
  69511. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  69512. if (this.adaptScaleToCurrentViewport) {
  69513. var currentViewport = engine.currentViewport;
  69514. if (currentViewport) {
  69515. desiredWidth *= currentViewport.width;
  69516. desiredHeight *= currentViewport.height;
  69517. }
  69518. }
  69519. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  69520. if (!this._options.width) {
  69521. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  69522. }
  69523. if (!this._options.height) {
  69524. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  69525. }
  69526. }
  69527. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  69528. if (this._textures.length > 0) {
  69529. for (var i = 0; i < this._textures.length; i++) {
  69530. this._engine._releaseTexture(this._textures.data[i]);
  69531. }
  69532. this._textures.reset();
  69533. }
  69534. this.width = desiredWidth;
  69535. this.height = desiredHeight;
  69536. var textureSize = { width: this.width, height: this.height };
  69537. var textureOptions = {
  69538. generateMipMaps: false,
  69539. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  69540. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  69541. samplingMode: this.renderTargetSamplingMode,
  69542. type: this._textureType
  69543. };
  69544. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  69545. if (this._reusable) {
  69546. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  69547. }
  69548. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  69549. this.onSizeChangedObservable.notifyObservers(this);
  69550. }
  69551. this._textures.forEach(function (texture) {
  69552. if (texture.samples !== _this.samples) {
  69553. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  69554. }
  69555. });
  69556. }
  69557. var target;
  69558. if (this._shareOutputWithPostProcess) {
  69559. target = this._shareOutputWithPostProcess.inputTexture;
  69560. }
  69561. else if (this._forcedOutputTexture) {
  69562. target = this._forcedOutputTexture;
  69563. this.width = this._forcedOutputTexture.width;
  69564. this.height = this._forcedOutputTexture.height;
  69565. }
  69566. else {
  69567. target = this.inputTexture;
  69568. }
  69569. // Bind the input of this post process to be used as the output of the previous post process.
  69570. if (this.enablePixelPerfectMode) {
  69571. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  69572. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  69573. }
  69574. else {
  69575. this._scaleRatio.copyFromFloats(1, 1);
  69576. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  69577. }
  69578. this.onActivateObservable.notifyObservers(camera);
  69579. // Clear
  69580. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  69581. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, scene._allowPostProcessClearColor, true, true);
  69582. }
  69583. if (this._reusable) {
  69584. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  69585. }
  69586. return target;
  69587. };
  69588. Object.defineProperty(PostProcess.prototype, "isSupported", {
  69589. /**
  69590. * If the post process is supported.
  69591. */
  69592. get: function () {
  69593. return this._effect.isSupported;
  69594. },
  69595. enumerable: true,
  69596. configurable: true
  69597. });
  69598. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  69599. /**
  69600. * The aspect ratio of the output texture.
  69601. */
  69602. get: function () {
  69603. if (this._shareOutputWithPostProcess) {
  69604. return this._shareOutputWithPostProcess.aspectRatio;
  69605. }
  69606. if (this._forcedOutputTexture) {
  69607. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  69608. }
  69609. return this.width / this.height;
  69610. },
  69611. enumerable: true,
  69612. configurable: true
  69613. });
  69614. /**
  69615. * Get a value indicating if the post-process is ready to be used
  69616. * @returns true if the post-process is ready (shader is compiled)
  69617. */
  69618. PostProcess.prototype.isReady = function () {
  69619. return this._effect && this._effect.isReady();
  69620. };
  69621. /**
  69622. * Binds all textures and uniforms to the shader, this will be run on every pass.
  69623. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  69624. */
  69625. PostProcess.prototype.apply = function () {
  69626. // Check
  69627. if (!this._effect || !this._effect.isReady())
  69628. return null;
  69629. // States
  69630. this._engine.enableEffect(this._effect);
  69631. this._engine.setState(false);
  69632. this._engine.setDepthBuffer(false);
  69633. this._engine.setDepthWrite(false);
  69634. // Alpha
  69635. this._engine.setAlphaMode(this.alphaMode);
  69636. if (this.alphaConstants) {
  69637. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  69638. }
  69639. // Bind the output texture of the preivous post process as the input to this post process.
  69640. var source;
  69641. if (this._shareOutputWithPostProcess) {
  69642. source = this._shareOutputWithPostProcess.inputTexture;
  69643. }
  69644. else if (this._forcedOutputTexture) {
  69645. source = this._forcedOutputTexture;
  69646. }
  69647. else {
  69648. source = this.inputTexture;
  69649. }
  69650. this._effect._bindTexture("textureSampler", source);
  69651. // Parameters
  69652. this._effect.setVector2("scale", this._scaleRatio);
  69653. this.onApplyObservable.notifyObservers(this._effect);
  69654. return this._effect;
  69655. };
  69656. PostProcess.prototype._disposeTextures = function () {
  69657. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  69658. return;
  69659. }
  69660. if (this._textures.length > 0) {
  69661. for (var i = 0; i < this._textures.length; i++) {
  69662. this._engine._releaseTexture(this._textures.data[i]);
  69663. }
  69664. }
  69665. this._textures.dispose();
  69666. };
  69667. /**
  69668. * Disposes the post process.
  69669. * @param camera The camera to dispose the post process on.
  69670. */
  69671. PostProcess.prototype.dispose = function (camera) {
  69672. camera = camera || this._camera;
  69673. this._disposeTextures();
  69674. if (this._scene) {
  69675. var index_1 = this._scene.postProcesses.indexOf(this);
  69676. if (index_1 !== -1) {
  69677. this._scene.postProcesses.splice(index_1, 1);
  69678. }
  69679. }
  69680. else {
  69681. var index_2 = this._engine.postProcesses.indexOf(this);
  69682. if (index_2 !== -1) {
  69683. this._engine.postProcesses.splice(index_2, 1);
  69684. }
  69685. }
  69686. if (!camera) {
  69687. return;
  69688. }
  69689. camera.detachPostProcess(this);
  69690. var index = camera._postProcesses.indexOf(this);
  69691. if (index === 0 && camera._postProcesses.length > 0) {
  69692. var firstPostProcess = this._camera._getFirstPostProcess();
  69693. if (firstPostProcess) {
  69694. firstPostProcess.markTextureDirty();
  69695. }
  69696. }
  69697. this.onActivateObservable.clear();
  69698. this.onAfterRenderObservable.clear();
  69699. this.onApplyObservable.clear();
  69700. this.onBeforeRenderObservable.clear();
  69701. this.onSizeChangedObservable.clear();
  69702. };
  69703. return PostProcess;
  69704. }());
  69705. BABYLON.PostProcess = PostProcess;
  69706. })(BABYLON || (BABYLON = {}));
  69707. //# sourceMappingURL=babylon.postProcess.js.map
  69708. var BABYLON;
  69709. (function (BABYLON) {
  69710. var PassPostProcess = /** @class */ (function (_super) {
  69711. __extends(PassPostProcess, _super);
  69712. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  69713. if (camera === void 0) { camera = null; }
  69714. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69715. if (blockCompilation === void 0) { blockCompilation = false; }
  69716. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  69717. }
  69718. return PassPostProcess;
  69719. }(BABYLON.PostProcess));
  69720. BABYLON.PassPostProcess = PassPostProcess;
  69721. })(BABYLON || (BABYLON = {}));
  69722. //# sourceMappingURL=babylon.passPostProcess.js.map
  69723. var __assign = (this && this.__assign) || function () {
  69724. __assign = Object.assign || function(t) {
  69725. for (var s, i = 1, n = arguments.length; i < n; i++) {
  69726. s = arguments[i];
  69727. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  69728. t[p] = s[p];
  69729. }
  69730. return t;
  69731. };
  69732. return __assign.apply(this, arguments);
  69733. };
  69734. var BABYLON;
  69735. (function (BABYLON) {
  69736. /**
  69737. * Default implementation IShadowGenerator.
  69738. * This is the main object responsible of generating shadows in the framework.
  69739. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  69740. */
  69741. var ShadowGenerator = /** @class */ (function () {
  69742. /**
  69743. * Creates a ShadowGenerator object.
  69744. * A ShadowGenerator is the required tool to use the shadows.
  69745. * Each light casting shadows needs to use its own ShadowGenerator.
  69746. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  69747. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  69748. * @param light The light object generating the shadows.
  69749. * @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.
  69750. */
  69751. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  69752. this._bias = 0.00005;
  69753. this._normalBias = 0;
  69754. this._blurBoxOffset = 1;
  69755. this._blurScale = 2;
  69756. this._blurKernel = 1;
  69757. this._useKernelBlur = false;
  69758. this._filter = ShadowGenerator.FILTER_NONE;
  69759. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  69760. this._contactHardeningLightSizeUVRatio = 0.1;
  69761. this._darkness = 0;
  69762. this._transparencyShadow = false;
  69763. /**
  69764. * Controls the extent to which the shadows fade out at the edge of the frustum
  69765. * Used only by directionals and spots
  69766. */
  69767. this.frustumEdgeFalloff = 0;
  69768. /**
  69769. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  69770. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  69771. * It might on the other hand introduce peter panning.
  69772. */
  69773. this.forceBackFacesOnly = false;
  69774. this._lightDirection = BABYLON.Vector3.Zero();
  69775. this._viewMatrix = BABYLON.Matrix.Zero();
  69776. this._projectionMatrix = BABYLON.Matrix.Zero();
  69777. this._transformMatrix = BABYLON.Matrix.Zero();
  69778. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  69779. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  69780. this._currentFaceIndex = 0;
  69781. this._currentFaceIndexCache = 0;
  69782. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  69783. this._mapSize = mapSize;
  69784. this._light = light;
  69785. this._scene = light.getScene();
  69786. light._shadowGenerator = this;
  69787. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR);
  69788. if (!component) {
  69789. component = new BABYLON.ShadowGeneratorSceneComponent(this._scene);
  69790. this._scene._addComponent(component);
  69791. }
  69792. // Texture type fallback from float to int if not supported.
  69793. var caps = this._scene.getEngine().getCaps();
  69794. if (!useFullFloatFirst) {
  69795. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  69796. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  69797. }
  69798. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  69799. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  69800. }
  69801. else {
  69802. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  69803. }
  69804. }
  69805. else {
  69806. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  69807. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  69808. }
  69809. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  69810. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  69811. }
  69812. else {
  69813. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  69814. }
  69815. }
  69816. this._initializeGenerator();
  69817. this._applyFilterValues();
  69818. }
  69819. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  69820. /**
  69821. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  69822. */
  69823. get: function () {
  69824. return this._bias;
  69825. },
  69826. /**
  69827. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  69828. */
  69829. set: function (bias) {
  69830. this._bias = bias;
  69831. },
  69832. enumerable: true,
  69833. configurable: true
  69834. });
  69835. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  69836. /**
  69837. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  69838. */
  69839. get: function () {
  69840. return this._normalBias;
  69841. },
  69842. /**
  69843. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  69844. */
  69845. set: function (normalBias) {
  69846. this._normalBias = normalBias;
  69847. },
  69848. enumerable: true,
  69849. configurable: true
  69850. });
  69851. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  69852. /**
  69853. * Gets the blur box offset: offset applied during the blur pass.
  69854. * Only usefull if useKernelBlur = false
  69855. */
  69856. get: function () {
  69857. return this._blurBoxOffset;
  69858. },
  69859. /**
  69860. * Sets the blur box offset: offset applied during the blur pass.
  69861. * Only usefull if useKernelBlur = false
  69862. */
  69863. set: function (value) {
  69864. if (this._blurBoxOffset === value) {
  69865. return;
  69866. }
  69867. this._blurBoxOffset = value;
  69868. this._disposeBlurPostProcesses();
  69869. },
  69870. enumerable: true,
  69871. configurable: true
  69872. });
  69873. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  69874. /**
  69875. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  69876. * 2 means half of the size.
  69877. */
  69878. get: function () {
  69879. return this._blurScale;
  69880. },
  69881. /**
  69882. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  69883. * 2 means half of the size.
  69884. */
  69885. set: function (value) {
  69886. if (this._blurScale === value) {
  69887. return;
  69888. }
  69889. this._blurScale = value;
  69890. this._disposeBlurPostProcesses();
  69891. },
  69892. enumerable: true,
  69893. configurable: true
  69894. });
  69895. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  69896. /**
  69897. * Gets the blur kernel: kernel size of the blur pass.
  69898. * Only usefull if useKernelBlur = true
  69899. */
  69900. get: function () {
  69901. return this._blurKernel;
  69902. },
  69903. /**
  69904. * Sets the blur kernel: kernel size of the blur pass.
  69905. * Only usefull if useKernelBlur = true
  69906. */
  69907. set: function (value) {
  69908. if (this._blurKernel === value) {
  69909. return;
  69910. }
  69911. this._blurKernel = value;
  69912. this._disposeBlurPostProcesses();
  69913. },
  69914. enumerable: true,
  69915. configurable: true
  69916. });
  69917. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  69918. /**
  69919. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  69920. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  69921. */
  69922. get: function () {
  69923. return this._useKernelBlur;
  69924. },
  69925. /**
  69926. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  69927. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  69928. */
  69929. set: function (value) {
  69930. if (this._useKernelBlur === value) {
  69931. return;
  69932. }
  69933. this._useKernelBlur = value;
  69934. this._disposeBlurPostProcesses();
  69935. },
  69936. enumerable: true,
  69937. configurable: true
  69938. });
  69939. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  69940. /**
  69941. * Gets the depth scale used in ESM mode.
  69942. */
  69943. get: function () {
  69944. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  69945. },
  69946. /**
  69947. * Sets the depth scale used in ESM mode.
  69948. * This can override the scale stored on the light.
  69949. */
  69950. set: function (value) {
  69951. this._depthScale = value;
  69952. },
  69953. enumerable: true,
  69954. configurable: true
  69955. });
  69956. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  69957. /**
  69958. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  69959. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  69960. */
  69961. get: function () {
  69962. return this._filter;
  69963. },
  69964. /**
  69965. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  69966. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  69967. */
  69968. set: function (value) {
  69969. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  69970. if (this._light.needCube()) {
  69971. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  69972. this.useExponentialShadowMap = true;
  69973. return;
  69974. }
  69975. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  69976. this.useCloseExponentialShadowMap = true;
  69977. return;
  69978. }
  69979. // PCF on cubemap would also be expensive
  69980. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  69981. this.usePoissonSampling = true;
  69982. return;
  69983. }
  69984. }
  69985. // Weblg1 fallback for PCF.
  69986. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  69987. if (this._scene.getEngine().webGLVersion === 1) {
  69988. this.usePoissonSampling = true;
  69989. return;
  69990. }
  69991. }
  69992. if (this._filter === value) {
  69993. return;
  69994. }
  69995. this._filter = value;
  69996. this._disposeBlurPostProcesses();
  69997. this._applyFilterValues();
  69998. this._light._markMeshesAsLightDirty();
  69999. },
  70000. enumerable: true,
  70001. configurable: true
  70002. });
  70003. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  70004. /**
  70005. * Gets if the current filter is set to Poisson Sampling.
  70006. */
  70007. get: function () {
  70008. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  70009. },
  70010. /**
  70011. * Sets the current filter to Poisson Sampling.
  70012. */
  70013. set: function (value) {
  70014. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  70015. return;
  70016. }
  70017. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  70018. },
  70019. enumerable: true,
  70020. configurable: true
  70021. });
  70022. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  70023. /**
  70024. * Gets if the current filter is set to VSM.
  70025. * DEPRECATED. Should use useExponentialShadowMap instead.
  70026. */
  70027. get: function () {
  70028. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  70029. return this.useExponentialShadowMap;
  70030. },
  70031. /**
  70032. * Sets the current filter is to VSM.
  70033. * DEPRECATED. Should use useExponentialShadowMap instead.
  70034. */
  70035. set: function (value) {
  70036. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  70037. this.useExponentialShadowMap = value;
  70038. },
  70039. enumerable: true,
  70040. configurable: true
  70041. });
  70042. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  70043. /**
  70044. * Gets if the current filter is set to blurred VSM.
  70045. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  70046. */
  70047. get: function () {
  70048. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  70049. return this.useBlurExponentialShadowMap;
  70050. },
  70051. /**
  70052. * Sets the current filter is to blurred VSM.
  70053. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  70054. */
  70055. set: function (value) {
  70056. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  70057. this.useBlurExponentialShadowMap = value;
  70058. },
  70059. enumerable: true,
  70060. configurable: true
  70061. });
  70062. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  70063. /**
  70064. * Gets if the current filter is set to ESM.
  70065. */
  70066. get: function () {
  70067. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  70068. },
  70069. /**
  70070. * Sets the current filter is to ESM.
  70071. */
  70072. set: function (value) {
  70073. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  70074. return;
  70075. }
  70076. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  70077. },
  70078. enumerable: true,
  70079. configurable: true
  70080. });
  70081. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  70082. /**
  70083. * Gets if the current filter is set to filtered ESM.
  70084. */
  70085. get: function () {
  70086. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  70087. },
  70088. /**
  70089. * Gets if the current filter is set to filtered ESM.
  70090. */
  70091. set: function (value) {
  70092. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  70093. return;
  70094. }
  70095. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  70096. },
  70097. enumerable: true,
  70098. configurable: true
  70099. });
  70100. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  70101. /**
  70102. * Gets if the current filter is set to "close ESM" (using the inverse of the
  70103. * exponential to prevent steep falloff artifacts).
  70104. */
  70105. get: function () {
  70106. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  70107. },
  70108. /**
  70109. * Sets the current filter to "close ESM" (using the inverse of the
  70110. * exponential to prevent steep falloff artifacts).
  70111. */
  70112. set: function (value) {
  70113. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  70114. return;
  70115. }
  70116. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  70117. },
  70118. enumerable: true,
  70119. configurable: true
  70120. });
  70121. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  70122. /**
  70123. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  70124. * exponential to prevent steep falloff artifacts).
  70125. */
  70126. get: function () {
  70127. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  70128. },
  70129. /**
  70130. * Sets the current filter to filtered "close ESM" (using the inverse of the
  70131. * exponential to prevent steep falloff artifacts).
  70132. */
  70133. set: function (value) {
  70134. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  70135. return;
  70136. }
  70137. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  70138. },
  70139. enumerable: true,
  70140. configurable: true
  70141. });
  70142. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  70143. /**
  70144. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  70145. */
  70146. get: function () {
  70147. return this.filter === ShadowGenerator.FILTER_PCF;
  70148. },
  70149. /**
  70150. * Sets the current filter to "PCF" (percentage closer filtering).
  70151. */
  70152. set: function (value) {
  70153. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  70154. return;
  70155. }
  70156. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  70157. },
  70158. enumerable: true,
  70159. configurable: true
  70160. });
  70161. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  70162. /**
  70163. * Gets the PCF or PCSS Quality.
  70164. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  70165. */
  70166. get: function () {
  70167. return this._filteringQuality;
  70168. },
  70169. /**
  70170. * Sets the PCF or PCSS Quality.
  70171. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  70172. */
  70173. set: function (filteringQuality) {
  70174. this._filteringQuality = filteringQuality;
  70175. },
  70176. enumerable: true,
  70177. configurable: true
  70178. });
  70179. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  70180. /**
  70181. * Gets if the current filter is set to "PCSS" (contact hardening).
  70182. */
  70183. get: function () {
  70184. return this.filter === ShadowGenerator.FILTER_PCSS;
  70185. },
  70186. /**
  70187. * Sets the current filter to "PCSS" (contact hardening).
  70188. */
  70189. set: function (value) {
  70190. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  70191. return;
  70192. }
  70193. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  70194. },
  70195. enumerable: true,
  70196. configurable: true
  70197. });
  70198. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  70199. /**
  70200. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  70201. * Using a ratio helps keeping shape stability independently of the map size.
  70202. *
  70203. * It does not account for the light projection as it was having too much
  70204. * instability during the light setup or during light position changes.
  70205. *
  70206. * Only valid if useContactHardeningShadow is true.
  70207. */
  70208. get: function () {
  70209. return this._contactHardeningLightSizeUVRatio;
  70210. },
  70211. /**
  70212. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  70213. * Using a ratio helps keeping shape stability independently of the map size.
  70214. *
  70215. * It does not account for the light projection as it was having too much
  70216. * instability during the light setup or during light position changes.
  70217. *
  70218. * Only valid if useContactHardeningShadow is true.
  70219. */
  70220. set: function (contactHardeningLightSizeUVRatio) {
  70221. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  70222. },
  70223. enumerable: true,
  70224. configurable: true
  70225. });
  70226. /**
  70227. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  70228. * 0 means strongest and 1 would means no shadow.
  70229. * @returns the darkness.
  70230. */
  70231. ShadowGenerator.prototype.getDarkness = function () {
  70232. return this._darkness;
  70233. };
  70234. /**
  70235. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  70236. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  70237. * @returns the shadow generator allowing fluent coding.
  70238. */
  70239. ShadowGenerator.prototype.setDarkness = function (darkness) {
  70240. if (darkness >= 1.0)
  70241. this._darkness = 1.0;
  70242. else if (darkness <= 0.0)
  70243. this._darkness = 0.0;
  70244. else
  70245. this._darkness = darkness;
  70246. return this;
  70247. };
  70248. /**
  70249. * Sets the ability to have transparent shadow (boolean).
  70250. * @param transparent True if transparent else False
  70251. * @returns the shadow generator allowing fluent coding
  70252. */
  70253. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  70254. this._transparencyShadow = transparent;
  70255. return this;
  70256. };
  70257. /**
  70258. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  70259. * @returns The render target texture if present otherwise, null
  70260. */
  70261. ShadowGenerator.prototype.getShadowMap = function () {
  70262. return this._shadowMap;
  70263. };
  70264. /**
  70265. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  70266. * @returns The render target texture if the shadow map is present otherwise, null
  70267. */
  70268. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  70269. if (this._shadowMap2) {
  70270. return this._shadowMap2;
  70271. }
  70272. return this._shadowMap;
  70273. };
  70274. /**
  70275. * Helper function to add a mesh and its descendants to the list of shadow casters.
  70276. * @param mesh Mesh to add
  70277. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  70278. * @returns the Shadow Generator itself
  70279. */
  70280. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  70281. if (includeDescendants === void 0) { includeDescendants = true; }
  70282. var _a;
  70283. if (!this._shadowMap) {
  70284. return this;
  70285. }
  70286. if (!this._shadowMap.renderList) {
  70287. this._shadowMap.renderList = [];
  70288. }
  70289. this._shadowMap.renderList.push(mesh);
  70290. if (includeDescendants) {
  70291. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  70292. }
  70293. return this;
  70294. };
  70295. /**
  70296. * Helper function to remove a mesh and its descendants from the list of shadow casters
  70297. * @param mesh Mesh to remove
  70298. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  70299. * @returns the Shadow Generator itself
  70300. */
  70301. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  70302. if (includeDescendants === void 0) { includeDescendants = true; }
  70303. if (!this._shadowMap || !this._shadowMap.renderList) {
  70304. return this;
  70305. }
  70306. var index = this._shadowMap.renderList.indexOf(mesh);
  70307. if (index !== -1) {
  70308. this._shadowMap.renderList.splice(index, 1);
  70309. }
  70310. if (includeDescendants) {
  70311. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  70312. var child = _a[_i];
  70313. this.removeShadowCaster(child);
  70314. }
  70315. }
  70316. return this;
  70317. };
  70318. /**
  70319. * Returns the associated light object.
  70320. * @returns the light generating the shadow
  70321. */
  70322. ShadowGenerator.prototype.getLight = function () {
  70323. return this._light;
  70324. };
  70325. ShadowGenerator.prototype._initializeGenerator = function () {
  70326. this._light._markMeshesAsLightDirty();
  70327. this._initializeShadowMap();
  70328. };
  70329. ShadowGenerator.prototype._initializeShadowMap = function () {
  70330. var _this = this;
  70331. // Render target
  70332. var engine = this._scene.getEngine();
  70333. if (engine.webGLVersion > 1) {
  70334. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  70335. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  70336. }
  70337. else {
  70338. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  70339. }
  70340. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70341. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70342. this._shadowMap.anisotropicFilteringLevel = 1;
  70343. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  70344. this._shadowMap.renderParticles = false;
  70345. this._shadowMap.ignoreCameraViewport = true;
  70346. // Record Face Index before render.
  70347. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  70348. _this._currentFaceIndex = faceIndex;
  70349. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  70350. engine.setColorWrite(false);
  70351. }
  70352. });
  70353. // Custom render function.
  70354. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  70355. // Blur if required afer render.
  70356. this._shadowMap.onAfterUnbindObservable.add(function () {
  70357. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  70358. engine.setColorWrite(true);
  70359. }
  70360. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  70361. return;
  70362. }
  70363. var shadowMap = _this.getShadowMapForRendering();
  70364. if (shadowMap) {
  70365. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  70366. }
  70367. });
  70368. // Clear according to the chosen filter.
  70369. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  70370. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  70371. this._shadowMap.onClearObservable.add(function (engine) {
  70372. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  70373. engine.clear(clearOne, false, true, false);
  70374. }
  70375. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  70376. engine.clear(clearZero, true, true, false);
  70377. }
  70378. else {
  70379. engine.clear(clearOne, true, true, false);
  70380. }
  70381. });
  70382. };
  70383. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  70384. var _this = this;
  70385. var engine = this._scene.getEngine();
  70386. var targetSize = this._mapSize / this.blurScale;
  70387. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  70388. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  70389. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70390. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70391. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  70392. }
  70393. if (this.useKernelBlur) {
  70394. 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);
  70395. this._kernelBlurXPostprocess.width = targetSize;
  70396. this._kernelBlurXPostprocess.height = targetSize;
  70397. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  70398. effect.setTexture("textureSampler", _this._shadowMap);
  70399. });
  70400. 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);
  70401. this._kernelBlurXPostprocess.autoClear = false;
  70402. this._kernelBlurYPostprocess.autoClear = false;
  70403. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  70404. this._kernelBlurXPostprocess.packedFloat = true;
  70405. this._kernelBlurYPostprocess.packedFloat = true;
  70406. }
  70407. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  70408. }
  70409. else {
  70410. 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);
  70411. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  70412. effect.setFloat2("screenSize", targetSize, targetSize);
  70413. effect.setTexture("textureSampler", _this._shadowMap);
  70414. });
  70415. this._boxBlurPostprocess.autoClear = false;
  70416. this._blurPostProcesses = [this._boxBlurPostprocess];
  70417. }
  70418. };
  70419. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  70420. var index;
  70421. var engine = this._scene.getEngine();
  70422. if (depthOnlySubMeshes.length) {
  70423. engine.setColorWrite(false);
  70424. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  70425. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  70426. }
  70427. engine.setColorWrite(true);
  70428. }
  70429. for (index = 0; index < opaqueSubMeshes.length; index++) {
  70430. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  70431. }
  70432. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  70433. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  70434. }
  70435. if (this._transparencyShadow) {
  70436. for (index = 0; index < transparentSubMeshes.length; index++) {
  70437. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  70438. }
  70439. }
  70440. };
  70441. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  70442. var _this = this;
  70443. var mesh = subMesh.getRenderingMesh();
  70444. var scene = this._scene;
  70445. var engine = scene.getEngine();
  70446. var material = subMesh.getMaterial();
  70447. if (!material) {
  70448. return;
  70449. }
  70450. // Culling
  70451. engine.setState(material.backFaceCulling);
  70452. // Managing instances
  70453. var batch = mesh._getInstancesRenderList(subMesh._id);
  70454. if (batch.mustReturn) {
  70455. return;
  70456. }
  70457. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  70458. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  70459. engine.enableEffect(this._effect);
  70460. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  70461. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  70462. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  70463. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  70464. this._effect.setVector3("lightData", this._cachedDirection);
  70465. }
  70466. else {
  70467. this._effect.setVector3("lightData", this._cachedPosition);
  70468. }
  70469. if (scene.activeCamera) {
  70470. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  70471. }
  70472. // Alpha test
  70473. if (material && material.needAlphaTesting()) {
  70474. var alphaTexture = material.getAlphaTestTexture();
  70475. if (alphaTexture) {
  70476. this._effect.setTexture("diffuseSampler", alphaTexture);
  70477. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  70478. }
  70479. }
  70480. // Bones
  70481. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  70482. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  70483. }
  70484. // Morph targets
  70485. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  70486. if (this.forceBackFacesOnly) {
  70487. engine.setState(true, 0, false, true);
  70488. }
  70489. // Draw
  70490. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  70491. if (this.forceBackFacesOnly) {
  70492. engine.setState(true, 0, false, false);
  70493. }
  70494. }
  70495. else {
  70496. // Need to reset refresh rate of the shadowMap
  70497. if (this._shadowMap) {
  70498. this._shadowMap.resetRefreshCounter();
  70499. }
  70500. }
  70501. };
  70502. ShadowGenerator.prototype._applyFilterValues = function () {
  70503. if (!this._shadowMap) {
  70504. return;
  70505. }
  70506. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  70507. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  70508. }
  70509. else {
  70510. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  70511. }
  70512. };
  70513. /**
  70514. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  70515. * @param onCompiled Callback triggered at the and of the effects compilation
  70516. * @param options Sets of optional options forcing the compilation with different modes
  70517. */
  70518. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  70519. var _this = this;
  70520. var localOptions = __assign({ useInstances: false }, options);
  70521. var shadowMap = this.getShadowMap();
  70522. if (!shadowMap) {
  70523. if (onCompiled) {
  70524. onCompiled(this);
  70525. }
  70526. return;
  70527. }
  70528. var renderList = shadowMap.renderList;
  70529. if (!renderList) {
  70530. if (onCompiled) {
  70531. onCompiled(this);
  70532. }
  70533. return;
  70534. }
  70535. var subMeshes = new Array();
  70536. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  70537. var mesh = renderList_1[_i];
  70538. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  70539. }
  70540. if (subMeshes.length === 0) {
  70541. if (onCompiled) {
  70542. onCompiled(this);
  70543. }
  70544. return;
  70545. }
  70546. var currentIndex = 0;
  70547. var checkReady = function () {
  70548. if (!_this._scene || !_this._scene.getEngine()) {
  70549. return;
  70550. }
  70551. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  70552. currentIndex++;
  70553. if (currentIndex >= subMeshes.length) {
  70554. if (onCompiled) {
  70555. onCompiled(_this);
  70556. }
  70557. return;
  70558. }
  70559. }
  70560. setTimeout(checkReady, 16);
  70561. };
  70562. checkReady();
  70563. };
  70564. /**
  70565. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  70566. * @param options Sets of optional options forcing the compilation with different modes
  70567. * @returns A promise that resolves when the compilation completes
  70568. */
  70569. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  70570. var _this = this;
  70571. return new Promise(function (resolve) {
  70572. _this.forceCompilation(function () {
  70573. resolve();
  70574. }, options);
  70575. });
  70576. };
  70577. /**
  70578. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  70579. * @param subMesh The submesh we want to render in the shadow map
  70580. * @param useInstances Defines wether will draw in the map using instances
  70581. * @returns true if ready otherwise, false
  70582. */
  70583. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  70584. var defines = [];
  70585. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  70586. defines.push("#define FLOAT");
  70587. }
  70588. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  70589. defines.push("#define ESM");
  70590. }
  70591. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  70592. defines.push("#define DEPTHTEXTURE");
  70593. }
  70594. var attribs = [BABYLON.VertexBuffer.PositionKind];
  70595. var mesh = subMesh.getMesh();
  70596. var material = subMesh.getMaterial();
  70597. // Normal bias.
  70598. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  70599. attribs.push(BABYLON.VertexBuffer.NormalKind);
  70600. defines.push("#define NORMAL");
  70601. if (mesh.nonUniformScaling) {
  70602. defines.push("#define NONUNIFORMSCALING");
  70603. }
  70604. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  70605. defines.push("#define DIRECTIONINLIGHTDATA");
  70606. }
  70607. }
  70608. // Alpha test
  70609. if (material && material.needAlphaTesting()) {
  70610. var alphaTexture = material.getAlphaTestTexture();
  70611. if (alphaTexture) {
  70612. defines.push("#define ALPHATEST");
  70613. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  70614. attribs.push(BABYLON.VertexBuffer.UVKind);
  70615. defines.push("#define UV1");
  70616. }
  70617. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  70618. if (alphaTexture.coordinatesIndex === 1) {
  70619. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  70620. defines.push("#define UV2");
  70621. }
  70622. }
  70623. }
  70624. }
  70625. // Bones
  70626. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  70627. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  70628. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  70629. if (mesh.numBoneInfluencers > 4) {
  70630. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  70631. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  70632. }
  70633. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  70634. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  70635. }
  70636. else {
  70637. defines.push("#define NUM_BONE_INFLUENCERS 0");
  70638. }
  70639. // Morph targets
  70640. var manager = mesh.morphTargetManager;
  70641. var morphInfluencers = 0;
  70642. if (manager) {
  70643. if (manager.numInfluencers > 0) {
  70644. defines.push("#define MORPHTARGETS");
  70645. morphInfluencers = manager.numInfluencers;
  70646. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  70647. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  70648. }
  70649. }
  70650. // Instances
  70651. if (useInstances) {
  70652. defines.push("#define INSTANCES");
  70653. attribs.push("world0");
  70654. attribs.push("world1");
  70655. attribs.push("world2");
  70656. attribs.push("world3");
  70657. }
  70658. // Get correct effect
  70659. var join = defines.join("\n");
  70660. if (this._cachedDefines !== join) {
  70661. this._cachedDefines = join;
  70662. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  70663. }
  70664. if (!this._effect.isReady()) {
  70665. return false;
  70666. }
  70667. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  70668. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  70669. this._initializeBlurRTTAndPostProcesses();
  70670. }
  70671. }
  70672. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  70673. return false;
  70674. }
  70675. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  70676. return false;
  70677. }
  70678. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  70679. return false;
  70680. }
  70681. return true;
  70682. };
  70683. /**
  70684. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  70685. * @param defines Defines of the material we want to update
  70686. * @param lightIndex Index of the light in the enabled light list of the material
  70687. */
  70688. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  70689. var scene = this._scene;
  70690. var light = this._light;
  70691. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  70692. return;
  70693. }
  70694. defines["SHADOW" + lightIndex] = true;
  70695. if (this.useContactHardeningShadow) {
  70696. defines["SHADOWPCSS" + lightIndex] = true;
  70697. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  70698. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  70699. }
  70700. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  70701. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  70702. }
  70703. // else default to high.
  70704. }
  70705. if (this.usePercentageCloserFiltering) {
  70706. defines["SHADOWPCF" + lightIndex] = true;
  70707. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  70708. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  70709. }
  70710. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  70711. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  70712. }
  70713. // else default to high.
  70714. }
  70715. else if (this.usePoissonSampling) {
  70716. defines["SHADOWPOISSON" + lightIndex] = true;
  70717. }
  70718. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  70719. defines["SHADOWESM" + lightIndex] = true;
  70720. }
  70721. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  70722. defines["SHADOWCLOSEESM" + lightIndex] = true;
  70723. }
  70724. if (light.needCube()) {
  70725. defines["SHADOWCUBE" + lightIndex] = true;
  70726. }
  70727. };
  70728. /**
  70729. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  70730. * defined in the generator but impacting the effect).
  70731. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  70732. * @param effect The effect we are binfing the information for
  70733. */
  70734. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  70735. var light = this._light;
  70736. var scene = this._scene;
  70737. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  70738. return;
  70739. }
  70740. var camera = scene.activeCamera;
  70741. if (!camera) {
  70742. return;
  70743. }
  70744. var shadowMap = this.getShadowMap();
  70745. if (!shadowMap) {
  70746. return;
  70747. }
  70748. if (!light.needCube()) {
  70749. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  70750. }
  70751. // Only PCF uses depth stencil texture.
  70752. if (this._filter === ShadowGenerator.FILTER_PCF) {
  70753. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  70754. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  70755. }
  70756. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  70757. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  70758. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  70759. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  70760. }
  70761. else {
  70762. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  70763. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  70764. }
  70765. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  70766. };
  70767. /**
  70768. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  70769. * (eq to shadow prjection matrix * light transform matrix)
  70770. * @returns The transform matrix used to create the shadow map
  70771. */
  70772. ShadowGenerator.prototype.getTransformMatrix = function () {
  70773. var scene = this._scene;
  70774. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  70775. return this._transformMatrix;
  70776. }
  70777. this._currentRenderID = scene.getRenderId();
  70778. this._currentFaceIndexCache = this._currentFaceIndex;
  70779. var lightPosition = this._light.position;
  70780. if (this._light.computeTransformedInformation()) {
  70781. lightPosition = this._light.transformedPosition;
  70782. }
  70783. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  70784. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  70785. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  70786. }
  70787. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  70788. this._cachedPosition.copyFrom(lightPosition);
  70789. this._cachedDirection.copyFrom(this._lightDirection);
  70790. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  70791. var shadowMap = this.getShadowMap();
  70792. if (shadowMap) {
  70793. var renderList = shadowMap.renderList;
  70794. if (renderList) {
  70795. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  70796. }
  70797. }
  70798. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  70799. }
  70800. return this._transformMatrix;
  70801. };
  70802. /**
  70803. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  70804. * Cube and 2D textures for instance.
  70805. */
  70806. ShadowGenerator.prototype.recreateShadowMap = function () {
  70807. var shadowMap = this._shadowMap;
  70808. if (!shadowMap) {
  70809. return;
  70810. }
  70811. // Track render list.
  70812. var renderList = shadowMap.renderList;
  70813. // Clean up existing data.
  70814. this._disposeRTTandPostProcesses();
  70815. // Reinitializes.
  70816. this._initializeGenerator();
  70817. // Reaffect the filter to ensure a correct fallback if necessary.
  70818. this.filter = this.filter;
  70819. // Reaffect the filter.
  70820. this._applyFilterValues();
  70821. // Reaffect Render List.
  70822. this._shadowMap.renderList = renderList;
  70823. };
  70824. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  70825. if (this._shadowMap2) {
  70826. this._shadowMap2.dispose();
  70827. this._shadowMap2 = null;
  70828. }
  70829. if (this._boxBlurPostprocess) {
  70830. this._boxBlurPostprocess.dispose();
  70831. this._boxBlurPostprocess = null;
  70832. }
  70833. if (this._kernelBlurXPostprocess) {
  70834. this._kernelBlurXPostprocess.dispose();
  70835. this._kernelBlurXPostprocess = null;
  70836. }
  70837. if (this._kernelBlurYPostprocess) {
  70838. this._kernelBlurYPostprocess.dispose();
  70839. this._kernelBlurYPostprocess = null;
  70840. }
  70841. this._blurPostProcesses = [];
  70842. };
  70843. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  70844. if (this._shadowMap) {
  70845. this._shadowMap.dispose();
  70846. this._shadowMap = null;
  70847. }
  70848. this._disposeBlurPostProcesses();
  70849. };
  70850. /**
  70851. * Disposes the ShadowGenerator.
  70852. * Returns nothing.
  70853. */
  70854. ShadowGenerator.prototype.dispose = function () {
  70855. this._disposeRTTandPostProcesses();
  70856. if (this._light) {
  70857. this._light._shadowGenerator = null;
  70858. this._light._markMeshesAsLightDirty();
  70859. }
  70860. };
  70861. /**
  70862. * Serializes the shadow generator setup to a json object.
  70863. * @returns The serialized JSON object
  70864. */
  70865. ShadowGenerator.prototype.serialize = function () {
  70866. var serializationObject = {};
  70867. var shadowMap = this.getShadowMap();
  70868. if (!shadowMap) {
  70869. return serializationObject;
  70870. }
  70871. serializationObject.lightId = this._light.id;
  70872. serializationObject.mapSize = shadowMap.getRenderSize();
  70873. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  70874. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  70875. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  70876. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  70877. serializationObject.usePoissonSampling = this.usePoissonSampling;
  70878. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  70879. serializationObject.depthScale = this.depthScale;
  70880. serializationObject.darkness = this.getDarkness();
  70881. serializationObject.blurBoxOffset = this.blurBoxOffset;
  70882. serializationObject.blurKernel = this.blurKernel;
  70883. serializationObject.blurScale = this.blurScale;
  70884. serializationObject.useKernelBlur = this.useKernelBlur;
  70885. serializationObject.transparencyShadow = this._transparencyShadow;
  70886. serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
  70887. serializationObject.bias = this.bias;
  70888. serializationObject.normalBias = this.normalBias;
  70889. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  70890. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  70891. serializationObject.filteringQuality = this.filteringQuality;
  70892. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  70893. serializationObject.renderList = [];
  70894. if (shadowMap.renderList) {
  70895. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  70896. var mesh = shadowMap.renderList[meshIndex];
  70897. serializationObject.renderList.push(mesh.id);
  70898. }
  70899. }
  70900. return serializationObject;
  70901. };
  70902. /**
  70903. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  70904. * @param parsedShadowGenerator The JSON object to parse
  70905. * @param scene The scene to create the shadow map for
  70906. * @returns The parsed shadow generator
  70907. */
  70908. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  70909. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  70910. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  70911. var shadowMap = shadowGenerator.getShadowMap();
  70912. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  70913. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  70914. meshes.forEach(function (mesh) {
  70915. if (!shadowMap) {
  70916. return;
  70917. }
  70918. if (!shadowMap.renderList) {
  70919. shadowMap.renderList = [];
  70920. }
  70921. shadowMap.renderList.push(mesh);
  70922. });
  70923. }
  70924. if (parsedShadowGenerator.usePoissonSampling) {
  70925. shadowGenerator.usePoissonSampling = true;
  70926. }
  70927. else if (parsedShadowGenerator.useExponentialShadowMap) {
  70928. shadowGenerator.useExponentialShadowMap = true;
  70929. }
  70930. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  70931. shadowGenerator.useBlurExponentialShadowMap = true;
  70932. }
  70933. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  70934. shadowGenerator.useCloseExponentialShadowMap = true;
  70935. }
  70936. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  70937. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  70938. }
  70939. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  70940. shadowGenerator.usePercentageCloserFiltering = true;
  70941. }
  70942. else if (parsedShadowGenerator.useContactHardeningShadow) {
  70943. shadowGenerator.useContactHardeningShadow = true;
  70944. }
  70945. if (parsedShadowGenerator.filteringQuality) {
  70946. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  70947. }
  70948. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  70949. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  70950. }
  70951. // Backward compat
  70952. else if (parsedShadowGenerator.useVarianceShadowMap) {
  70953. shadowGenerator.useExponentialShadowMap = true;
  70954. }
  70955. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  70956. shadowGenerator.useBlurExponentialShadowMap = true;
  70957. }
  70958. if (parsedShadowGenerator.depthScale) {
  70959. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  70960. }
  70961. if (parsedShadowGenerator.blurScale) {
  70962. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  70963. }
  70964. if (parsedShadowGenerator.blurBoxOffset) {
  70965. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  70966. }
  70967. if (parsedShadowGenerator.useKernelBlur) {
  70968. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  70969. }
  70970. if (parsedShadowGenerator.blurKernel) {
  70971. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  70972. }
  70973. if (parsedShadowGenerator.bias !== undefined) {
  70974. shadowGenerator.bias = parsedShadowGenerator.bias;
  70975. }
  70976. if (parsedShadowGenerator.normalBias !== undefined) {
  70977. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  70978. }
  70979. if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
  70980. shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
  70981. }
  70982. if (parsedShadowGenerator.darkness) {
  70983. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  70984. }
  70985. if (parsedShadowGenerator.transparencyShadow) {
  70986. shadowGenerator.setTransparencyShadow(true);
  70987. }
  70988. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  70989. return shadowGenerator;
  70990. };
  70991. /**
  70992. * Shadow generator mode None: no filtering applied.
  70993. */
  70994. ShadowGenerator.FILTER_NONE = 0;
  70995. /**
  70996. * Shadow generator mode ESM: Exponential Shadow Mapping.
  70997. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  70998. */
  70999. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  71000. /**
  71001. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  71002. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  71003. */
  71004. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  71005. /**
  71006. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  71007. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  71008. */
  71009. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  71010. /**
  71011. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  71012. * edge artifacts on steep falloff.
  71013. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  71014. */
  71015. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  71016. /**
  71017. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  71018. * edge artifacts on steep falloff.
  71019. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  71020. */
  71021. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  71022. /**
  71023. * Shadow generator mode PCF: Percentage Closer Filtering
  71024. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  71025. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  71026. */
  71027. ShadowGenerator.FILTER_PCF = 6;
  71028. /**
  71029. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  71030. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  71031. * Contact Hardening
  71032. */
  71033. ShadowGenerator.FILTER_PCSS = 7;
  71034. /**
  71035. * Reserved for PCF and PCSS
  71036. * Highest Quality.
  71037. *
  71038. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  71039. *
  71040. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  71041. */
  71042. ShadowGenerator.QUALITY_HIGH = 0;
  71043. /**
  71044. * Reserved for PCF and PCSS
  71045. * Good tradeoff for quality/perf cross devices
  71046. *
  71047. * Execute PCF on a 3*3 kernel.
  71048. *
  71049. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  71050. */
  71051. ShadowGenerator.QUALITY_MEDIUM = 1;
  71052. /**
  71053. * Reserved for PCF and PCSS
  71054. * The lowest quality but the fastest.
  71055. *
  71056. * Execute PCF on a 1*1 kernel.
  71057. *
  71058. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  71059. */
  71060. ShadowGenerator.QUALITY_LOW = 2;
  71061. return ShadowGenerator;
  71062. }());
  71063. BABYLON.ShadowGenerator = ShadowGenerator;
  71064. })(BABYLON || (BABYLON = {}));
  71065. //# sourceMappingURL=babylon.shadowGenerator.js.map
  71066. var BABYLON;
  71067. (function (BABYLON) {
  71068. // Adds the parser to the scene parsers.
  71069. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR, function (parsedData, scene, container, rootUrl) {
  71070. // Shadows
  71071. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  71072. for (var index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  71073. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  71074. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  71075. // SG would be available on their associated lights
  71076. }
  71077. }
  71078. });
  71079. /**
  71080. * Defines the shadow generator component responsible to manage any shadow generators
  71081. * in a given scene.
  71082. */
  71083. var ShadowGeneratorSceneComponent = /** @class */ (function () {
  71084. /**
  71085. * Creates a new instance of the component for the given scene
  71086. * @param scene Defines the scene to register the component in
  71087. */
  71088. function ShadowGeneratorSceneComponent(scene) {
  71089. /**
  71090. * The component name helpfull to identify the component in the list of scene components.
  71091. */
  71092. this.name = BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR;
  71093. this.scene = scene;
  71094. }
  71095. /**
  71096. * Registers the component in a given scene
  71097. */
  71098. ShadowGeneratorSceneComponent.prototype.register = function () {
  71099. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR, this, this._gatherRenderTargets);
  71100. };
  71101. /**
  71102. * Rebuilds the elements related to this component in case of
  71103. * context lost for instance.
  71104. */
  71105. ShadowGeneratorSceneComponent.prototype.rebuild = function () {
  71106. // Nothing To Do Here.
  71107. };
  71108. /**
  71109. * Serializes the component data to the specified json object
  71110. * @param serializationObject The object to serialize to
  71111. */
  71112. ShadowGeneratorSceneComponent.prototype.serialize = function (serializationObject) {
  71113. // Shadows
  71114. serializationObject.shadowGenerators = [];
  71115. var lights = this.scene.lights;
  71116. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  71117. var light = lights_1[_i];
  71118. var shadowGenerator = light.getShadowGenerator();
  71119. if (shadowGenerator) {
  71120. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  71121. }
  71122. }
  71123. };
  71124. /**
  71125. * Adds all the element from the container to the scene
  71126. * @param container the container holding the elements
  71127. */
  71128. ShadowGeneratorSceneComponent.prototype.addFromContainer = function (container) {
  71129. // Nothing To Do Here. (directly attached to a light)
  71130. };
  71131. /**
  71132. * Removes all the elements in the container from the scene
  71133. * @param container contains the elements to remove
  71134. */
  71135. ShadowGeneratorSceneComponent.prototype.removeFromContainer = function (container) {
  71136. // Nothing To Do Here. (directly attached to a light)
  71137. };
  71138. /**
  71139. * Rebuilds the elements related to this component in case of
  71140. * context lost for instance.
  71141. */
  71142. ShadowGeneratorSceneComponent.prototype.dispose = function () {
  71143. // Nothing To Do Here.
  71144. };
  71145. ShadowGeneratorSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  71146. // Shadows
  71147. var scene = this.scene;
  71148. if (this.scene.shadowsEnabled) {
  71149. for (var lightIndex = 0; lightIndex < scene.lights.length; lightIndex++) {
  71150. var light = scene.lights[lightIndex];
  71151. var shadowGenerator = light.getShadowGenerator();
  71152. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  71153. var shadowMap = (shadowGenerator.getShadowMap());
  71154. if (scene.textures.indexOf(shadowMap) !== -1) {
  71155. renderTargets.push(shadowMap);
  71156. }
  71157. }
  71158. }
  71159. }
  71160. };
  71161. return ShadowGeneratorSceneComponent;
  71162. }());
  71163. BABYLON.ShadowGeneratorSceneComponent = ShadowGeneratorSceneComponent;
  71164. })(BABYLON || (BABYLON = {}));
  71165. //# sourceMappingURL=babylon.shadowGeneratorSceneComponent.js.map
  71166. var BABYLON;
  71167. (function (BABYLON) {
  71168. var DefaultLoadingScreen = /** @class */ (function () {
  71169. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  71170. if (_loadingText === void 0) { _loadingText = ""; }
  71171. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  71172. var _this = this;
  71173. this._renderingCanvas = _renderingCanvas;
  71174. this._loadingText = _loadingText;
  71175. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  71176. // Resize
  71177. this._resizeLoadingUI = function () {
  71178. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  71179. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  71180. if (!_this._loadingDiv) {
  71181. return;
  71182. }
  71183. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  71184. _this._loadingDiv.style.left = canvasRect.left + "px";
  71185. _this._loadingDiv.style.top = canvasRect.top + "px";
  71186. _this._loadingDiv.style.width = canvasRect.width + "px";
  71187. _this._loadingDiv.style.height = canvasRect.height + "px";
  71188. };
  71189. }
  71190. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  71191. if (this._loadingDiv) {
  71192. // Do not add a loading screen if there is already one
  71193. return;
  71194. }
  71195. this._loadingDiv = document.createElement("div");
  71196. this._loadingDiv.id = "babylonjsLoadingDiv";
  71197. this._loadingDiv.style.opacity = "0";
  71198. this._loadingDiv.style.transition = "opacity 1.5s ease";
  71199. this._loadingDiv.style.pointerEvents = "none";
  71200. // Loading text
  71201. this._loadingTextDiv = document.createElement("div");
  71202. this._loadingTextDiv.style.position = "absolute";
  71203. this._loadingTextDiv.style.left = "0";
  71204. this._loadingTextDiv.style.top = "50%";
  71205. this._loadingTextDiv.style.marginTop = "80px";
  71206. this._loadingTextDiv.style.width = "100%";
  71207. this._loadingTextDiv.style.height = "20px";
  71208. this._loadingTextDiv.style.fontFamily = "Arial";
  71209. this._loadingTextDiv.style.fontSize = "14px";
  71210. this._loadingTextDiv.style.color = "white";
  71211. this._loadingTextDiv.style.textAlign = "center";
  71212. this._loadingTextDiv.innerHTML = "Loading";
  71213. this._loadingDiv.appendChild(this._loadingTextDiv);
  71214. //set the predefined text
  71215. this._loadingTextDiv.innerHTML = this._loadingText;
  71216. // Generating keyframes
  71217. var style = document.createElement('style');
  71218. style.type = 'text/css';
  71219. 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 }";
  71220. style.innerHTML = keyFrames;
  71221. document.getElementsByTagName('head')[0].appendChild(style);
  71222. // Loading img
  71223. var imgBack = new Image();
  71224. 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";
  71225. imgBack.style.position = "absolute";
  71226. imgBack.style.left = "50%";
  71227. imgBack.style.top = "50%";
  71228. imgBack.style.marginLeft = "-60px";
  71229. imgBack.style.marginTop = "-60px";
  71230. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  71231. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  71232. imgBack.style.transformOrigin = "50% 50%";
  71233. imgBack.style.webkitTransformOrigin = "50% 50%";
  71234. this._loadingDiv.appendChild(imgBack);
  71235. this._resizeLoadingUI();
  71236. window.addEventListener("resize", this._resizeLoadingUI);
  71237. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  71238. document.body.appendChild(this._loadingDiv);
  71239. this._loadingDiv.style.opacity = "1";
  71240. };
  71241. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  71242. var _this = this;
  71243. if (!this._loadingDiv) {
  71244. return;
  71245. }
  71246. var onTransitionEnd = function () {
  71247. if (!_this._loadingDiv) {
  71248. return;
  71249. }
  71250. document.body.removeChild(_this._loadingDiv);
  71251. window.removeEventListener("resize", _this._resizeLoadingUI);
  71252. _this._loadingDiv = null;
  71253. };
  71254. this._loadingDiv.style.opacity = "0";
  71255. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  71256. };
  71257. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  71258. set: function (text) {
  71259. this._loadingText = text;
  71260. if (this._loadingTextDiv) {
  71261. this._loadingTextDiv.innerHTML = this._loadingText;
  71262. }
  71263. },
  71264. enumerable: true,
  71265. configurable: true
  71266. });
  71267. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  71268. get: function () {
  71269. return this._loadingDivBackgroundColor;
  71270. },
  71271. set: function (color) {
  71272. this._loadingDivBackgroundColor = color;
  71273. if (!this._loadingDiv) {
  71274. return;
  71275. }
  71276. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  71277. },
  71278. enumerable: true,
  71279. configurable: true
  71280. });
  71281. return DefaultLoadingScreen;
  71282. }());
  71283. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  71284. })(BABYLON || (BABYLON = {}));
  71285. //# sourceMappingURL=babylon.loadingScreen.js.map
  71286. var BABYLON;
  71287. (function (BABYLON) {
  71288. var SceneLoaderProgressEvent = /** @class */ (function () {
  71289. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  71290. this.lengthComputable = lengthComputable;
  71291. this.loaded = loaded;
  71292. this.total = total;
  71293. }
  71294. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  71295. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  71296. };
  71297. return SceneLoaderProgressEvent;
  71298. }());
  71299. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  71300. var SceneLoader = /** @class */ (function () {
  71301. function SceneLoader() {
  71302. }
  71303. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  71304. get: function () {
  71305. return 0;
  71306. },
  71307. enumerable: true,
  71308. configurable: true
  71309. });
  71310. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  71311. get: function () {
  71312. return 1;
  71313. },
  71314. enumerable: true,
  71315. configurable: true
  71316. });
  71317. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  71318. get: function () {
  71319. return 2;
  71320. },
  71321. enumerable: true,
  71322. configurable: true
  71323. });
  71324. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  71325. get: function () {
  71326. return 3;
  71327. },
  71328. enumerable: true,
  71329. configurable: true
  71330. });
  71331. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  71332. get: function () {
  71333. return SceneLoader._ForceFullSceneLoadingForIncremental;
  71334. },
  71335. set: function (value) {
  71336. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  71337. },
  71338. enumerable: true,
  71339. configurable: true
  71340. });
  71341. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  71342. get: function () {
  71343. return SceneLoader._ShowLoadingScreen;
  71344. },
  71345. set: function (value) {
  71346. SceneLoader._ShowLoadingScreen = value;
  71347. },
  71348. enumerable: true,
  71349. configurable: true
  71350. });
  71351. Object.defineProperty(SceneLoader, "loggingLevel", {
  71352. get: function () {
  71353. return SceneLoader._loggingLevel;
  71354. },
  71355. set: function (value) {
  71356. SceneLoader._loggingLevel = value;
  71357. },
  71358. enumerable: true,
  71359. configurable: true
  71360. });
  71361. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  71362. get: function () {
  71363. return SceneLoader._CleanBoneMatrixWeights;
  71364. },
  71365. set: function (value) {
  71366. SceneLoader._CleanBoneMatrixWeights = value;
  71367. },
  71368. enumerable: true,
  71369. configurable: true
  71370. });
  71371. SceneLoader._getDefaultPlugin = function () {
  71372. return SceneLoader._registeredPlugins[".babylon"];
  71373. };
  71374. SceneLoader._getPluginForExtension = function (extension) {
  71375. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  71376. if (registeredPlugin) {
  71377. return registeredPlugin;
  71378. }
  71379. 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");
  71380. return SceneLoader._getDefaultPlugin();
  71381. };
  71382. SceneLoader._getPluginForDirectLoad = function (data) {
  71383. for (var extension in SceneLoader._registeredPlugins) {
  71384. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  71385. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  71386. return SceneLoader._registeredPlugins[extension];
  71387. }
  71388. }
  71389. return SceneLoader._getDefaultPlugin();
  71390. };
  71391. SceneLoader._getPluginForFilename = function (sceneFilename) {
  71392. if (sceneFilename.name) {
  71393. sceneFilename = sceneFilename.name;
  71394. }
  71395. var queryStringPosition = sceneFilename.indexOf("?");
  71396. if (queryStringPosition !== -1) {
  71397. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  71398. }
  71399. var dotPosition = sceneFilename.lastIndexOf(".");
  71400. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  71401. return SceneLoader._getPluginForExtension(extension);
  71402. };
  71403. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  71404. SceneLoader._getDirectLoad = function (sceneFilename) {
  71405. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  71406. return sceneFilename.substr(5);
  71407. }
  71408. return null;
  71409. };
  71410. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  71411. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  71412. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  71413. var plugin;
  71414. if (registeredPlugin.plugin.createPlugin) {
  71415. plugin = registeredPlugin.plugin.createPlugin();
  71416. }
  71417. else {
  71418. plugin = registeredPlugin.plugin;
  71419. }
  71420. var useArrayBuffer = registeredPlugin.isBinary;
  71421. var database;
  71422. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  71423. var dataCallback = function (data, responseURL) {
  71424. if (scene.isDisposed) {
  71425. onError("Scene has been disposed");
  71426. return;
  71427. }
  71428. scene.database = database;
  71429. onSuccess(plugin, data, responseURL);
  71430. };
  71431. var request = null;
  71432. var pluginDisposed = false;
  71433. var onDisposeObservable = plugin.onDisposeObservable;
  71434. if (onDisposeObservable) {
  71435. onDisposeObservable.add(function () {
  71436. pluginDisposed = true;
  71437. if (request) {
  71438. request.abort();
  71439. request = null;
  71440. }
  71441. onDispose();
  71442. });
  71443. }
  71444. var manifestChecked = function () {
  71445. if (pluginDisposed) {
  71446. return;
  71447. }
  71448. var url = rootUrl + sceneFilename;
  71449. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  71450. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  71451. } : undefined, database, useArrayBuffer, function (request, exception) {
  71452. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  71453. });
  71454. };
  71455. if (directLoad) {
  71456. dataCallback(directLoad);
  71457. return plugin;
  71458. }
  71459. if (rootUrl.indexOf("file:") === -1) {
  71460. var engine = scene.getEngine();
  71461. var canUseOfflineSupport = engine.enableOfflineSupport;
  71462. if (canUseOfflineSupport) {
  71463. // Also check for exceptions
  71464. var exceptionFound = false;
  71465. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  71466. var regex = _a[_i];
  71467. if (regex.test(rootUrl + sceneFilename)) {
  71468. exceptionFound = true;
  71469. break;
  71470. }
  71471. }
  71472. canUseOfflineSupport = !exceptionFound;
  71473. }
  71474. if (canUseOfflineSupport) {
  71475. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  71476. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked, engine.disableManifestCheck);
  71477. }
  71478. else {
  71479. manifestChecked();
  71480. }
  71481. }
  71482. // Loading file from disk via input file or drag'n'drop
  71483. else {
  71484. var fileOrString = sceneFilename;
  71485. if (fileOrString.name) { // File
  71486. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  71487. }
  71488. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  71489. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  71490. }
  71491. else {
  71492. onError("Unable to find file named " + sceneFilename);
  71493. }
  71494. }
  71495. return plugin;
  71496. };
  71497. // Public functions
  71498. SceneLoader.GetPluginForExtension = function (extension) {
  71499. return SceneLoader._getPluginForExtension(extension).plugin;
  71500. };
  71501. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  71502. return !!SceneLoader._registeredPlugins[extension];
  71503. };
  71504. SceneLoader.RegisterPlugin = function (plugin) {
  71505. if (typeof plugin.extensions === "string") {
  71506. var extension = plugin.extensions;
  71507. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  71508. plugin: plugin,
  71509. isBinary: false
  71510. };
  71511. }
  71512. else {
  71513. var extensions = plugin.extensions;
  71514. Object.keys(extensions).forEach(function (extension) {
  71515. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  71516. plugin: plugin,
  71517. isBinary: extensions[extension].isBinary
  71518. };
  71519. });
  71520. }
  71521. };
  71522. /**
  71523. * Import meshes into a scene
  71524. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  71525. * @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)
  71526. * @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)
  71527. * @param scene the instance of BABYLON.Scene to append to
  71528. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  71529. * @param onProgress a callback with a progress event for each file being loaded
  71530. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  71531. * @param pluginExtension the extension used to determine the plugin
  71532. * @returns The loaded plugin
  71533. */
  71534. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  71535. if (sceneFilename === void 0) { sceneFilename = ""; }
  71536. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  71537. if (onSuccess === void 0) { onSuccess = null; }
  71538. if (onProgress === void 0) { onProgress = null; }
  71539. if (onError === void 0) { onError = null; }
  71540. if (pluginExtension === void 0) { pluginExtension = null; }
  71541. if (!scene) {
  71542. BABYLON.Tools.Error("No scene available to import mesh to");
  71543. return null;
  71544. }
  71545. if (!sceneFilename) {
  71546. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  71547. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  71548. }
  71549. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  71550. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  71551. return null;
  71552. }
  71553. var loadingToken = {};
  71554. scene._addPendingData(loadingToken);
  71555. var disposeHandler = function () {
  71556. scene._removePendingData(loadingToken);
  71557. };
  71558. var errorHandler = function (message, exception) {
  71559. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  71560. if (onError) {
  71561. onError(scene, errorMessage, exception);
  71562. }
  71563. else {
  71564. BABYLON.Tools.Error(errorMessage);
  71565. // should the exception be thrown?
  71566. }
  71567. disposeHandler();
  71568. };
  71569. var progressHandler = onProgress ? function (event) {
  71570. try {
  71571. onProgress(event);
  71572. }
  71573. catch (e) {
  71574. errorHandler("Error in onProgress callback", e);
  71575. }
  71576. } : undefined;
  71577. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  71578. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  71579. if (onSuccess) {
  71580. try {
  71581. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  71582. }
  71583. catch (e) {
  71584. errorHandler("Error in onSuccess callback", e);
  71585. }
  71586. }
  71587. scene._removePendingData(loadingToken);
  71588. };
  71589. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  71590. if (plugin.rewriteRootURL) {
  71591. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  71592. }
  71593. if (sceneFilename === "") {
  71594. if (sceneFilename === "") {
  71595. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  71596. }
  71597. }
  71598. if (plugin.importMesh) {
  71599. var syncedPlugin = plugin;
  71600. var meshes = new Array();
  71601. var particleSystems = new Array();
  71602. var skeletons = new Array();
  71603. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  71604. return;
  71605. }
  71606. scene.loadingPluginName = plugin.name;
  71607. successHandler(meshes, particleSystems, skeletons, []);
  71608. }
  71609. else {
  71610. var asyncedPlugin = plugin;
  71611. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler, rootUrl + sceneFilename).then(function (result) {
  71612. scene.loadingPluginName = plugin.name;
  71613. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  71614. }).catch(function (error) {
  71615. errorHandler(error.message, error);
  71616. });
  71617. }
  71618. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  71619. };
  71620. /**
  71621. * Import meshes into a scene
  71622. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  71623. * @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)
  71624. * @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)
  71625. * @param scene the instance of BABYLON.Scene to append to
  71626. * @param onProgress a callback with a progress event for each file being loaded
  71627. * @param pluginExtension the extension used to determine the plugin
  71628. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  71629. */
  71630. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  71631. if (sceneFilename === void 0) { sceneFilename = ""; }
  71632. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  71633. if (onProgress === void 0) { onProgress = null; }
  71634. if (pluginExtension === void 0) { pluginExtension = null; }
  71635. return new Promise(function (resolve, reject) {
  71636. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  71637. resolve({
  71638. meshes: meshes,
  71639. particleSystems: particleSystems,
  71640. skeletons: skeletons,
  71641. animationGroups: animationGroups
  71642. });
  71643. }, onProgress, function (scene, message, exception) {
  71644. reject(exception || new Error(message));
  71645. }, pluginExtension);
  71646. });
  71647. };
  71648. /**
  71649. * Load a scene
  71650. * @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)
  71651. * @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)
  71652. * @param engine is the instance of BABYLON.Engine to use to create the scene
  71653. * @param onSuccess a callback with the scene when import succeeds
  71654. * @param onProgress a callback with a progress event for each file being loaded
  71655. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  71656. * @param pluginExtension the extension used to determine the plugin
  71657. * @returns The loaded plugin
  71658. */
  71659. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  71660. if (onSuccess === void 0) { onSuccess = null; }
  71661. if (onProgress === void 0) { onProgress = null; }
  71662. if (onError === void 0) { onError = null; }
  71663. if (pluginExtension === void 0) { pluginExtension = null; }
  71664. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  71665. };
  71666. /**
  71667. * Load a scene
  71668. * @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)
  71669. * @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)
  71670. * @param engine is the instance of BABYLON.Engine to use to create the scene
  71671. * @param onProgress a callback with a progress event for each file being loaded
  71672. * @param pluginExtension the extension used to determine the plugin
  71673. * @returns The loaded scene
  71674. */
  71675. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  71676. if (onProgress === void 0) { onProgress = null; }
  71677. if (pluginExtension === void 0) { pluginExtension = null; }
  71678. return new Promise(function (resolve, reject) {
  71679. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  71680. resolve(scene);
  71681. }, onProgress, function (scene, message, exception) {
  71682. reject(exception || new Error(message));
  71683. }, pluginExtension);
  71684. });
  71685. };
  71686. /**
  71687. * Append a scene
  71688. * @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)
  71689. * @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)
  71690. * @param scene is the instance of BABYLON.Scene to append to
  71691. * @param onSuccess a callback with the scene when import succeeds
  71692. * @param onProgress a callback with a progress event for each file being loaded
  71693. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  71694. * @param pluginExtension the extension used to determine the plugin
  71695. * @returns The loaded plugin
  71696. */
  71697. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  71698. if (sceneFilename === void 0) { sceneFilename = ""; }
  71699. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  71700. if (onSuccess === void 0) { onSuccess = null; }
  71701. if (onProgress === void 0) { onProgress = null; }
  71702. if (onError === void 0) { onError = null; }
  71703. if (pluginExtension === void 0) { pluginExtension = null; }
  71704. if (!scene) {
  71705. BABYLON.Tools.Error("No scene available to append to");
  71706. return null;
  71707. }
  71708. if (!sceneFilename) {
  71709. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  71710. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  71711. }
  71712. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  71713. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  71714. return null;
  71715. }
  71716. if (SceneLoader.ShowLoadingScreen) {
  71717. scene.getEngine().displayLoadingUI();
  71718. }
  71719. var loadingToken = {};
  71720. scene._addPendingData(loadingToken);
  71721. var disposeHandler = function () {
  71722. scene._removePendingData(loadingToken);
  71723. scene.getEngine().hideLoadingUI();
  71724. };
  71725. var errorHandler = function (message, exception) {
  71726. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  71727. if (onError) {
  71728. onError(scene, errorMessage, exception);
  71729. }
  71730. else {
  71731. BABYLON.Tools.Error(errorMessage);
  71732. // should the exception be thrown?
  71733. }
  71734. disposeHandler();
  71735. };
  71736. var progressHandler = onProgress ? function (event) {
  71737. try {
  71738. onProgress(event);
  71739. }
  71740. catch (e) {
  71741. errorHandler("Error in onProgress callback", e);
  71742. }
  71743. } : undefined;
  71744. var successHandler = function () {
  71745. if (onSuccess) {
  71746. try {
  71747. onSuccess(scene);
  71748. }
  71749. catch (e) {
  71750. errorHandler("Error in onSuccess callback", e);
  71751. }
  71752. }
  71753. scene._removePendingData(loadingToken);
  71754. };
  71755. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  71756. if (sceneFilename === "") {
  71757. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  71758. }
  71759. if (plugin.load) {
  71760. var syncedPlugin = plugin;
  71761. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  71762. return;
  71763. }
  71764. scene.loadingPluginName = plugin.name;
  71765. successHandler();
  71766. }
  71767. else {
  71768. var asyncedPlugin = plugin;
  71769. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler, rootUrl + sceneFilename).then(function () {
  71770. scene.loadingPluginName = plugin.name;
  71771. successHandler();
  71772. }).catch(function (error) {
  71773. errorHandler(error.message, error);
  71774. });
  71775. }
  71776. if (SceneLoader.ShowLoadingScreen) {
  71777. scene.executeWhenReady(function () {
  71778. scene.getEngine().hideLoadingUI();
  71779. });
  71780. }
  71781. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  71782. };
  71783. /**
  71784. * Append a scene
  71785. * @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)
  71786. * @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)
  71787. * @param scene is the instance of BABYLON.Scene to append to
  71788. * @param onProgress a callback with a progress event for each file being loaded
  71789. * @param pluginExtension the extension used to determine the plugin
  71790. * @returns The given scene
  71791. */
  71792. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  71793. if (sceneFilename === void 0) { sceneFilename = ""; }
  71794. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  71795. if (onProgress === void 0) { onProgress = null; }
  71796. if (pluginExtension === void 0) { pluginExtension = null; }
  71797. return new Promise(function (resolve, reject) {
  71798. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  71799. resolve(scene);
  71800. }, onProgress, function (scene, message, exception) {
  71801. reject(exception || new Error(message));
  71802. }, pluginExtension);
  71803. });
  71804. };
  71805. /**
  71806. * Load a scene into an asset container
  71807. * @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)
  71808. * @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)
  71809. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  71810. * @param onSuccess a callback with the scene when import succeeds
  71811. * @param onProgress a callback with a progress event for each file being loaded
  71812. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  71813. * @param pluginExtension the extension used to determine the plugin
  71814. * @returns The loaded plugin
  71815. */
  71816. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  71817. if (sceneFilename === void 0) { sceneFilename = ""; }
  71818. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  71819. if (onSuccess === void 0) { onSuccess = null; }
  71820. if (onProgress === void 0) { onProgress = null; }
  71821. if (onError === void 0) { onError = null; }
  71822. if (pluginExtension === void 0) { pluginExtension = null; }
  71823. if (!scene) {
  71824. BABYLON.Tools.Error("No scene available to load asset container to");
  71825. return null;
  71826. }
  71827. if (!sceneFilename) {
  71828. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  71829. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  71830. }
  71831. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  71832. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  71833. return null;
  71834. }
  71835. var loadingToken = {};
  71836. scene._addPendingData(loadingToken);
  71837. var disposeHandler = function () {
  71838. scene._removePendingData(loadingToken);
  71839. };
  71840. var errorHandler = function (message, exception) {
  71841. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  71842. if (onError) {
  71843. onError(scene, errorMessage, exception);
  71844. }
  71845. else {
  71846. BABYLON.Tools.Error(errorMessage);
  71847. // should the exception be thrown?
  71848. }
  71849. disposeHandler();
  71850. };
  71851. var progressHandler = onProgress ? function (event) {
  71852. try {
  71853. onProgress(event);
  71854. }
  71855. catch (e) {
  71856. errorHandler("Error in onProgress callback", e);
  71857. }
  71858. } : undefined;
  71859. var successHandler = function (assets) {
  71860. if (onSuccess) {
  71861. try {
  71862. onSuccess(assets);
  71863. }
  71864. catch (e) {
  71865. errorHandler("Error in onSuccess callback", e);
  71866. }
  71867. }
  71868. scene._removePendingData(loadingToken);
  71869. };
  71870. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  71871. if (plugin.loadAssetContainer) {
  71872. var syncedPlugin = plugin;
  71873. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  71874. if (!assetContainer) {
  71875. return;
  71876. }
  71877. scene.loadingPluginName = plugin.name;
  71878. successHandler(assetContainer);
  71879. }
  71880. else if (plugin.loadAssetContainerAsync) {
  71881. var asyncedPlugin = plugin;
  71882. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler, rootUrl + sceneFilename).then(function (assetContainer) {
  71883. scene.loadingPluginName = plugin.name;
  71884. successHandler(assetContainer);
  71885. }).catch(function (error) {
  71886. errorHandler(error.message, error);
  71887. });
  71888. }
  71889. else {
  71890. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  71891. }
  71892. if (SceneLoader.ShowLoadingScreen) {
  71893. scene.executeWhenReady(function () {
  71894. scene.getEngine().hideLoadingUI();
  71895. });
  71896. }
  71897. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  71898. };
  71899. /**
  71900. * Load a scene into an asset container
  71901. * @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)
  71902. * @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)
  71903. * @param scene is the instance of BABYLON.Scene to append to
  71904. * @param onProgress a callback with a progress event for each file being loaded
  71905. * @param pluginExtension the extension used to determine the plugin
  71906. * @returns The loaded asset container
  71907. */
  71908. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  71909. if (sceneFilename === void 0) { sceneFilename = ""; }
  71910. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  71911. if (onProgress === void 0) { onProgress = null; }
  71912. if (pluginExtension === void 0) { pluginExtension = null; }
  71913. return new Promise(function (resolve, reject) {
  71914. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  71915. resolve(assetContainer);
  71916. }, onProgress, function (scene, message, exception) {
  71917. reject(exception || new Error(message));
  71918. }, pluginExtension);
  71919. });
  71920. };
  71921. // Flags
  71922. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  71923. SceneLoader._ShowLoadingScreen = true;
  71924. SceneLoader._CleanBoneMatrixWeights = false;
  71925. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  71926. // Members
  71927. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  71928. SceneLoader._registeredPlugins = {};
  71929. return SceneLoader;
  71930. }());
  71931. BABYLON.SceneLoader = SceneLoader;
  71932. ;
  71933. })(BABYLON || (BABYLON = {}));
  71934. //# sourceMappingURL=babylon.sceneLoader.js.map
  71935. var BABYLON;
  71936. (function (BABYLON) {
  71937. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  71938. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  71939. var parsedMaterial = parsedData.materials[index];
  71940. if (parsedMaterial.id === id) {
  71941. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  71942. }
  71943. }
  71944. return null;
  71945. };
  71946. var isDescendantOf = function (mesh, names, hierarchyIds) {
  71947. for (var i in names) {
  71948. if (mesh.name === names[i]) {
  71949. hierarchyIds.push(mesh.id);
  71950. return true;
  71951. }
  71952. }
  71953. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  71954. hierarchyIds.push(mesh.id);
  71955. return true;
  71956. }
  71957. return false;
  71958. };
  71959. var logOperation = function (operation, producer) {
  71960. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  71961. };
  71962. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  71963. if (addToScene === void 0) { addToScene = false; }
  71964. var container = new BABYLON.AssetContainer(scene);
  71965. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  71966. // when SceneLoader.debugLogging = true (default), or exception encountered.
  71967. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  71968. // and avoid problems with multiple concurrent .babylon loads.
  71969. var log = "importScene has failed JSON parse";
  71970. try {
  71971. var parsedData = JSON.parse(data);
  71972. log = "";
  71973. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  71974. var index;
  71975. var cache;
  71976. // Lights
  71977. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  71978. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  71979. var parsedLight = parsedData.lights[index];
  71980. var light = BABYLON.Light.Parse(parsedLight, scene);
  71981. if (light) {
  71982. container.lights.push(light);
  71983. log += (index === 0 ? "\n\tLights:" : "");
  71984. log += "\n\t\t" + light.toString(fullDetails);
  71985. }
  71986. }
  71987. }
  71988. // Animations
  71989. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  71990. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  71991. var parsedAnimation = parsedData.animations[index];
  71992. var animation = BABYLON.Animation.Parse(parsedAnimation);
  71993. scene.animations.push(animation);
  71994. container.animations.push(animation);
  71995. log += (index === 0 ? "\n\tAnimations:" : "");
  71996. log += "\n\t\t" + animation.toString(fullDetails);
  71997. }
  71998. }
  71999. // Materials
  72000. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  72001. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  72002. var parsedMaterial = parsedData.materials[index];
  72003. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  72004. container.materials.push(mat);
  72005. log += (index === 0 ? "\n\tMaterials:" : "");
  72006. log += "\n\t\t" + mat.toString(fullDetails);
  72007. }
  72008. }
  72009. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  72010. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  72011. var parsedMultiMaterial = parsedData.multiMaterials[index];
  72012. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  72013. container.multiMaterials.push(mmat);
  72014. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  72015. log += "\n\t\t" + mmat.toString(fullDetails);
  72016. }
  72017. }
  72018. // Morph targets
  72019. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  72020. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  72021. var managerData = _a[_i];
  72022. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  72023. }
  72024. }
  72025. // Skeletons
  72026. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  72027. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  72028. var parsedSkeleton = parsedData.skeletons[index];
  72029. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  72030. container.skeletons.push(skeleton);
  72031. log += (index === 0 ? "\n\tSkeletons:" : "");
  72032. log += "\n\t\t" + skeleton.toString(fullDetails);
  72033. }
  72034. }
  72035. // Geometries
  72036. var geometries = parsedData.geometries;
  72037. if (geometries !== undefined && geometries !== null) {
  72038. var addedGeometry = new Array();
  72039. // Boxes
  72040. var boxes = geometries.boxes;
  72041. if (boxes !== undefined && boxes !== null) {
  72042. for (index = 0, cache = boxes.length; index < cache; index++) {
  72043. var parsedBox = boxes[index];
  72044. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  72045. }
  72046. }
  72047. // Spheres
  72048. var spheres = geometries.spheres;
  72049. if (spheres !== undefined && spheres !== null) {
  72050. for (index = 0, cache = spheres.length; index < cache; index++) {
  72051. var parsedSphere = spheres[index];
  72052. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  72053. }
  72054. }
  72055. // Cylinders
  72056. var cylinders = geometries.cylinders;
  72057. if (cylinders !== undefined && cylinders !== null) {
  72058. for (index = 0, cache = cylinders.length; index < cache; index++) {
  72059. var parsedCylinder = cylinders[index];
  72060. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  72061. }
  72062. }
  72063. // Toruses
  72064. var toruses = geometries.toruses;
  72065. if (toruses !== undefined && toruses !== null) {
  72066. for (index = 0, cache = toruses.length; index < cache; index++) {
  72067. var parsedTorus = toruses[index];
  72068. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  72069. }
  72070. }
  72071. // Grounds
  72072. var grounds = geometries.grounds;
  72073. if (grounds !== undefined && grounds !== null) {
  72074. for (index = 0, cache = grounds.length; index < cache; index++) {
  72075. var parsedGround = grounds[index];
  72076. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  72077. }
  72078. }
  72079. // Planes
  72080. var planes = geometries.planes;
  72081. if (planes !== undefined && planes !== null) {
  72082. for (index = 0, cache = planes.length; index < cache; index++) {
  72083. var parsedPlane = planes[index];
  72084. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  72085. }
  72086. }
  72087. // TorusKnots
  72088. var torusKnots = geometries.torusKnots;
  72089. if (torusKnots !== undefined && torusKnots !== null) {
  72090. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  72091. var parsedTorusKnot = torusKnots[index];
  72092. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  72093. }
  72094. }
  72095. // VertexData
  72096. var vertexData = geometries.vertexData;
  72097. if (vertexData !== undefined && vertexData !== null) {
  72098. for (index = 0, cache = vertexData.length; index < cache; index++) {
  72099. var parsedVertexData = vertexData[index];
  72100. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  72101. }
  72102. }
  72103. addedGeometry.forEach(function (g) {
  72104. if (g) {
  72105. container.geometries.push(g);
  72106. }
  72107. });
  72108. }
  72109. // Transform nodes
  72110. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  72111. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  72112. var parsedTransformNode = parsedData.transformNodes[index];
  72113. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  72114. container.transformNodes.push(node);
  72115. }
  72116. }
  72117. // Meshes
  72118. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  72119. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  72120. var parsedMesh = parsedData.meshes[index];
  72121. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  72122. container.meshes.push(mesh);
  72123. log += (index === 0 ? "\n\tMeshes:" : "");
  72124. log += "\n\t\t" + mesh.toString(fullDetails);
  72125. }
  72126. }
  72127. // Cameras
  72128. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  72129. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  72130. var parsedCamera = parsedData.cameras[index];
  72131. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  72132. container.cameras.push(camera);
  72133. log += (index === 0 ? "\n\tCameras:" : "");
  72134. log += "\n\t\t" + camera.toString(fullDetails);
  72135. }
  72136. }
  72137. // Browsing all the graph to connect the dots
  72138. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  72139. var camera = scene.cameras[index];
  72140. if (camera._waitingParentId) {
  72141. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  72142. camera._waitingParentId = null;
  72143. }
  72144. }
  72145. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  72146. var light_1 = scene.lights[index];
  72147. if (light_1 && light_1._waitingParentId) {
  72148. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  72149. light_1._waitingParentId = null;
  72150. }
  72151. }
  72152. // Sounds
  72153. // TODO: add sound
  72154. var loadedSounds = [];
  72155. var loadedSound;
  72156. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  72157. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  72158. var parsedSound = parsedData.sounds[index];
  72159. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  72160. if (!parsedSound.url)
  72161. parsedSound.url = parsedSound.name;
  72162. if (!loadedSounds[parsedSound.url]) {
  72163. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  72164. loadedSounds[parsedSound.url] = loadedSound;
  72165. container.sounds.push(loadedSound);
  72166. }
  72167. else {
  72168. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  72169. }
  72170. }
  72171. else {
  72172. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  72173. }
  72174. }
  72175. }
  72176. loadedSounds = [];
  72177. // Connect parents & children and parse actions
  72178. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  72179. var transformNode = scene.transformNodes[index];
  72180. if (transformNode._waitingParentId) {
  72181. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  72182. transformNode._waitingParentId = null;
  72183. }
  72184. }
  72185. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  72186. var mesh = scene.meshes[index];
  72187. if (mesh._waitingParentId) {
  72188. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  72189. mesh._waitingParentId = null;
  72190. }
  72191. if (mesh._waitingActions) {
  72192. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  72193. mesh._waitingActions = null;
  72194. }
  72195. }
  72196. // freeze world matrix application
  72197. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  72198. var currentMesh = scene.meshes[index];
  72199. if (currentMesh._waitingFreezeWorldMatrix) {
  72200. currentMesh.freezeWorldMatrix();
  72201. currentMesh._waitingFreezeWorldMatrix = null;
  72202. }
  72203. else {
  72204. currentMesh.computeWorldMatrix(true);
  72205. }
  72206. }
  72207. // Lights exclusions / inclusions
  72208. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  72209. var light_2 = scene.lights[index];
  72210. // Excluded check
  72211. if (light_2._excludedMeshesIds.length > 0) {
  72212. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  72213. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  72214. if (excludedMesh) {
  72215. light_2.excludedMeshes.push(excludedMesh);
  72216. }
  72217. }
  72218. light_2._excludedMeshesIds = [];
  72219. }
  72220. // Included check
  72221. if (light_2._includedOnlyMeshesIds.length > 0) {
  72222. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  72223. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  72224. if (includedOnlyMesh) {
  72225. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  72226. }
  72227. }
  72228. light_2._includedOnlyMeshesIds = [];
  72229. }
  72230. }
  72231. BABYLON.AbstractScene.Parse(parsedData, scene, container, rootUrl);
  72232. // Actions (scene)
  72233. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  72234. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  72235. }
  72236. if (!addToScene) {
  72237. container.removeAllFromScene();
  72238. }
  72239. }
  72240. catch (err) {
  72241. var msg = logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + log;
  72242. if (onError) {
  72243. onError(msg, err);
  72244. }
  72245. else {
  72246. BABYLON.Tools.Log(msg);
  72247. throw err;
  72248. }
  72249. }
  72250. finally {
  72251. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  72252. BABYLON.Tools.Log(logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  72253. }
  72254. }
  72255. return container;
  72256. };
  72257. BABYLON.SceneLoader.RegisterPlugin({
  72258. name: "babylon.js",
  72259. extensions: ".babylon",
  72260. canDirectLoad: function (data) {
  72261. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  72262. return true;
  72263. }
  72264. return false;
  72265. },
  72266. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  72267. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  72268. // when SceneLoader.debugLogging = true (default), or exception encountered.
  72269. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  72270. // and avoid problems with multiple concurrent .babylon loads.
  72271. var log = "importMesh has failed JSON parse";
  72272. try {
  72273. var parsedData = JSON.parse(data);
  72274. log = "";
  72275. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  72276. if (!meshesNames) {
  72277. meshesNames = null;
  72278. }
  72279. else if (!Array.isArray(meshesNames)) {
  72280. meshesNames = [meshesNames];
  72281. }
  72282. var hierarchyIds = new Array();
  72283. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  72284. var loadedSkeletonsIds = [];
  72285. var loadedMaterialsIds = [];
  72286. var index;
  72287. var cache;
  72288. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  72289. var parsedMesh = parsedData.meshes[index];
  72290. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  72291. if (meshesNames !== null) {
  72292. // Remove found mesh name from list.
  72293. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  72294. }
  72295. //Geometry?
  72296. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  72297. //does the file contain geometries?
  72298. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  72299. //find the correct geometry and add it to the scene
  72300. var found = false;
  72301. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  72302. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  72303. return;
  72304. }
  72305. else {
  72306. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  72307. if (parsedGeometryData.id === parsedMesh.geometryId) {
  72308. switch (geometryType) {
  72309. case "boxes":
  72310. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  72311. break;
  72312. case "spheres":
  72313. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  72314. break;
  72315. case "cylinders":
  72316. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  72317. break;
  72318. case "toruses":
  72319. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  72320. break;
  72321. case "grounds":
  72322. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  72323. break;
  72324. case "planes":
  72325. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  72326. break;
  72327. case "torusKnots":
  72328. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  72329. break;
  72330. case "vertexData":
  72331. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  72332. break;
  72333. }
  72334. found = true;
  72335. }
  72336. });
  72337. }
  72338. });
  72339. if (found === false) {
  72340. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  72341. }
  72342. }
  72343. }
  72344. // Material ?
  72345. if (parsedMesh.materialId) {
  72346. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  72347. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  72348. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  72349. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  72350. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  72351. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  72352. var subMatId = parsedMultiMaterial.materials[matIndex];
  72353. loadedMaterialsIds.push(subMatId);
  72354. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  72355. if (mat) {
  72356. log += "\n\tMaterial " + mat.toString(fullDetails);
  72357. }
  72358. }
  72359. loadedMaterialsIds.push(parsedMultiMaterial.id);
  72360. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  72361. if (mmat) {
  72362. materialFound = true;
  72363. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  72364. }
  72365. break;
  72366. }
  72367. }
  72368. }
  72369. if (materialFound === false) {
  72370. loadedMaterialsIds.push(parsedMesh.materialId);
  72371. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  72372. if (!mat) {
  72373. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  72374. }
  72375. else {
  72376. log += "\n\tMaterial " + mat.toString(fullDetails);
  72377. }
  72378. }
  72379. }
  72380. // Skeleton ?
  72381. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  72382. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  72383. if (skeletonAlreadyLoaded === false) {
  72384. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  72385. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  72386. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  72387. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  72388. skeletons.push(skeleton);
  72389. loadedSkeletonsIds.push(parsedSkeleton.id);
  72390. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  72391. }
  72392. }
  72393. }
  72394. }
  72395. // Morph targets ?
  72396. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  72397. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  72398. var managerData = _a[_i];
  72399. BABYLON.MorphTargetManager.Parse(managerData, scene);
  72400. }
  72401. }
  72402. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  72403. meshes.push(mesh);
  72404. log += "\n\tMesh " + mesh.toString(fullDetails);
  72405. }
  72406. }
  72407. // Connecting parents
  72408. var currentMesh;
  72409. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  72410. currentMesh = scene.meshes[index];
  72411. if (currentMesh._waitingParentId) {
  72412. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  72413. currentMesh._waitingParentId = null;
  72414. }
  72415. }
  72416. // freeze and compute world matrix application
  72417. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  72418. currentMesh = scene.meshes[index];
  72419. if (currentMesh._waitingFreezeWorldMatrix) {
  72420. currentMesh.freezeWorldMatrix();
  72421. currentMesh._waitingFreezeWorldMatrix = null;
  72422. }
  72423. else {
  72424. currentMesh.computeWorldMatrix(true);
  72425. }
  72426. }
  72427. }
  72428. // Particles
  72429. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  72430. var parser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  72431. if (parser) {
  72432. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  72433. var parsedParticleSystem = parsedData.particleSystems[index];
  72434. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  72435. particleSystems.push(parser(parsedParticleSystem, scene, rootUrl));
  72436. }
  72437. }
  72438. }
  72439. }
  72440. return true;
  72441. }
  72442. catch (err) {
  72443. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  72444. if (onError) {
  72445. onError(msg, err);
  72446. }
  72447. else {
  72448. BABYLON.Tools.Log(msg);
  72449. throw err;
  72450. }
  72451. }
  72452. finally {
  72453. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  72454. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  72455. }
  72456. }
  72457. return false;
  72458. },
  72459. load: function (scene, data, rootUrl, onError) {
  72460. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  72461. // when SceneLoader.debugLogging = true (default), or exception encountered.
  72462. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  72463. // and avoid problems with multiple concurrent .babylon loads.
  72464. var log = "importScene has failed JSON parse";
  72465. try {
  72466. var parsedData = JSON.parse(data);
  72467. log = "";
  72468. // Scene
  72469. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  72470. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  72471. }
  72472. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  72473. scene.autoClear = parsedData.autoClear;
  72474. }
  72475. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  72476. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  72477. }
  72478. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  72479. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  72480. }
  72481. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  72482. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  72483. }
  72484. // Fog
  72485. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  72486. scene.fogMode = parsedData.fogMode;
  72487. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  72488. scene.fogStart = parsedData.fogStart;
  72489. scene.fogEnd = parsedData.fogEnd;
  72490. scene.fogDensity = parsedData.fogDensity;
  72491. log += "\tFog mode for scene: ";
  72492. switch (scene.fogMode) {
  72493. // getters not compiling, so using hardcoded
  72494. case 1:
  72495. log += "exp\n";
  72496. break;
  72497. case 2:
  72498. log += "exp2\n";
  72499. break;
  72500. case 3:
  72501. log += "linear\n";
  72502. break;
  72503. }
  72504. }
  72505. //Physics
  72506. if (parsedData.physicsEnabled) {
  72507. var physicsPlugin;
  72508. if (parsedData.physicsEngine === "cannon") {
  72509. physicsPlugin = new BABYLON.CannonJSPlugin();
  72510. }
  72511. else if (parsedData.physicsEngine === "oimo") {
  72512. physicsPlugin = new BABYLON.OimoJSPlugin();
  72513. }
  72514. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  72515. //else - default engine, which is currently oimo
  72516. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  72517. scene.enablePhysics(physicsGravity, physicsPlugin);
  72518. }
  72519. // Metadata
  72520. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  72521. scene.metadata = parsedData.metadata;
  72522. }
  72523. //collisions, if defined. otherwise, default is true
  72524. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  72525. scene.collisionsEnabled = parsedData.collisionsEnabled;
  72526. }
  72527. scene.workerCollisions = !!parsedData.workerCollisions;
  72528. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  72529. if (!container) {
  72530. return false;
  72531. }
  72532. if (parsedData.autoAnimate) {
  72533. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  72534. }
  72535. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  72536. scene.setActiveCameraByID(parsedData.activeCameraID);
  72537. }
  72538. // Environment texture
  72539. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  72540. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  72541. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  72542. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  72543. if (parsedData.environmentTextureRotationY) {
  72544. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  72545. }
  72546. scene.environmentTexture = hdrTexture;
  72547. }
  72548. else {
  72549. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  72550. if (parsedData.environmentTextureRotationY) {
  72551. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  72552. }
  72553. scene.environmentTexture = cubeTexture;
  72554. }
  72555. if (parsedData.createDefaultSkybox === true) {
  72556. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  72557. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  72558. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  72559. }
  72560. }
  72561. // Finish
  72562. return true;
  72563. }
  72564. catch (err) {
  72565. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  72566. if (onError) {
  72567. onError(msg, err);
  72568. }
  72569. else {
  72570. BABYLON.Tools.Log(msg);
  72571. throw err;
  72572. }
  72573. }
  72574. finally {
  72575. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  72576. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  72577. }
  72578. }
  72579. return false;
  72580. },
  72581. loadAssetContainer: function (scene, data, rootUrl, onError) {
  72582. var container = loadAssetContainer(scene, data, rootUrl, onError);
  72583. return container;
  72584. }
  72585. });
  72586. })(BABYLON || (BABYLON = {}));
  72587. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  72588. var BABYLON;
  72589. (function (BABYLON) {
  72590. var FilesInput = /** @class */ (function () {
  72591. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  72592. this.onProcessFileCallback = function () { return true; };
  72593. this._engine = engine;
  72594. this._currentScene = scene;
  72595. this._sceneLoadedCallback = sceneLoadedCallback;
  72596. this._progressCallback = progressCallback;
  72597. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  72598. this._textureLoadingCallback = textureLoadingCallback;
  72599. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  72600. this._onReloadCallback = onReloadCallback;
  72601. this._errorCallback = errorCallback;
  72602. }
  72603. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  72604. var _this = this;
  72605. if (elementToMonitor) {
  72606. this._elementToMonitor = elementToMonitor;
  72607. this._dragEnterHandler = function (e) { _this.drag(e); };
  72608. this._dragOverHandler = function (e) { _this.drag(e); };
  72609. this._dropHandler = function (e) { _this.drop(e); };
  72610. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  72611. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  72612. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  72613. }
  72614. };
  72615. FilesInput.prototype.dispose = function () {
  72616. if (!this._elementToMonitor) {
  72617. return;
  72618. }
  72619. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  72620. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  72621. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  72622. };
  72623. FilesInput.prototype.renderFunction = function () {
  72624. if (this._additionalRenderLoopLogicCallback) {
  72625. this._additionalRenderLoopLogicCallback();
  72626. }
  72627. if (this._currentScene) {
  72628. if (this._textureLoadingCallback) {
  72629. var remaining = this._currentScene.getWaitingItemsCount();
  72630. if (remaining > 0) {
  72631. this._textureLoadingCallback(remaining);
  72632. }
  72633. }
  72634. this._currentScene.render();
  72635. }
  72636. };
  72637. FilesInput.prototype.drag = function (e) {
  72638. e.stopPropagation();
  72639. e.preventDefault();
  72640. };
  72641. FilesInput.prototype.drop = function (eventDrop) {
  72642. eventDrop.stopPropagation();
  72643. eventDrop.preventDefault();
  72644. this.loadFiles(eventDrop);
  72645. };
  72646. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  72647. var _this = this;
  72648. var reader = folder.createReader();
  72649. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  72650. reader.readEntries(function (entries) {
  72651. remaining.count += entries.length;
  72652. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  72653. var entry = entries_1[_i];
  72654. if (entry.isFile) {
  72655. entry.file(function (file) {
  72656. file.correctName = relativePath + file.name;
  72657. files.push(file);
  72658. if (--remaining.count === 0) {
  72659. callback();
  72660. }
  72661. });
  72662. }
  72663. else if (entry.isDirectory) {
  72664. _this._traverseFolder(entry, files, remaining, callback);
  72665. }
  72666. }
  72667. if (--remaining.count) {
  72668. callback();
  72669. }
  72670. });
  72671. };
  72672. FilesInput.prototype._processFiles = function (files) {
  72673. for (var i = 0; i < files.length; i++) {
  72674. var name = files[i].correctName.toLowerCase();
  72675. var extension = name.split('.').pop();
  72676. if (!this.onProcessFileCallback(files[i], name, extension)) {
  72677. continue;
  72678. }
  72679. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  72680. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  72681. this._sceneFileToLoad = files[i];
  72682. }
  72683. else {
  72684. FilesInput.FilesToLoad[name] = files[i];
  72685. }
  72686. }
  72687. };
  72688. FilesInput.prototype.loadFiles = function (event) {
  72689. var _this = this;
  72690. // Handling data transfer via drag'n'drop
  72691. if (event && event.dataTransfer && event.dataTransfer.files) {
  72692. this._filesToLoad = event.dataTransfer.files;
  72693. }
  72694. // Handling files from input files
  72695. if (event && event.target && event.target.files) {
  72696. this._filesToLoad = event.target.files;
  72697. }
  72698. if (!this._filesToLoad || this._filesToLoad.length === 0) {
  72699. return;
  72700. }
  72701. if (this._startingProcessingFilesCallback) {
  72702. this._startingProcessingFilesCallback(this._filesToLoad);
  72703. }
  72704. if (this._filesToLoad && this._filesToLoad.length > 0) {
  72705. var files_1 = new Array();
  72706. var folders = [];
  72707. var items = event.dataTransfer ? event.dataTransfer.items : null;
  72708. for (var i = 0; i < this._filesToLoad.length; i++) {
  72709. var fileToLoad = this._filesToLoad[i];
  72710. var name_1 = fileToLoad.name.toLowerCase();
  72711. var entry = void 0;
  72712. fileToLoad.correctName = name_1;
  72713. if (items) {
  72714. var item = items[i];
  72715. if (item.getAsEntry) {
  72716. entry = item.getAsEntry();
  72717. }
  72718. else if (item.webkitGetAsEntry) {
  72719. entry = item.webkitGetAsEntry();
  72720. }
  72721. }
  72722. if (!entry) {
  72723. files_1.push(fileToLoad);
  72724. }
  72725. else {
  72726. if (entry.isDirectory) {
  72727. folders.push(entry);
  72728. }
  72729. else {
  72730. files_1.push(fileToLoad);
  72731. }
  72732. }
  72733. }
  72734. if (folders.length === 0) {
  72735. this._processFiles(files_1);
  72736. this._processReload();
  72737. }
  72738. else {
  72739. var remaining = { count: folders.length };
  72740. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  72741. var folder = folders_1[_i];
  72742. this._traverseFolder(folder, files_1, remaining, function () {
  72743. _this._processFiles(files_1);
  72744. if (remaining.count === 0) {
  72745. _this._processReload();
  72746. }
  72747. });
  72748. }
  72749. }
  72750. }
  72751. };
  72752. FilesInput.prototype._processReload = function () {
  72753. if (this._onReloadCallback) {
  72754. this._onReloadCallback(this._sceneFileToLoad);
  72755. }
  72756. else {
  72757. this.reload();
  72758. }
  72759. };
  72760. FilesInput.prototype.reload = function () {
  72761. var _this = this;
  72762. // If a scene file has been provided
  72763. if (this._sceneFileToLoad) {
  72764. if (this._currentScene) {
  72765. if (BABYLON.Tools.errorsCount > 0) {
  72766. BABYLON.Tools.ClearLogCache();
  72767. }
  72768. this._engine.stopRenderLoop();
  72769. }
  72770. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  72771. if (_this._progressCallback) {
  72772. _this._progressCallback(progress);
  72773. }
  72774. }).then(function (scene) {
  72775. if (_this._currentScene) {
  72776. _this._currentScene.dispose();
  72777. }
  72778. _this._currentScene = scene;
  72779. if (_this._sceneLoadedCallback) {
  72780. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  72781. }
  72782. // Wait for textures and shaders to be ready
  72783. _this._currentScene.executeWhenReady(function () {
  72784. _this._engine.runRenderLoop(function () {
  72785. _this.renderFunction();
  72786. });
  72787. });
  72788. }).catch(function (error) {
  72789. if (_this._errorCallback) {
  72790. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  72791. }
  72792. });
  72793. }
  72794. else {
  72795. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  72796. }
  72797. };
  72798. FilesInput.FilesToLoad = {};
  72799. return FilesInput;
  72800. }());
  72801. BABYLON.FilesInput = FilesInput;
  72802. })(BABYLON || (BABYLON = {}));
  72803. //# sourceMappingURL=babylon.filesInput.js.map
  72804. var BABYLON;
  72805. (function (BABYLON) {
  72806. var Tags = /** @class */ (function () {
  72807. function Tags() {
  72808. }
  72809. Tags.EnableFor = function (obj) {
  72810. obj._tags = obj._tags || {};
  72811. obj.hasTags = function () {
  72812. return Tags.HasTags(obj);
  72813. };
  72814. obj.addTags = function (tagsString) {
  72815. return Tags.AddTagsTo(obj, tagsString);
  72816. };
  72817. obj.removeTags = function (tagsString) {
  72818. return Tags.RemoveTagsFrom(obj, tagsString);
  72819. };
  72820. obj.matchesTagsQuery = function (tagsQuery) {
  72821. return Tags.MatchesQuery(obj, tagsQuery);
  72822. };
  72823. };
  72824. Tags.DisableFor = function (obj) {
  72825. delete obj._tags;
  72826. delete obj.hasTags;
  72827. delete obj.addTags;
  72828. delete obj.removeTags;
  72829. delete obj.matchesTagsQuery;
  72830. };
  72831. Tags.HasTags = function (obj) {
  72832. if (!obj._tags) {
  72833. return false;
  72834. }
  72835. return !BABYLON.Tools.IsEmpty(obj._tags);
  72836. };
  72837. Tags.GetTags = function (obj, asString) {
  72838. if (asString === void 0) { asString = true; }
  72839. if (!obj._tags) {
  72840. return null;
  72841. }
  72842. if (asString) {
  72843. var tagsArray = [];
  72844. for (var tag in obj._tags) {
  72845. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  72846. tagsArray.push(tag);
  72847. }
  72848. }
  72849. return tagsArray.join(" ");
  72850. }
  72851. else {
  72852. return obj._tags;
  72853. }
  72854. };
  72855. // the tags 'true' and 'false' are reserved and cannot be used as tags
  72856. // a tag cannot start with '||', '&&', and '!'
  72857. // it cannot contain whitespaces
  72858. Tags.AddTagsTo = function (obj, tagsString) {
  72859. if (!tagsString) {
  72860. return;
  72861. }
  72862. if (typeof tagsString !== "string") {
  72863. return;
  72864. }
  72865. var tags = tagsString.split(" ");
  72866. tags.forEach(function (tag, index, array) {
  72867. Tags._AddTagTo(obj, tag);
  72868. });
  72869. };
  72870. Tags._AddTagTo = function (obj, tag) {
  72871. tag = tag.trim();
  72872. if (tag === "" || tag === "true" || tag === "false") {
  72873. return;
  72874. }
  72875. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  72876. return;
  72877. }
  72878. Tags.EnableFor(obj);
  72879. obj._tags[tag] = true;
  72880. };
  72881. Tags.RemoveTagsFrom = function (obj, tagsString) {
  72882. if (!Tags.HasTags(obj)) {
  72883. return;
  72884. }
  72885. var tags = tagsString.split(" ");
  72886. for (var t in tags) {
  72887. Tags._RemoveTagFrom(obj, tags[t]);
  72888. }
  72889. };
  72890. Tags._RemoveTagFrom = function (obj, tag) {
  72891. delete obj._tags[tag];
  72892. };
  72893. Tags.MatchesQuery = function (obj, tagsQuery) {
  72894. if (tagsQuery === undefined) {
  72895. return true;
  72896. }
  72897. if (tagsQuery === "") {
  72898. return Tags.HasTags(obj);
  72899. }
  72900. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  72901. };
  72902. return Tags;
  72903. }());
  72904. BABYLON.Tags = Tags;
  72905. })(BABYLON || (BABYLON = {}));
  72906. //# sourceMappingURL=babylon.tags.js.map
  72907. var BABYLON;
  72908. (function (BABYLON) {
  72909. /**
  72910. * Class used to evalaute queries containing `and` and `or` operators
  72911. */
  72912. var AndOrNotEvaluator = /** @class */ (function () {
  72913. function AndOrNotEvaluator() {
  72914. }
  72915. /**
  72916. * Evaluate a query
  72917. * @param query defines the query to evaluate
  72918. * @param evaluateCallback defines the callback used to filter result
  72919. * @returns true if the query matches
  72920. */
  72921. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  72922. if (!query.match(/\([^\(\)]*\)/g)) {
  72923. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  72924. }
  72925. else {
  72926. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  72927. // remove parenthesis
  72928. r = r.slice(1, r.length - 1);
  72929. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  72930. });
  72931. }
  72932. if (query === "true") {
  72933. return true;
  72934. }
  72935. if (query === "false") {
  72936. return false;
  72937. }
  72938. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  72939. };
  72940. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  72941. evaluateCallback = evaluateCallback || (function (r) {
  72942. return r === "true" ? true : false;
  72943. });
  72944. var result;
  72945. var or = parenthesisContent.split("||");
  72946. for (var i in or) {
  72947. if (or.hasOwnProperty(i)) {
  72948. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  72949. var and = ori.split("&&");
  72950. if (and.length > 1) {
  72951. for (var j = 0; j < and.length; ++j) {
  72952. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  72953. if (andj !== "true" && andj !== "false") {
  72954. if (andj[0] === "!") {
  72955. result = !evaluateCallback(andj.substring(1));
  72956. }
  72957. else {
  72958. result = evaluateCallback(andj);
  72959. }
  72960. }
  72961. else {
  72962. result = andj === "true" ? true : false;
  72963. }
  72964. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  72965. ori = "false";
  72966. break;
  72967. }
  72968. }
  72969. }
  72970. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  72971. result = true;
  72972. break;
  72973. }
  72974. // result equals false (or undefined)
  72975. if (ori !== "true" && ori !== "false") {
  72976. if (ori[0] === "!") {
  72977. result = !evaluateCallback(ori.substring(1));
  72978. }
  72979. else {
  72980. result = evaluateCallback(ori);
  72981. }
  72982. }
  72983. else {
  72984. result = ori === "true" ? true : false;
  72985. }
  72986. }
  72987. }
  72988. // the whole parenthesis scope is replaced by 'true' or 'false'
  72989. return result ? "true" : "false";
  72990. };
  72991. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  72992. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  72993. // remove whitespaces
  72994. r = r.replace(/[\s]/g, function () { return ""; });
  72995. return r.length % 2 ? "!" : "";
  72996. });
  72997. booleanString = booleanString.trim();
  72998. if (booleanString === "!true") {
  72999. booleanString = "false";
  73000. }
  73001. else if (booleanString === "!false") {
  73002. booleanString = "true";
  73003. }
  73004. return booleanString;
  73005. };
  73006. return AndOrNotEvaluator;
  73007. }());
  73008. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  73009. })(BABYLON || (BABYLON = {}));
  73010. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  73011. var BABYLON;
  73012. (function (BABYLON) {
  73013. /**
  73014. * Class used to enable access to IndexedDB
  73015. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  73016. */
  73017. var Database = /** @class */ (function () {
  73018. /**
  73019. * Creates a new Database
  73020. * @param urlToScene defines the url to load the scene
  73021. * @param callbackManifestChecked defines the callback to use when manifest is checked
  73022. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  73023. */
  73024. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  73025. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  73026. var _this = this;
  73027. // Handling various flavors of prefixed version of IndexedDB
  73028. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  73029. this.callbackManifestChecked = callbackManifestChecked;
  73030. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  73031. this.db = null;
  73032. this._enableSceneOffline = false;
  73033. this._enableTexturesOffline = false;
  73034. this.manifestVersionFound = 0;
  73035. this.mustUpdateRessources = false;
  73036. this.hasReachedQuota = false;
  73037. if (!Database.IDBStorageEnabled) {
  73038. this.callbackManifestChecked(true);
  73039. }
  73040. else {
  73041. if (disableManifestCheck) {
  73042. this._enableSceneOffline = true;
  73043. this._enableTexturesOffline = true;
  73044. this.manifestVersionFound = 1;
  73045. BABYLON.Tools.SetImmediate(function () {
  73046. _this.callbackManifestChecked(true);
  73047. });
  73048. }
  73049. else {
  73050. this._checkManifestFile();
  73051. }
  73052. }
  73053. }
  73054. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  73055. /**
  73056. * Gets a boolean indicating if scene must be saved in the database
  73057. */
  73058. get: function () {
  73059. return this._enableSceneOffline;
  73060. },
  73061. enumerable: true,
  73062. configurable: true
  73063. });
  73064. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  73065. /**
  73066. * Gets a boolean indicating if textures must be saved in the database
  73067. */
  73068. get: function () {
  73069. return this._enableTexturesOffline;
  73070. },
  73071. enumerable: true,
  73072. configurable: true
  73073. });
  73074. Database.prototype._checkManifestFile = function () {
  73075. var _this = this;
  73076. var noManifestFile = function () {
  73077. _this._enableSceneOffline = false;
  73078. _this._enableTexturesOffline = false;
  73079. _this.callbackManifestChecked(false);
  73080. };
  73081. var timeStampUsed = false;
  73082. var manifestURL = this.currentSceneUrl + ".manifest";
  73083. var xhr = new XMLHttpRequest();
  73084. if (navigator.onLine) {
  73085. // Adding a timestamp to by-pass browsers' cache
  73086. timeStampUsed = true;
  73087. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  73088. }
  73089. xhr.open("GET", manifestURL, true);
  73090. xhr.addEventListener("load", function () {
  73091. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  73092. try {
  73093. var manifestFile = JSON.parse(xhr.response);
  73094. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  73095. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  73096. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  73097. _this.manifestVersionFound = manifestFile.version;
  73098. }
  73099. if (_this.callbackManifestChecked) {
  73100. _this.callbackManifestChecked(true);
  73101. }
  73102. }
  73103. catch (ex) {
  73104. noManifestFile();
  73105. }
  73106. }
  73107. else {
  73108. noManifestFile();
  73109. }
  73110. }, false);
  73111. xhr.addEventListener("error", function (event) {
  73112. if (timeStampUsed) {
  73113. timeStampUsed = false;
  73114. // Let's retry without the timeStamp
  73115. // It could fail when coupled with HTML5 Offline API
  73116. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  73117. xhr.open("GET", retryManifestURL, true);
  73118. xhr.send();
  73119. }
  73120. else {
  73121. noManifestFile();
  73122. }
  73123. }, false);
  73124. try {
  73125. xhr.send();
  73126. }
  73127. catch (ex) {
  73128. BABYLON.Tools.Error("Error on XHR send request.");
  73129. this.callbackManifestChecked(false);
  73130. }
  73131. };
  73132. /**
  73133. * Open the database and make it available
  73134. * @param successCallback defines the callback to call on success
  73135. * @param errorCallback defines the callback to call on error
  73136. */
  73137. Database.prototype.openAsync = function (successCallback, errorCallback) {
  73138. var _this = this;
  73139. var handleError = function () {
  73140. _this.isSupported = false;
  73141. if (errorCallback)
  73142. errorCallback();
  73143. };
  73144. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  73145. // Your browser doesn't support IndexedDB
  73146. this.isSupported = false;
  73147. if (errorCallback)
  73148. errorCallback();
  73149. }
  73150. else {
  73151. // If the DB hasn't been opened or created yet
  73152. if (!this.db) {
  73153. this.hasReachedQuota = false;
  73154. this.isSupported = true;
  73155. var request = this.idbFactory.open("babylonjs", 1);
  73156. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  73157. request.onerror = function (event) {
  73158. handleError();
  73159. };
  73160. // executes when a version change transaction cannot complete due to other active transactions
  73161. request.onblocked = function (event) {
  73162. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  73163. handleError();
  73164. };
  73165. // DB has been opened successfully
  73166. request.onsuccess = function (event) {
  73167. _this.db = request.result;
  73168. successCallback();
  73169. };
  73170. // Initialization of the DB. Creating Scenes & Textures stores
  73171. request.onupgradeneeded = function (event) {
  73172. _this.db = (event.target).result;
  73173. if (_this.db) {
  73174. try {
  73175. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  73176. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  73177. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  73178. }
  73179. catch (ex) {
  73180. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  73181. handleError();
  73182. }
  73183. }
  73184. };
  73185. }
  73186. // DB has already been created and opened
  73187. else {
  73188. if (successCallback)
  73189. successCallback();
  73190. }
  73191. }
  73192. };
  73193. /**
  73194. * Loads an image from the database
  73195. * @param url defines the url to load from
  73196. * @param image defines the target DOM image
  73197. */
  73198. Database.prototype.loadImageFromDB = function (url, image) {
  73199. var _this = this;
  73200. var completeURL = Database._ReturnFullUrlLocation(url);
  73201. var saveAndLoadImage = function () {
  73202. if (!_this.hasReachedQuota && _this.db !== null) {
  73203. // the texture is not yet in the DB, let's try to save it
  73204. _this._saveImageIntoDBAsync(completeURL, image);
  73205. }
  73206. // If the texture is not in the DB and we've reached the DB quota limit
  73207. // let's load it directly from the web
  73208. else {
  73209. image.src = url;
  73210. }
  73211. };
  73212. if (!this.mustUpdateRessources) {
  73213. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  73214. }
  73215. // First time we're download the images or update requested in the manifest file by a version change
  73216. else {
  73217. saveAndLoadImage();
  73218. }
  73219. };
  73220. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  73221. if (this.isSupported && this.db !== null) {
  73222. var texture;
  73223. var transaction = this.db.transaction(["textures"]);
  73224. transaction.onabort = function (event) {
  73225. image.src = url;
  73226. };
  73227. transaction.oncomplete = function (event) {
  73228. var blobTextureURL;
  73229. if (texture) {
  73230. var URL = window.URL || window.webkitURL;
  73231. blobTextureURL = URL.createObjectURL(texture.data);
  73232. image.onerror = function () {
  73233. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  73234. image.src = url;
  73235. };
  73236. image.src = blobTextureURL;
  73237. }
  73238. else {
  73239. notInDBCallback();
  73240. }
  73241. };
  73242. var getRequest = transaction.objectStore("textures").get(url);
  73243. getRequest.onsuccess = function (event) {
  73244. texture = (event.target).result;
  73245. };
  73246. getRequest.onerror = function (event) {
  73247. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  73248. image.src = url;
  73249. };
  73250. }
  73251. else {
  73252. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  73253. image.src = url;
  73254. }
  73255. };
  73256. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  73257. var _this = this;
  73258. if (this.isSupported) {
  73259. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  73260. var generateBlobUrl = function () {
  73261. var blobTextureURL;
  73262. if (blob) {
  73263. var URL = window.URL || window.webkitURL;
  73264. try {
  73265. blobTextureURL = URL.createObjectURL(blob);
  73266. }
  73267. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  73268. catch (ex) {
  73269. blobTextureURL = URL.createObjectURL(blob);
  73270. }
  73271. }
  73272. if (blobTextureURL) {
  73273. image.src = blobTextureURL;
  73274. }
  73275. };
  73276. if (Database.IsUASupportingBlobStorage) { // Create XHR
  73277. var xhr = new XMLHttpRequest(), blob;
  73278. xhr.open("GET", url, true);
  73279. xhr.responseType = "blob";
  73280. xhr.addEventListener("load", function () {
  73281. if (xhr.status === 200 && _this.db) {
  73282. // Blob as response (XHR2)
  73283. blob = xhr.response;
  73284. var transaction = _this.db.transaction(["textures"], "readwrite");
  73285. // the transaction could abort because of a QuotaExceededError error
  73286. transaction.onabort = function (event) {
  73287. try {
  73288. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  73289. var srcElement = (event.srcElement || event.target);
  73290. var error = srcElement.error;
  73291. if (error && error.name === "QuotaExceededError") {
  73292. _this.hasReachedQuota = true;
  73293. }
  73294. }
  73295. catch (ex) { }
  73296. generateBlobUrl();
  73297. };
  73298. transaction.oncomplete = function (event) {
  73299. generateBlobUrl();
  73300. };
  73301. var newTexture = { textureUrl: url, data: blob };
  73302. try {
  73303. // Put the blob into the dabase
  73304. var addRequest = transaction.objectStore("textures").put(newTexture);
  73305. addRequest.onsuccess = function (event) {
  73306. };
  73307. addRequest.onerror = function (event) {
  73308. generateBlobUrl();
  73309. };
  73310. }
  73311. catch (ex) {
  73312. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  73313. if (ex.code === 25) {
  73314. Database.IsUASupportingBlobStorage = false;
  73315. }
  73316. image.src = url;
  73317. }
  73318. }
  73319. else {
  73320. image.src = url;
  73321. }
  73322. }, false);
  73323. xhr.addEventListener("error", function (event) {
  73324. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  73325. image.src = url;
  73326. }, false);
  73327. xhr.send();
  73328. }
  73329. else {
  73330. image.src = url;
  73331. }
  73332. }
  73333. else {
  73334. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  73335. image.src = url;
  73336. }
  73337. };
  73338. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  73339. var _this = this;
  73340. var updateVersion = function () {
  73341. // the version is not yet in the DB or we need to update it
  73342. _this._saveVersionIntoDBAsync(url, versionLoaded);
  73343. };
  73344. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  73345. };
  73346. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  73347. var _this = this;
  73348. if (this.isSupported && this.db) {
  73349. var version;
  73350. try {
  73351. var transaction = this.db.transaction(["versions"]);
  73352. transaction.oncomplete = function (event) {
  73353. if (version) {
  73354. // If the version in the JSON file is different from the version in DB
  73355. if (_this.manifestVersionFound !== version.data) {
  73356. _this.mustUpdateRessources = true;
  73357. updateInDBCallback();
  73358. }
  73359. else {
  73360. callback(version.data);
  73361. }
  73362. }
  73363. // version was not found in DB
  73364. else {
  73365. _this.mustUpdateRessources = true;
  73366. updateInDBCallback();
  73367. }
  73368. };
  73369. transaction.onabort = function (event) {
  73370. callback(-1);
  73371. };
  73372. var getRequest = transaction.objectStore("versions").get(url);
  73373. getRequest.onsuccess = function (event) {
  73374. version = (event.target).result;
  73375. };
  73376. getRequest.onerror = function (event) {
  73377. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  73378. callback(-1);
  73379. };
  73380. }
  73381. catch (ex) {
  73382. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  73383. callback(-1);
  73384. }
  73385. }
  73386. else {
  73387. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  73388. callback(-1);
  73389. }
  73390. };
  73391. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  73392. var _this = this;
  73393. if (this.isSupported && !this.hasReachedQuota && this.db) {
  73394. try {
  73395. // Open a transaction to the database
  73396. var transaction = this.db.transaction(["versions"], "readwrite");
  73397. // the transaction could abort because of a QuotaExceededError error
  73398. transaction.onabort = function (event) {
  73399. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  73400. var error = event.srcElement['error'];
  73401. if (error && error.name === "QuotaExceededError") {
  73402. _this.hasReachedQuota = true;
  73403. }
  73404. }
  73405. catch (ex) { }
  73406. callback(-1);
  73407. };
  73408. transaction.oncomplete = function (event) {
  73409. callback(_this.manifestVersionFound);
  73410. };
  73411. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  73412. // Put the scene into the database
  73413. var addRequest = transaction.objectStore("versions").put(newVersion);
  73414. addRequest.onsuccess = function (event) {
  73415. };
  73416. addRequest.onerror = function (event) {
  73417. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  73418. };
  73419. }
  73420. catch (ex) {
  73421. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  73422. callback(-1);
  73423. }
  73424. }
  73425. else {
  73426. callback(-1);
  73427. }
  73428. };
  73429. /**
  73430. * Loads a file from database
  73431. * @param url defines the URL to load from
  73432. * @param sceneLoaded defines a callback to call on success
  73433. * @param progressCallBack defines a callback to call when progress changed
  73434. * @param errorCallback defines a callback to call on error
  73435. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  73436. */
  73437. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  73438. var _this = this;
  73439. var completeUrl = Database._ReturnFullUrlLocation(url);
  73440. var saveAndLoadFile = function () {
  73441. // the scene is not yet in the DB, let's try to save it
  73442. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  73443. };
  73444. this._checkVersionFromDB(completeUrl, function (version) {
  73445. if (version !== -1) {
  73446. if (!_this.mustUpdateRessources) {
  73447. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  73448. }
  73449. else {
  73450. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  73451. }
  73452. }
  73453. else {
  73454. if (errorCallback) {
  73455. errorCallback();
  73456. }
  73457. }
  73458. });
  73459. };
  73460. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  73461. if (this.isSupported && this.db) {
  73462. var targetStore;
  73463. if (url.indexOf(".babylon") !== -1) {
  73464. targetStore = "scenes";
  73465. }
  73466. else {
  73467. targetStore = "textures";
  73468. }
  73469. var file;
  73470. var transaction = this.db.transaction([targetStore]);
  73471. transaction.oncomplete = function (event) {
  73472. if (file) {
  73473. callback(file.data);
  73474. }
  73475. // file was not found in DB
  73476. else {
  73477. notInDBCallback();
  73478. }
  73479. };
  73480. transaction.onabort = function (event) {
  73481. notInDBCallback();
  73482. };
  73483. var getRequest = transaction.objectStore(targetStore).get(url);
  73484. getRequest.onsuccess = function (event) {
  73485. file = (event.target).result;
  73486. };
  73487. getRequest.onerror = function (event) {
  73488. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  73489. notInDBCallback();
  73490. };
  73491. }
  73492. else {
  73493. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  73494. callback();
  73495. }
  73496. };
  73497. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer, errorCallback) {
  73498. var _this = this;
  73499. if (this.isSupported) {
  73500. var targetStore;
  73501. if (url.indexOf(".babylon") !== -1) {
  73502. targetStore = "scenes";
  73503. }
  73504. else {
  73505. targetStore = "textures";
  73506. }
  73507. // Create XHR
  73508. var xhr = new XMLHttpRequest();
  73509. var fileData;
  73510. xhr.open("GET", url + "?" + Date.now(), true);
  73511. if (useArrayBuffer) {
  73512. xhr.responseType = "arraybuffer";
  73513. }
  73514. if (progressCallback) {
  73515. xhr.onprogress = progressCallback;
  73516. }
  73517. xhr.addEventListener("load", function () {
  73518. if (xhr.status === 200 || (xhr.status < 400 && BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6))) {
  73519. // Blob as response (XHR2)
  73520. //fileData = xhr.responseText;
  73521. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  73522. if (!_this.hasReachedQuota && _this.db) {
  73523. // Open a transaction to the database
  73524. var transaction = _this.db.transaction([targetStore], "readwrite");
  73525. // the transaction could abort because of a QuotaExceededError error
  73526. transaction.onabort = function (event) {
  73527. try {
  73528. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  73529. var error = event.srcElement['error'];
  73530. if (error && error.name === "QuotaExceededError") {
  73531. _this.hasReachedQuota = true;
  73532. }
  73533. }
  73534. catch (ex) { }
  73535. callback(fileData);
  73536. };
  73537. transaction.oncomplete = function (event) {
  73538. callback(fileData);
  73539. };
  73540. var newFile;
  73541. if (targetStore === "scenes") {
  73542. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  73543. }
  73544. else {
  73545. newFile = { textureUrl: url, data: fileData };
  73546. }
  73547. try {
  73548. // Put the scene into the database
  73549. var addRequest = transaction.objectStore(targetStore).put(newFile);
  73550. addRequest.onsuccess = function (event) {
  73551. };
  73552. addRequest.onerror = function (event) {
  73553. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  73554. };
  73555. }
  73556. catch (ex) {
  73557. callback(fileData);
  73558. }
  73559. }
  73560. else {
  73561. callback(fileData);
  73562. }
  73563. }
  73564. else {
  73565. if (xhr.status >= 400 && errorCallback) {
  73566. errorCallback(xhr);
  73567. }
  73568. else {
  73569. callback();
  73570. }
  73571. }
  73572. }, false);
  73573. xhr.addEventListener("error", function (event) {
  73574. BABYLON.Tools.Error("error on XHR request.");
  73575. callback();
  73576. }, false);
  73577. xhr.send();
  73578. }
  73579. else {
  73580. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  73581. callback();
  73582. }
  73583. };
  73584. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  73585. Database.IsUASupportingBlobStorage = true;
  73586. /** Gets a boolean indicating if Database storate is enabled */
  73587. Database.IDBStorageEnabled = true;
  73588. Database._ParseURL = function (url) {
  73589. var a = document.createElement('a');
  73590. a.href = url;
  73591. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  73592. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  73593. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  73594. return absLocation;
  73595. };
  73596. Database._ReturnFullUrlLocation = function (url) {
  73597. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  73598. return (Database._ParseURL(window.location.href) + url);
  73599. }
  73600. else {
  73601. return url;
  73602. }
  73603. };
  73604. return Database;
  73605. }());
  73606. BABYLON.Database = Database;
  73607. })(BABYLON || (BABYLON = {}));
  73608. //# sourceMappingURL=babylon.database.js.map
  73609. var BABYLON;
  73610. (function (BABYLON) {
  73611. var FresnelParameters = /** @class */ (function () {
  73612. function FresnelParameters() {
  73613. this._isEnabled = true;
  73614. this.leftColor = BABYLON.Color3.White();
  73615. this.rightColor = BABYLON.Color3.Black();
  73616. this.bias = 0;
  73617. this.power = 1;
  73618. }
  73619. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  73620. get: function () {
  73621. return this._isEnabled;
  73622. },
  73623. set: function (value) {
  73624. if (this._isEnabled === value) {
  73625. return;
  73626. }
  73627. this._isEnabled = value;
  73628. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  73629. },
  73630. enumerable: true,
  73631. configurable: true
  73632. });
  73633. FresnelParameters.prototype.clone = function () {
  73634. var newFresnelParameters = new FresnelParameters();
  73635. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  73636. return newFresnelParameters;
  73637. };
  73638. FresnelParameters.prototype.serialize = function () {
  73639. var serializationObject = {};
  73640. serializationObject.isEnabled = this.isEnabled;
  73641. serializationObject.leftColor = this.leftColor.asArray();
  73642. serializationObject.rightColor = this.rightColor.asArray();
  73643. serializationObject.bias = this.bias;
  73644. serializationObject.power = this.power;
  73645. return serializationObject;
  73646. };
  73647. FresnelParameters.Parse = function (parsedFresnelParameters) {
  73648. var fresnelParameters = new FresnelParameters();
  73649. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  73650. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  73651. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  73652. fresnelParameters.bias = parsedFresnelParameters.bias;
  73653. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  73654. return fresnelParameters;
  73655. };
  73656. return FresnelParameters;
  73657. }());
  73658. BABYLON.FresnelParameters = FresnelParameters;
  73659. })(BABYLON || (BABYLON = {}));
  73660. //# sourceMappingURL=babylon.fresnelParameters.js.map
  73661. var BABYLON;
  73662. (function (BABYLON) {
  73663. var MultiMaterial = /** @class */ (function (_super) {
  73664. __extends(MultiMaterial, _super);
  73665. function MultiMaterial(name, scene) {
  73666. var _this = _super.call(this, name, scene, true) || this;
  73667. scene.multiMaterials.push(_this);
  73668. _this.subMaterials = new Array();
  73669. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  73670. return _this;
  73671. }
  73672. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  73673. get: function () {
  73674. return this._subMaterials;
  73675. },
  73676. set: function (value) {
  73677. this._subMaterials = value;
  73678. this._hookArray(value);
  73679. },
  73680. enumerable: true,
  73681. configurable: true
  73682. });
  73683. MultiMaterial.prototype._hookArray = function (array) {
  73684. var _this = this;
  73685. var oldPush = array.push;
  73686. array.push = function () {
  73687. var items = [];
  73688. for (var _i = 0; _i < arguments.length; _i++) {
  73689. items[_i] = arguments[_i];
  73690. }
  73691. var result = oldPush.apply(array, items);
  73692. _this._markAllSubMeshesAsTexturesDirty();
  73693. return result;
  73694. };
  73695. var oldSplice = array.splice;
  73696. array.splice = function (index, deleteCount) {
  73697. var deleted = oldSplice.apply(array, [index, deleteCount]);
  73698. _this._markAllSubMeshesAsTexturesDirty();
  73699. return deleted;
  73700. };
  73701. };
  73702. // Properties
  73703. MultiMaterial.prototype.getSubMaterial = function (index) {
  73704. if (index < 0 || index >= this.subMaterials.length) {
  73705. return this.getScene().defaultMaterial;
  73706. }
  73707. return this.subMaterials[index];
  73708. };
  73709. MultiMaterial.prototype.getActiveTextures = function () {
  73710. var _a;
  73711. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  73712. if (subMaterial) {
  73713. return subMaterial.getActiveTextures();
  73714. }
  73715. else {
  73716. return [];
  73717. }
  73718. }));
  73719. };
  73720. // Methods
  73721. MultiMaterial.prototype.getClassName = function () {
  73722. return "MultiMaterial";
  73723. };
  73724. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  73725. for (var index = 0; index < this.subMaterials.length; index++) {
  73726. var subMaterial = this.subMaterials[index];
  73727. if (subMaterial) {
  73728. if (subMaterial.storeEffectOnSubMeshes) {
  73729. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  73730. return false;
  73731. }
  73732. continue;
  73733. }
  73734. if (!subMaterial.isReady(mesh)) {
  73735. return false;
  73736. }
  73737. }
  73738. }
  73739. return true;
  73740. };
  73741. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  73742. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  73743. for (var index = 0; index < this.subMaterials.length; index++) {
  73744. var subMaterial = null;
  73745. var current = this.subMaterials[index];
  73746. if (cloneChildren && current) {
  73747. subMaterial = current.clone(name + "-" + current.name);
  73748. }
  73749. else {
  73750. subMaterial = this.subMaterials[index];
  73751. }
  73752. newMultiMaterial.subMaterials.push(subMaterial);
  73753. }
  73754. return newMultiMaterial;
  73755. };
  73756. MultiMaterial.prototype.serialize = function () {
  73757. var serializationObject = {};
  73758. serializationObject.name = this.name;
  73759. serializationObject.id = this.id;
  73760. if (BABYLON.Tags) {
  73761. serializationObject.tags = BABYLON.Tags.GetTags(this);
  73762. }
  73763. serializationObject.materials = [];
  73764. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  73765. var subMat = this.subMaterials[matIndex];
  73766. if (subMat) {
  73767. serializationObject.materials.push(subMat.id);
  73768. }
  73769. else {
  73770. serializationObject.materials.push(null);
  73771. }
  73772. }
  73773. return serializationObject;
  73774. };
  73775. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  73776. var scene = this.getScene();
  73777. if (!scene) {
  73778. return;
  73779. }
  73780. var index = scene.multiMaterials.indexOf(this);
  73781. if (index >= 0) {
  73782. scene.multiMaterials.splice(index, 1);
  73783. }
  73784. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  73785. };
  73786. return MultiMaterial;
  73787. }(BABYLON.Material));
  73788. BABYLON.MultiMaterial = MultiMaterial;
  73789. })(BABYLON || (BABYLON = {}));
  73790. //# sourceMappingURL=babylon.multiMaterial.js.map
  73791. var BABYLON;
  73792. (function (BABYLON) {
  73793. var FreeCameraTouchInput = /** @class */ (function () {
  73794. function FreeCameraTouchInput() {
  73795. this._offsetX = null;
  73796. this._offsetY = null;
  73797. this._pointerPressed = new Array();
  73798. this.touchAngularSensibility = 200000.0;
  73799. this.touchMoveSensibility = 250.0;
  73800. }
  73801. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  73802. var _this = this;
  73803. var previousPosition = null;
  73804. if (this._pointerInput === undefined) {
  73805. this._onLostFocus = function (evt) {
  73806. _this._offsetX = null;
  73807. _this._offsetY = null;
  73808. };
  73809. this._pointerInput = function (p, s) {
  73810. var evt = p.event;
  73811. if (evt.pointerType === "mouse") {
  73812. return;
  73813. }
  73814. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  73815. if (!noPreventDefault) {
  73816. evt.preventDefault();
  73817. }
  73818. _this._pointerPressed.push(evt.pointerId);
  73819. if (_this._pointerPressed.length !== 1) {
  73820. return;
  73821. }
  73822. previousPosition = {
  73823. x: evt.clientX,
  73824. y: evt.clientY
  73825. };
  73826. }
  73827. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  73828. if (!noPreventDefault) {
  73829. evt.preventDefault();
  73830. }
  73831. var index = _this._pointerPressed.indexOf(evt.pointerId);
  73832. if (index === -1) {
  73833. return;
  73834. }
  73835. _this._pointerPressed.splice(index, 1);
  73836. if (index != 0) {
  73837. return;
  73838. }
  73839. previousPosition = null;
  73840. _this._offsetX = null;
  73841. _this._offsetY = null;
  73842. }
  73843. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  73844. if (!noPreventDefault) {
  73845. evt.preventDefault();
  73846. }
  73847. if (!previousPosition) {
  73848. return;
  73849. }
  73850. var index = _this._pointerPressed.indexOf(evt.pointerId);
  73851. if (index != 0) {
  73852. return;
  73853. }
  73854. _this._offsetX = evt.clientX - previousPosition.x;
  73855. _this._offsetY = -(evt.clientY - previousPosition.y);
  73856. }
  73857. };
  73858. }
  73859. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  73860. if (this._onLostFocus) {
  73861. element.addEventListener("blur", this._onLostFocus);
  73862. }
  73863. };
  73864. FreeCameraTouchInput.prototype.detachControl = function (element) {
  73865. if (this._pointerInput && element) {
  73866. if (this._observer) {
  73867. this.camera.getScene().onPointerObservable.remove(this._observer);
  73868. this._observer = null;
  73869. }
  73870. if (this._onLostFocus) {
  73871. element.removeEventListener("blur", this._onLostFocus);
  73872. this._onLostFocus = null;
  73873. }
  73874. this._pointerPressed = [];
  73875. this._offsetX = null;
  73876. this._offsetY = null;
  73877. }
  73878. };
  73879. FreeCameraTouchInput.prototype.checkInputs = function () {
  73880. if (this._offsetX && this._offsetY) {
  73881. var camera = this.camera;
  73882. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  73883. if (this._pointerPressed.length > 1) {
  73884. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  73885. }
  73886. else {
  73887. var speed = camera._computeLocalCameraSpeed();
  73888. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  73889. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  73890. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  73891. }
  73892. }
  73893. };
  73894. FreeCameraTouchInput.prototype.getClassName = function () {
  73895. return "FreeCameraTouchInput";
  73896. };
  73897. FreeCameraTouchInput.prototype.getSimpleName = function () {
  73898. return "touch";
  73899. };
  73900. __decorate([
  73901. BABYLON.serialize()
  73902. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  73903. __decorate([
  73904. BABYLON.serialize()
  73905. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  73906. return FreeCameraTouchInput;
  73907. }());
  73908. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  73909. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  73910. })(BABYLON || (BABYLON = {}));
  73911. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  73912. var BABYLON;
  73913. (function (BABYLON) {
  73914. BABYLON.Node.AddNodeConstructor("TouchCamera", function (name, scene) {
  73915. return function () { return new TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  73916. });
  73917. // We're mainly based on the logic defined into the FreeCamera code
  73918. var TouchCamera = /** @class */ (function (_super) {
  73919. __extends(TouchCamera, _super);
  73920. //-- end properties for backward compatibility for inputs
  73921. function TouchCamera(name, position, scene) {
  73922. var _this = _super.call(this, name, position, scene) || this;
  73923. _this.inputs.addTouch();
  73924. _this._setupInputs();
  73925. return _this;
  73926. }
  73927. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  73928. //-- Begin properties for backward compatibility for inputs
  73929. get: function () {
  73930. var touch = this.inputs.attached["touch"];
  73931. if (touch)
  73932. return touch.touchAngularSensibility;
  73933. return 0;
  73934. },
  73935. set: function (value) {
  73936. var touch = this.inputs.attached["touch"];
  73937. if (touch)
  73938. touch.touchAngularSensibility = value;
  73939. },
  73940. enumerable: true,
  73941. configurable: true
  73942. });
  73943. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  73944. get: function () {
  73945. var touch = this.inputs.attached["touch"];
  73946. if (touch)
  73947. return touch.touchMoveSensibility;
  73948. return 0;
  73949. },
  73950. set: function (value) {
  73951. var touch = this.inputs.attached["touch"];
  73952. if (touch)
  73953. touch.touchMoveSensibility = value;
  73954. },
  73955. enumerable: true,
  73956. configurable: true
  73957. });
  73958. TouchCamera.prototype.getClassName = function () {
  73959. return "TouchCamera";
  73960. };
  73961. /** @hidden */
  73962. TouchCamera.prototype._setupInputs = function () {
  73963. var mouse = this.inputs.attached["mouse"];
  73964. if (mouse) {
  73965. mouse.touchEnabled = false;
  73966. }
  73967. };
  73968. return TouchCamera;
  73969. }(BABYLON.FreeCamera));
  73970. BABYLON.TouchCamera = TouchCamera;
  73971. })(BABYLON || (BABYLON = {}));
  73972. //# sourceMappingURL=babylon.touchCamera.js.map
  73973. var BABYLON;
  73974. (function (BABYLON) {
  73975. var ProceduralTexture = /** @class */ (function (_super) {
  73976. __extends(ProceduralTexture, _super);
  73977. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  73978. if (fallbackTexture === void 0) { fallbackTexture = null; }
  73979. if (generateMipMaps === void 0) { generateMipMaps = true; }
  73980. if (isCube === void 0) { isCube = false; }
  73981. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  73982. _this.isCube = isCube;
  73983. _this.isEnabled = true;
  73984. _this._currentRefreshId = -1;
  73985. _this._refreshRate = 1;
  73986. _this._vertexBuffers = {};
  73987. _this._uniforms = new Array();
  73988. _this._samplers = new Array();
  73989. /** @hidden */
  73990. _this._textures = {};
  73991. _this._floats = {};
  73992. _this._ints = {};
  73993. _this._floatsArrays = {};
  73994. _this._colors3 = {};
  73995. _this._colors4 = {};
  73996. _this._vectors2 = {};
  73997. _this._vectors3 = {};
  73998. _this._matrices = {};
  73999. _this._fallbackTextureUsed = false;
  74000. _this._cachedDefines = "";
  74001. scene = _this.getScene();
  74002. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_PROCEDURALTEXTURE);
  74003. if (!component) {
  74004. component = new BABYLON.ProceduralTextureSceneComponent(scene);
  74005. scene._addComponent(component);
  74006. }
  74007. scene.proceduralTextures.push(_this);
  74008. _this._engine = scene.getEngine();
  74009. _this.name = name;
  74010. _this.isRenderTarget = true;
  74011. _this._size = size;
  74012. _this._generateMipMaps = generateMipMaps;
  74013. _this.setFragment(fragment);
  74014. _this._fallbackTexture = fallbackTexture;
  74015. if (isCube) {
  74016. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  74017. _this.setFloat("face", 0);
  74018. }
  74019. else {
  74020. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  74021. }
  74022. // VBO
  74023. var vertices = [];
  74024. vertices.push(1, 1);
  74025. vertices.push(-1, 1);
  74026. vertices.push(-1, -1);
  74027. vertices.push(1, -1);
  74028. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  74029. _this._createIndexBuffer();
  74030. return _this;
  74031. }
  74032. ProceduralTexture.prototype._createIndexBuffer = function () {
  74033. var engine = this._engine;
  74034. // Indices
  74035. var indices = [];
  74036. indices.push(0);
  74037. indices.push(1);
  74038. indices.push(2);
  74039. indices.push(0);
  74040. indices.push(2);
  74041. indices.push(3);
  74042. this._indexBuffer = engine.createIndexBuffer(indices);
  74043. };
  74044. /** @hidden */
  74045. ProceduralTexture.prototype._rebuild = function () {
  74046. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  74047. if (vb) {
  74048. vb._rebuild();
  74049. }
  74050. this._createIndexBuffer();
  74051. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  74052. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  74053. }
  74054. };
  74055. ProceduralTexture.prototype.reset = function () {
  74056. if (this._effect === undefined) {
  74057. return;
  74058. }
  74059. var engine = this._engine;
  74060. engine._releaseEffect(this._effect);
  74061. };
  74062. ProceduralTexture.prototype._getDefines = function () {
  74063. return "";
  74064. };
  74065. ProceduralTexture.prototype.isReady = function () {
  74066. var _this = this;
  74067. var engine = this._engine;
  74068. var shaders;
  74069. if (!this._fragment) {
  74070. return false;
  74071. }
  74072. if (this._fallbackTextureUsed) {
  74073. return true;
  74074. }
  74075. var defines = this._getDefines();
  74076. if (this._effect && defines === this._cachedDefines && this._effect.isReady()) {
  74077. return true;
  74078. }
  74079. if (this._fragment.fragmentElement !== undefined) {
  74080. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  74081. }
  74082. else {
  74083. shaders = { vertex: "procedural", fragment: this._fragment };
  74084. }
  74085. this._cachedDefines = defines;
  74086. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, defines, undefined, undefined, function () {
  74087. _this.releaseInternalTexture();
  74088. if (_this._fallbackTexture) {
  74089. _this._texture = _this._fallbackTexture._texture;
  74090. if (_this._texture) {
  74091. _this._texture.incrementReferences();
  74092. }
  74093. }
  74094. _this._fallbackTextureUsed = true;
  74095. });
  74096. return this._effect.isReady();
  74097. };
  74098. ProceduralTexture.prototype.resetRefreshCounter = function () {
  74099. this._currentRefreshId = -1;
  74100. };
  74101. ProceduralTexture.prototype.setFragment = function (fragment) {
  74102. this._fragment = fragment;
  74103. };
  74104. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  74105. get: function () {
  74106. return this._refreshRate;
  74107. },
  74108. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  74109. set: function (value) {
  74110. this._refreshRate = value;
  74111. this.resetRefreshCounter();
  74112. },
  74113. enumerable: true,
  74114. configurable: true
  74115. });
  74116. /** @hidden */
  74117. ProceduralTexture.prototype._shouldRender = function () {
  74118. if (!this.isEnabled || !this.isReady() || !this._texture) {
  74119. return false;
  74120. }
  74121. if (this._fallbackTextureUsed) {
  74122. return false;
  74123. }
  74124. if (this._currentRefreshId === -1) { // At least render once
  74125. this._currentRefreshId = 1;
  74126. return true;
  74127. }
  74128. if (this.refreshRate === this._currentRefreshId) {
  74129. this._currentRefreshId = 1;
  74130. return true;
  74131. }
  74132. this._currentRefreshId++;
  74133. return false;
  74134. };
  74135. ProceduralTexture.prototype.getRenderSize = function () {
  74136. return this._size;
  74137. };
  74138. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  74139. if (this._fallbackTextureUsed) {
  74140. return;
  74141. }
  74142. this.releaseInternalTexture();
  74143. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  74144. // Update properties
  74145. this._size = size;
  74146. this._generateMipMaps = generateMipMaps;
  74147. };
  74148. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  74149. if (this._uniforms.indexOf(uniformName) === -1) {
  74150. this._uniforms.push(uniformName);
  74151. }
  74152. };
  74153. ProceduralTexture.prototype.setTexture = function (name, texture) {
  74154. if (this._samplers.indexOf(name) === -1) {
  74155. this._samplers.push(name);
  74156. }
  74157. this._textures[name] = texture;
  74158. return this;
  74159. };
  74160. ProceduralTexture.prototype.setFloat = function (name, value) {
  74161. this._checkUniform(name);
  74162. this._floats[name] = value;
  74163. return this;
  74164. };
  74165. /**
  74166. * Set the value of an uniform to an integer value
  74167. * @param name defines the name of the uniform
  74168. * @param value defines the value to set
  74169. * @returns the current procedural texture
  74170. */
  74171. ProceduralTexture.prototype.setInt = function (name, value) {
  74172. this._checkUniform(name);
  74173. this._ints[name] = value;
  74174. return this;
  74175. };
  74176. ProceduralTexture.prototype.setFloats = function (name, value) {
  74177. this._checkUniform(name);
  74178. this._floatsArrays[name] = value;
  74179. return this;
  74180. };
  74181. ProceduralTexture.prototype.setColor3 = function (name, value) {
  74182. this._checkUniform(name);
  74183. this._colors3[name] = value;
  74184. return this;
  74185. };
  74186. ProceduralTexture.prototype.setColor4 = function (name, value) {
  74187. this._checkUniform(name);
  74188. this._colors4[name] = value;
  74189. return this;
  74190. };
  74191. ProceduralTexture.prototype.setVector2 = function (name, value) {
  74192. this._checkUniform(name);
  74193. this._vectors2[name] = value;
  74194. return this;
  74195. };
  74196. ProceduralTexture.prototype.setVector3 = function (name, value) {
  74197. this._checkUniform(name);
  74198. this._vectors3[name] = value;
  74199. return this;
  74200. };
  74201. ProceduralTexture.prototype.setMatrix = function (name, value) {
  74202. this._checkUniform(name);
  74203. this._matrices[name] = value;
  74204. return this;
  74205. };
  74206. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  74207. var scene = this.getScene();
  74208. if (!scene) {
  74209. return;
  74210. }
  74211. var engine = this._engine;
  74212. // Render
  74213. engine.enableEffect(this._effect);
  74214. engine.setState(false);
  74215. // Texture
  74216. for (var name in this._textures) {
  74217. this._effect.setTexture(name, this._textures[name]);
  74218. }
  74219. // Float
  74220. for (name in this._ints) {
  74221. this._effect.setInt(name, this._ints[name]);
  74222. }
  74223. // Float
  74224. for (name in this._floats) {
  74225. this._effect.setFloat(name, this._floats[name]);
  74226. }
  74227. // Floats
  74228. for (name in this._floatsArrays) {
  74229. this._effect.setArray(name, this._floatsArrays[name]);
  74230. }
  74231. // Color3
  74232. for (name in this._colors3) {
  74233. this._effect.setColor3(name, this._colors3[name]);
  74234. }
  74235. // Color4
  74236. for (name in this._colors4) {
  74237. var color = this._colors4[name];
  74238. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  74239. }
  74240. // Vector2
  74241. for (name in this._vectors2) {
  74242. this._effect.setVector2(name, this._vectors2[name]);
  74243. }
  74244. // Vector3
  74245. for (name in this._vectors3) {
  74246. this._effect.setVector3(name, this._vectors3[name]);
  74247. }
  74248. // Matrix
  74249. for (name in this._matrices) {
  74250. this._effect.setMatrix(name, this._matrices[name]);
  74251. }
  74252. if (!this._texture) {
  74253. return;
  74254. }
  74255. if (this.isCube) {
  74256. for (var face = 0; face < 6; face++) {
  74257. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  74258. // VBOs
  74259. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  74260. this._effect.setFloat("face", face);
  74261. // Clear
  74262. engine.clear(scene.clearColor, true, true, true);
  74263. // Draw order
  74264. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  74265. // Mipmaps
  74266. if (face === 5) {
  74267. engine.generateMipMapsForCubemap(this._texture);
  74268. }
  74269. }
  74270. }
  74271. else {
  74272. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  74273. // VBOs
  74274. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  74275. // Clear
  74276. engine.clear(scene.clearColor, true, true, true);
  74277. // Draw order
  74278. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  74279. }
  74280. // Unbind
  74281. engine.unBindFramebuffer(this._texture, this.isCube);
  74282. if (this.onGenerated) {
  74283. this.onGenerated();
  74284. }
  74285. };
  74286. ProceduralTexture.prototype.clone = function () {
  74287. var textureSize = this.getSize();
  74288. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  74289. // Base texture
  74290. newTexture.hasAlpha = this.hasAlpha;
  74291. newTexture.level = this.level;
  74292. // RenderTarget Texture
  74293. newTexture.coordinatesMode = this.coordinatesMode;
  74294. return newTexture;
  74295. };
  74296. ProceduralTexture.prototype.dispose = function () {
  74297. var scene = this.getScene();
  74298. if (!scene) {
  74299. return;
  74300. }
  74301. var index = scene.proceduralTextures.indexOf(this);
  74302. if (index >= 0) {
  74303. scene.proceduralTextures.splice(index, 1);
  74304. }
  74305. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  74306. if (vertexBuffer) {
  74307. vertexBuffer.dispose();
  74308. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  74309. }
  74310. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  74311. this._indexBuffer = null;
  74312. }
  74313. _super.prototype.dispose.call(this);
  74314. };
  74315. __decorate([
  74316. BABYLON.serialize()
  74317. ], ProceduralTexture.prototype, "_size", void 0);
  74318. __decorate([
  74319. BABYLON.serialize()
  74320. ], ProceduralTexture.prototype, "_generateMipMaps", void 0);
  74321. __decorate([
  74322. BABYLON.serialize()
  74323. ], ProceduralTexture.prototype, "isEnabled", void 0);
  74324. __decorate([
  74325. BABYLON.serialize()
  74326. ], ProceduralTexture.prototype, "refreshRate", null);
  74327. return ProceduralTexture;
  74328. }(BABYLON.Texture));
  74329. BABYLON.ProceduralTexture = ProceduralTexture;
  74330. })(BABYLON || (BABYLON = {}));
  74331. //# sourceMappingURL=babylon.proceduralTexture.js.map
  74332. var BABYLON;
  74333. (function (BABYLON) {
  74334. /**
  74335. * Defines the Procedural Texture scene component responsible to manage any Procedural Texture
  74336. * in a given scene.
  74337. */
  74338. var ProceduralTextureSceneComponent = /** @class */ (function () {
  74339. /**
  74340. * Creates a new instance of the component for the given scene
  74341. * @param scene Defines the scene to register the component in
  74342. */
  74343. function ProceduralTextureSceneComponent(scene) {
  74344. /**
  74345. * The component name helpfull to identify the component in the list of scene components.
  74346. */
  74347. this.name = BABYLON.SceneComponentConstants.NAME_PROCEDURALTEXTURE;
  74348. this.scene = scene;
  74349. this.scene.proceduralTextures = new Array();
  74350. scene.layers = new Array();
  74351. }
  74352. /**
  74353. * Registers the component in a given scene
  74354. */
  74355. ProceduralTextureSceneComponent.prototype.register = function () {
  74356. this.scene._beforeClearStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE, this, this._beforeClear);
  74357. };
  74358. /**
  74359. * Rebuilds the elements related to this component in case of
  74360. * context lost for instance.
  74361. */
  74362. ProceduralTextureSceneComponent.prototype.rebuild = function () {
  74363. // Nothing to do here.
  74364. };
  74365. /**
  74366. * Disposes the component and the associated ressources.
  74367. */
  74368. ProceduralTextureSceneComponent.prototype.dispose = function () {
  74369. // Nothing to do here.
  74370. };
  74371. ProceduralTextureSceneComponent.prototype._beforeClear = function () {
  74372. if (this.scene.proceduralTexturesEnabled) {
  74373. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0);
  74374. for (var proceduralIndex = 0; proceduralIndex < this.scene.proceduralTextures.length; proceduralIndex++) {
  74375. var proceduralTexture = this.scene.proceduralTextures[proceduralIndex];
  74376. if (proceduralTexture._shouldRender()) {
  74377. proceduralTexture.render();
  74378. }
  74379. }
  74380. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0);
  74381. }
  74382. };
  74383. return ProceduralTextureSceneComponent;
  74384. }());
  74385. BABYLON.ProceduralTextureSceneComponent = ProceduralTextureSceneComponent;
  74386. })(BABYLON || (BABYLON = {}));
  74387. //# sourceMappingURL=babylon.proceduralTextureSceneComponent.js.map
  74388. var BABYLON;
  74389. (function (BABYLON) {
  74390. var CustomProceduralTexture = /** @class */ (function (_super) {
  74391. __extends(CustomProceduralTexture, _super);
  74392. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  74393. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  74394. _this._animate = true;
  74395. _this._time = 0;
  74396. _this._texturePath = texturePath;
  74397. //Try to load json
  74398. _this.loadJson(texturePath);
  74399. _this.refreshRate = 1;
  74400. return _this;
  74401. }
  74402. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  74403. var _this = this;
  74404. var noConfigFile = function () {
  74405. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  74406. try {
  74407. _this.setFragment(_this._texturePath);
  74408. }
  74409. catch (ex) {
  74410. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  74411. }
  74412. };
  74413. var configFileUrl = jsonUrl + "/config.json";
  74414. var xhr = new XMLHttpRequest();
  74415. xhr.open("GET", configFileUrl, true);
  74416. xhr.addEventListener("load", function () {
  74417. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  74418. try {
  74419. _this._config = JSON.parse(xhr.response);
  74420. _this.updateShaderUniforms();
  74421. _this.updateTextures();
  74422. _this.setFragment(_this._texturePath + "/custom");
  74423. _this._animate = _this._config.animate;
  74424. _this.refreshRate = _this._config.refreshrate;
  74425. }
  74426. catch (ex) {
  74427. noConfigFile();
  74428. }
  74429. }
  74430. else {
  74431. noConfigFile();
  74432. }
  74433. }, false);
  74434. xhr.addEventListener("error", function () {
  74435. noConfigFile();
  74436. }, false);
  74437. try {
  74438. xhr.send();
  74439. }
  74440. catch (ex) {
  74441. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  74442. }
  74443. };
  74444. CustomProceduralTexture.prototype.isReady = function () {
  74445. if (!_super.prototype.isReady.call(this)) {
  74446. return false;
  74447. }
  74448. for (var name in this._textures) {
  74449. var texture = this._textures[name];
  74450. if (!texture.isReady()) {
  74451. return false;
  74452. }
  74453. }
  74454. return true;
  74455. };
  74456. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  74457. var scene = this.getScene();
  74458. if (this._animate && scene) {
  74459. this._time += scene.getAnimationRatio() * 0.03;
  74460. this.updateShaderUniforms();
  74461. }
  74462. _super.prototype.render.call(this, useCameraPostProcess);
  74463. };
  74464. CustomProceduralTexture.prototype.updateTextures = function () {
  74465. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  74466. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  74467. }
  74468. };
  74469. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  74470. if (this._config) {
  74471. for (var j = 0; j < this._config.uniforms.length; j++) {
  74472. var uniform = this._config.uniforms[j];
  74473. switch (uniform.type) {
  74474. case "float":
  74475. this.setFloat(uniform.name, uniform.value);
  74476. break;
  74477. case "color3":
  74478. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  74479. break;
  74480. case "color4":
  74481. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  74482. break;
  74483. case "vector2":
  74484. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  74485. break;
  74486. case "vector3":
  74487. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  74488. break;
  74489. }
  74490. }
  74491. }
  74492. this.setFloat("time", this._time);
  74493. };
  74494. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  74495. get: function () {
  74496. return this._animate;
  74497. },
  74498. set: function (value) {
  74499. this._animate = value;
  74500. },
  74501. enumerable: true,
  74502. configurable: true
  74503. });
  74504. return CustomProceduralTexture;
  74505. }(BABYLON.ProceduralTexture));
  74506. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  74507. })(BABYLON || (BABYLON = {}));
  74508. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  74509. var BABYLON;
  74510. (function (BABYLON) {
  74511. var FreeCameraGamepadInput = /** @class */ (function () {
  74512. function FreeCameraGamepadInput() {
  74513. this.gamepadAngularSensibility = 200;
  74514. this.gamepadMoveSensibility = 40;
  74515. // private members
  74516. this._cameraTransform = BABYLON.Matrix.Identity();
  74517. this._deltaTransform = BABYLON.Vector3.Zero();
  74518. this._vector3 = BABYLON.Vector3.Zero();
  74519. this._vector2 = BABYLON.Vector2.Zero();
  74520. }
  74521. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  74522. var _this = this;
  74523. var manager = this.camera.getScene().gamepadManager;
  74524. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  74525. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  74526. // prioritize XBOX gamepads.
  74527. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  74528. _this.gamepad = gamepad;
  74529. }
  74530. }
  74531. });
  74532. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  74533. if (_this.gamepad === gamepad) {
  74534. _this.gamepad = null;
  74535. }
  74536. });
  74537. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  74538. };
  74539. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  74540. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  74541. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  74542. this.gamepad = null;
  74543. };
  74544. FreeCameraGamepadInput.prototype.checkInputs = function () {
  74545. if (this.gamepad && this.gamepad.leftStick) {
  74546. var camera = this.camera;
  74547. var LSValues = this.gamepad.leftStick;
  74548. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  74549. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  74550. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  74551. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  74552. var RSValues = this.gamepad.rightStick;
  74553. if (RSValues) {
  74554. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  74555. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  74556. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  74557. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  74558. }
  74559. else {
  74560. RSValues = { x: 0, y: 0 };
  74561. }
  74562. if (!camera.rotationQuaternion) {
  74563. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  74564. }
  74565. else {
  74566. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  74567. }
  74568. var speed = camera._computeLocalCameraSpeed() * 50.0;
  74569. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  74570. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  74571. camera.cameraDirection.addInPlace(this._deltaTransform);
  74572. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  74573. camera.cameraRotation.addInPlace(this._vector2);
  74574. }
  74575. };
  74576. FreeCameraGamepadInput.prototype.getClassName = function () {
  74577. return "FreeCameraGamepadInput";
  74578. };
  74579. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  74580. return "gamepad";
  74581. };
  74582. __decorate([
  74583. BABYLON.serialize()
  74584. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  74585. __decorate([
  74586. BABYLON.serialize()
  74587. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  74588. return FreeCameraGamepadInput;
  74589. }());
  74590. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  74591. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  74592. })(BABYLON || (BABYLON = {}));
  74593. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  74594. var BABYLON;
  74595. (function (BABYLON) {
  74596. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  74597. function ArcRotateCameraGamepadInput() {
  74598. this.gamepadRotationSensibility = 80;
  74599. this.gamepadMoveSensibility = 40;
  74600. }
  74601. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  74602. var _this = this;
  74603. var manager = this.camera.getScene().gamepadManager;
  74604. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  74605. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  74606. // prioritize XBOX gamepads.
  74607. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  74608. _this.gamepad = gamepad;
  74609. }
  74610. }
  74611. });
  74612. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  74613. if (_this.gamepad === gamepad) {
  74614. _this.gamepad = null;
  74615. }
  74616. });
  74617. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  74618. };
  74619. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  74620. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  74621. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  74622. this.gamepad = null;
  74623. };
  74624. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  74625. if (this.gamepad) {
  74626. var camera = this.camera;
  74627. var RSValues = this.gamepad.rightStick;
  74628. if (RSValues) {
  74629. if (RSValues.x != 0) {
  74630. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  74631. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  74632. camera.inertialAlphaOffset += normalizedRX;
  74633. }
  74634. }
  74635. if (RSValues.y != 0) {
  74636. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  74637. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  74638. camera.inertialBetaOffset += normalizedRY;
  74639. }
  74640. }
  74641. }
  74642. var LSValues = this.gamepad.leftStick;
  74643. if (LSValues && LSValues.y != 0) {
  74644. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  74645. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  74646. this.camera.inertialRadiusOffset -= normalizedLY;
  74647. }
  74648. }
  74649. }
  74650. };
  74651. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  74652. return "ArcRotateCameraGamepadInput";
  74653. };
  74654. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  74655. return "gamepad";
  74656. };
  74657. __decorate([
  74658. BABYLON.serialize()
  74659. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  74660. __decorate([
  74661. BABYLON.serialize()
  74662. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  74663. return ArcRotateCameraGamepadInput;
  74664. }());
  74665. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  74666. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  74667. })(BABYLON || (BABYLON = {}));
  74668. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  74669. var BABYLON;
  74670. (function (BABYLON) {
  74671. var GamepadManager = /** @class */ (function () {
  74672. function GamepadManager(_scene) {
  74673. var _this = this;
  74674. this._scene = _scene;
  74675. this._babylonGamepads = [];
  74676. this._oneGamepadConnected = false;
  74677. /** @hidden */
  74678. this._isMonitoring = false;
  74679. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  74680. if (!BABYLON.Tools.IsWindowObjectExist()) {
  74681. this._gamepadEventSupported = false;
  74682. }
  74683. else {
  74684. this._gamepadEventSupported = 'GamepadEvent' in window;
  74685. this._gamepadSupport = (navigator.getGamepads ||
  74686. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  74687. }
  74688. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  74689. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  74690. for (var i in _this._babylonGamepads) {
  74691. var gamepad = _this._babylonGamepads[i];
  74692. if (gamepad && gamepad._isConnected) {
  74693. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  74694. }
  74695. }
  74696. });
  74697. this._onGamepadConnectedEvent = function (evt) {
  74698. var gamepad = evt.gamepad;
  74699. if (gamepad.index in _this._babylonGamepads) {
  74700. if (_this._babylonGamepads[gamepad.index].isConnected) {
  74701. return;
  74702. }
  74703. }
  74704. var newGamepad;
  74705. if (_this._babylonGamepads[gamepad.index]) {
  74706. newGamepad = _this._babylonGamepads[gamepad.index];
  74707. newGamepad.browserGamepad = gamepad;
  74708. newGamepad._isConnected = true;
  74709. }
  74710. else {
  74711. newGamepad = _this._addNewGamepad(gamepad);
  74712. }
  74713. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  74714. _this._startMonitoringGamepads();
  74715. };
  74716. this._onGamepadDisconnectedEvent = function (evt) {
  74717. var gamepad = evt.gamepad;
  74718. // Remove the gamepad from the list of gamepads to monitor.
  74719. for (var i in _this._babylonGamepads) {
  74720. if (_this._babylonGamepads[i].index === gamepad.index) {
  74721. var disconnectedGamepad = _this._babylonGamepads[i];
  74722. disconnectedGamepad._isConnected = false;
  74723. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  74724. break;
  74725. }
  74726. }
  74727. };
  74728. if (this._gamepadSupport) {
  74729. //first add already-connected gamepads
  74730. this._updateGamepadObjects();
  74731. if (this._babylonGamepads.length) {
  74732. this._startMonitoringGamepads();
  74733. }
  74734. // Checking if the gamepad connected event is supported (like in Firefox)
  74735. if (this._gamepadEventSupported) {
  74736. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  74737. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  74738. }
  74739. else {
  74740. this._startMonitoringGamepads();
  74741. }
  74742. }
  74743. }
  74744. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  74745. get: function () {
  74746. return this._babylonGamepads;
  74747. },
  74748. enumerable: true,
  74749. configurable: true
  74750. });
  74751. GamepadManager.prototype.getGamepadByType = function (type) {
  74752. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  74753. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  74754. var gamepad = _a[_i];
  74755. if (gamepad && gamepad.type === type) {
  74756. return gamepad;
  74757. }
  74758. }
  74759. return null;
  74760. };
  74761. GamepadManager.prototype.dispose = function () {
  74762. if (this._gamepadEventSupported) {
  74763. if (this._onGamepadConnectedEvent) {
  74764. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  74765. }
  74766. if (this._onGamepadDisconnectedEvent) {
  74767. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  74768. }
  74769. this._onGamepadConnectedEvent = null;
  74770. this._onGamepadDisconnectedEvent = null;
  74771. }
  74772. this._babylonGamepads.forEach(function (gamepad) {
  74773. gamepad.dispose();
  74774. });
  74775. this.onGamepadConnectedObservable.clear();
  74776. this.onGamepadDisconnectedObservable.clear();
  74777. this._oneGamepadConnected = false;
  74778. this._stopMonitoringGamepads();
  74779. this._babylonGamepads = [];
  74780. };
  74781. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  74782. if (!this._oneGamepadConnected) {
  74783. this._oneGamepadConnected = true;
  74784. }
  74785. var newGamepad;
  74786. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  74787. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  74788. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  74789. }
  74790. // if pose is supported, use the (WebVR) pose enabled controller
  74791. else if (gamepad.pose) {
  74792. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  74793. }
  74794. else {
  74795. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  74796. }
  74797. this._babylonGamepads[newGamepad.index] = newGamepad;
  74798. return newGamepad;
  74799. };
  74800. GamepadManager.prototype._startMonitoringGamepads = function () {
  74801. if (!this._isMonitoring) {
  74802. this._isMonitoring = true;
  74803. //back-comp
  74804. if (!this._scene) {
  74805. this._checkGamepadsStatus();
  74806. }
  74807. }
  74808. };
  74809. GamepadManager.prototype._stopMonitoringGamepads = function () {
  74810. this._isMonitoring = false;
  74811. };
  74812. /** @hidden */
  74813. GamepadManager.prototype._checkGamepadsStatus = function () {
  74814. var _this = this;
  74815. // Hack to be compatible Chrome
  74816. this._updateGamepadObjects();
  74817. for (var i in this._babylonGamepads) {
  74818. var gamepad = this._babylonGamepads[i];
  74819. if (!gamepad || !gamepad.isConnected) {
  74820. continue;
  74821. }
  74822. gamepad.update();
  74823. }
  74824. if (this._isMonitoring && !this._scene) {
  74825. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  74826. }
  74827. };
  74828. // This function is called only on Chrome, which does not properly support
  74829. // connection/disconnection events and forces you to recopy again the gamepad object
  74830. GamepadManager.prototype._updateGamepadObjects = function () {
  74831. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  74832. for (var i = 0; i < gamepads.length; i++) {
  74833. var gamepad = gamepads[i];
  74834. if (gamepad) {
  74835. if (!this._babylonGamepads[gamepad.index]) {
  74836. var newGamepad = this._addNewGamepad(gamepad);
  74837. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  74838. }
  74839. else {
  74840. // Forced to copy again this object for Chrome for unknown reason
  74841. this._babylonGamepads[i].browserGamepad = gamepad;
  74842. if (!this._babylonGamepads[i].isConnected) {
  74843. this._babylonGamepads[i]._isConnected = true;
  74844. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  74845. }
  74846. }
  74847. }
  74848. }
  74849. };
  74850. return GamepadManager;
  74851. }());
  74852. BABYLON.GamepadManager = GamepadManager;
  74853. })(BABYLON || (BABYLON = {}));
  74854. //# sourceMappingURL=babylon.gamepadManager.js.map
  74855. var BABYLON;
  74856. (function (BABYLON) {
  74857. var StickValues = /** @class */ (function () {
  74858. function StickValues(x, y) {
  74859. this.x = x;
  74860. this.y = y;
  74861. }
  74862. return StickValues;
  74863. }());
  74864. BABYLON.StickValues = StickValues;
  74865. var Gamepad = /** @class */ (function () {
  74866. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  74867. if (leftStickX === void 0) { leftStickX = 0; }
  74868. if (leftStickY === void 0) { leftStickY = 1; }
  74869. if (rightStickX === void 0) { rightStickX = 2; }
  74870. if (rightStickY === void 0) { rightStickY = 3; }
  74871. this.id = id;
  74872. this.index = index;
  74873. this.browserGamepad = browserGamepad;
  74874. this._leftStick = { x: 0, y: 0 };
  74875. this._rightStick = { x: 0, y: 0 };
  74876. /** @hidden */
  74877. this._isConnected = true;
  74878. this._invertLeftStickY = false;
  74879. this.type = Gamepad.GAMEPAD;
  74880. this._leftStickAxisX = leftStickX;
  74881. this._leftStickAxisY = leftStickY;
  74882. this._rightStickAxisX = rightStickX;
  74883. this._rightStickAxisY = rightStickY;
  74884. if (this.browserGamepad.axes.length >= 2) {
  74885. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  74886. }
  74887. if (this.browserGamepad.axes.length >= 4) {
  74888. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  74889. }
  74890. }
  74891. Object.defineProperty(Gamepad.prototype, "isConnected", {
  74892. get: function () {
  74893. return this._isConnected;
  74894. },
  74895. enumerable: true,
  74896. configurable: true
  74897. });
  74898. Gamepad.prototype.onleftstickchanged = function (callback) {
  74899. this._onleftstickchanged = callback;
  74900. };
  74901. Gamepad.prototype.onrightstickchanged = function (callback) {
  74902. this._onrightstickchanged = callback;
  74903. };
  74904. Object.defineProperty(Gamepad.prototype, "leftStick", {
  74905. get: function () {
  74906. return this._leftStick;
  74907. },
  74908. set: function (newValues) {
  74909. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  74910. this._onleftstickchanged(newValues);
  74911. }
  74912. this._leftStick = newValues;
  74913. },
  74914. enumerable: true,
  74915. configurable: true
  74916. });
  74917. Object.defineProperty(Gamepad.prototype, "rightStick", {
  74918. get: function () {
  74919. return this._rightStick;
  74920. },
  74921. set: function (newValues) {
  74922. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  74923. this._onrightstickchanged(newValues);
  74924. }
  74925. this._rightStick = newValues;
  74926. },
  74927. enumerable: true,
  74928. configurable: true
  74929. });
  74930. Gamepad.prototype.update = function () {
  74931. if (this._leftStick) {
  74932. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  74933. if (this._invertLeftStickY) {
  74934. this.leftStick.y *= -1;
  74935. }
  74936. }
  74937. if (this._rightStick) {
  74938. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  74939. }
  74940. };
  74941. Gamepad.prototype.dispose = function () {
  74942. };
  74943. Gamepad.GAMEPAD = 0;
  74944. Gamepad.GENERIC = 1;
  74945. Gamepad.XBOX = 2;
  74946. Gamepad.POSE_ENABLED = 3;
  74947. return Gamepad;
  74948. }());
  74949. BABYLON.Gamepad = Gamepad;
  74950. var GenericPad = /** @class */ (function (_super) {
  74951. __extends(GenericPad, _super);
  74952. function GenericPad(id, index, browserGamepad) {
  74953. var _this = _super.call(this, id, index, browserGamepad) || this;
  74954. _this.onButtonDownObservable = new BABYLON.Observable();
  74955. _this.onButtonUpObservable = new BABYLON.Observable();
  74956. _this.type = Gamepad.GENERIC;
  74957. _this._buttons = new Array(browserGamepad.buttons.length);
  74958. return _this;
  74959. }
  74960. GenericPad.prototype.onbuttondown = function (callback) {
  74961. this._onbuttondown = callback;
  74962. };
  74963. GenericPad.prototype.onbuttonup = function (callback) {
  74964. this._onbuttonup = callback;
  74965. };
  74966. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  74967. if (newValue !== currentValue) {
  74968. if (newValue === 1) {
  74969. if (this._onbuttondown) {
  74970. this._onbuttondown(buttonIndex);
  74971. }
  74972. this.onButtonDownObservable.notifyObservers(buttonIndex);
  74973. }
  74974. if (newValue === 0) {
  74975. if (this._onbuttonup) {
  74976. this._onbuttonup(buttonIndex);
  74977. }
  74978. this.onButtonUpObservable.notifyObservers(buttonIndex);
  74979. }
  74980. }
  74981. return newValue;
  74982. };
  74983. GenericPad.prototype.update = function () {
  74984. _super.prototype.update.call(this);
  74985. for (var index = 0; index < this._buttons.length; index++) {
  74986. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  74987. }
  74988. };
  74989. GenericPad.prototype.dispose = function () {
  74990. _super.prototype.dispose.call(this);
  74991. this.onButtonDownObservable.clear();
  74992. this.onButtonUpObservable.clear();
  74993. };
  74994. return GenericPad;
  74995. }(Gamepad));
  74996. BABYLON.GenericPad = GenericPad;
  74997. })(BABYLON || (BABYLON = {}));
  74998. //# sourceMappingURL=babylon.gamepad.js.map
  74999. var BABYLON;
  75000. (function (BABYLON) {
  75001. /**
  75002. * Defines supported buttons for XBox360 compatible gamepads
  75003. */
  75004. var Xbox360Button;
  75005. (function (Xbox360Button) {
  75006. /** A */
  75007. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  75008. /** B */
  75009. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  75010. /** X */
  75011. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  75012. /** Y */
  75013. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  75014. /** Start */
  75015. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  75016. /** Back */
  75017. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  75018. /** Left button */
  75019. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  75020. /** Right button */
  75021. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  75022. /** Left stick */
  75023. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  75024. /** Right stick */
  75025. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  75026. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  75027. /** Defines values for XBox360 DPad */
  75028. var Xbox360Dpad;
  75029. (function (Xbox360Dpad) {
  75030. /** Up */
  75031. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  75032. /** Down */
  75033. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  75034. /** Left */
  75035. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  75036. /** Right */
  75037. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  75038. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  75039. /**
  75040. * Defines a XBox360 gamepad
  75041. */
  75042. var Xbox360Pad = /** @class */ (function (_super) {
  75043. __extends(Xbox360Pad, _super);
  75044. /**
  75045. * Creates a new XBox360 gamepad object
  75046. * @param id defines the id of this gamepad
  75047. * @param index defines its index
  75048. * @param gamepad defines the internal HTML gamepad object
  75049. * @param xboxOne defines if it is a XBox One gamepad
  75050. */
  75051. function Xbox360Pad(id, index, gamepad, xboxOne) {
  75052. if (xboxOne === void 0) { xboxOne = false; }
  75053. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  75054. _this._leftTrigger = 0;
  75055. _this._rightTrigger = 0;
  75056. /** Observable raised when a button is pressed */
  75057. _this.onButtonDownObservable = new BABYLON.Observable();
  75058. /** Observable raised when a button is released */
  75059. _this.onButtonUpObservable = new BABYLON.Observable();
  75060. /** Observable raised when a pad is pressed */
  75061. _this.onPadDownObservable = new BABYLON.Observable();
  75062. /** Observable raised when a pad is released */
  75063. _this.onPadUpObservable = new BABYLON.Observable();
  75064. _this._buttonA = 0;
  75065. _this._buttonB = 0;
  75066. _this._buttonX = 0;
  75067. _this._buttonY = 0;
  75068. _this._buttonBack = 0;
  75069. _this._buttonStart = 0;
  75070. _this._buttonLB = 0;
  75071. _this._buttonRB = 0;
  75072. _this._buttonLeftStick = 0;
  75073. _this._buttonRightStick = 0;
  75074. _this._dPadUp = 0;
  75075. _this._dPadDown = 0;
  75076. _this._dPadLeft = 0;
  75077. _this._dPadRight = 0;
  75078. _this._isXboxOnePad = false;
  75079. _this.type = BABYLON.Gamepad.XBOX;
  75080. _this._isXboxOnePad = xboxOne;
  75081. return _this;
  75082. }
  75083. /**
  75084. * Defines the callback to call when left trigger is pressed
  75085. * @param callback defines the callback to use
  75086. */
  75087. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  75088. this._onlefttriggerchanged = callback;
  75089. };
  75090. /**
  75091. * Defines the callback to call when right trigger is pressed
  75092. * @param callback defines the callback to use
  75093. */
  75094. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  75095. this._onrighttriggerchanged = callback;
  75096. };
  75097. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  75098. /**
  75099. * Gets or sets left trigger value
  75100. */
  75101. get: function () {
  75102. return this._leftTrigger;
  75103. },
  75104. set: function (newValue) {
  75105. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  75106. this._onlefttriggerchanged(newValue);
  75107. }
  75108. this._leftTrigger = newValue;
  75109. },
  75110. enumerable: true,
  75111. configurable: true
  75112. });
  75113. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  75114. /**
  75115. * Gets or sets right trigger value
  75116. */
  75117. get: function () {
  75118. return this._rightTrigger;
  75119. },
  75120. set: function (newValue) {
  75121. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  75122. this._onrighttriggerchanged(newValue);
  75123. }
  75124. this._rightTrigger = newValue;
  75125. },
  75126. enumerable: true,
  75127. configurable: true
  75128. });
  75129. /**
  75130. * Defines the callback to call when a button is pressed
  75131. * @param callback defines the callback to use
  75132. */
  75133. Xbox360Pad.prototype.onbuttondown = function (callback) {
  75134. this._onbuttondown = callback;
  75135. };
  75136. /**
  75137. * Defines the callback to call when a button is released
  75138. * @param callback defines the callback to use
  75139. */
  75140. Xbox360Pad.prototype.onbuttonup = function (callback) {
  75141. this._onbuttonup = callback;
  75142. };
  75143. /**
  75144. * Defines the callback to call when a pad is pressed
  75145. * @param callback defines the callback to use
  75146. */
  75147. Xbox360Pad.prototype.ondpaddown = function (callback) {
  75148. this._ondpaddown = callback;
  75149. };
  75150. /**
  75151. * Defines the callback to call when a pad is released
  75152. * @param callback defines the callback to use
  75153. */
  75154. Xbox360Pad.prototype.ondpadup = function (callback) {
  75155. this._ondpadup = callback;
  75156. };
  75157. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  75158. if (newValue !== currentValue) {
  75159. if (newValue === 1) {
  75160. if (this._onbuttondown) {
  75161. this._onbuttondown(buttonType);
  75162. }
  75163. this.onButtonDownObservable.notifyObservers(buttonType);
  75164. }
  75165. if (newValue === 0) {
  75166. if (this._onbuttonup) {
  75167. this._onbuttonup(buttonType);
  75168. }
  75169. this.onButtonUpObservable.notifyObservers(buttonType);
  75170. }
  75171. }
  75172. return newValue;
  75173. };
  75174. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  75175. if (newValue !== currentValue) {
  75176. if (newValue === 1) {
  75177. if (this._ondpaddown) {
  75178. this._ondpaddown(buttonType);
  75179. }
  75180. this.onPadDownObservable.notifyObservers(buttonType);
  75181. }
  75182. if (newValue === 0) {
  75183. if (this._ondpadup) {
  75184. this._ondpadup(buttonType);
  75185. }
  75186. this.onPadUpObservable.notifyObservers(buttonType);
  75187. }
  75188. }
  75189. return newValue;
  75190. };
  75191. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  75192. /** Gets or sets value of A button */
  75193. get: function () {
  75194. return this._buttonA;
  75195. },
  75196. set: function (value) {
  75197. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  75198. },
  75199. enumerable: true,
  75200. configurable: true
  75201. });
  75202. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  75203. /** Gets or sets value of B button */
  75204. get: function () {
  75205. return this._buttonB;
  75206. },
  75207. set: function (value) {
  75208. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  75209. },
  75210. enumerable: true,
  75211. configurable: true
  75212. });
  75213. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  75214. /** Gets or sets value of X button */
  75215. get: function () {
  75216. return this._buttonX;
  75217. },
  75218. set: function (value) {
  75219. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  75220. },
  75221. enumerable: true,
  75222. configurable: true
  75223. });
  75224. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  75225. /** Gets or sets value of Y button */
  75226. get: function () {
  75227. return this._buttonY;
  75228. },
  75229. set: function (value) {
  75230. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  75231. },
  75232. enumerable: true,
  75233. configurable: true
  75234. });
  75235. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  75236. /** Gets or sets value of Start button */
  75237. get: function () {
  75238. return this._buttonStart;
  75239. },
  75240. set: function (value) {
  75241. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  75242. },
  75243. enumerable: true,
  75244. configurable: true
  75245. });
  75246. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  75247. /** Gets or sets value of Back button */
  75248. get: function () {
  75249. return this._buttonBack;
  75250. },
  75251. set: function (value) {
  75252. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  75253. },
  75254. enumerable: true,
  75255. configurable: true
  75256. });
  75257. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  75258. /** Gets or sets value of Left button */
  75259. get: function () {
  75260. return this._buttonLB;
  75261. },
  75262. set: function (value) {
  75263. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  75264. },
  75265. enumerable: true,
  75266. configurable: true
  75267. });
  75268. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  75269. /** Gets or sets value of Right button */
  75270. get: function () {
  75271. return this._buttonRB;
  75272. },
  75273. set: function (value) {
  75274. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  75275. },
  75276. enumerable: true,
  75277. configurable: true
  75278. });
  75279. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  75280. /** Gets or sets value of left stick */
  75281. get: function () {
  75282. return this._buttonLeftStick;
  75283. },
  75284. set: function (value) {
  75285. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  75286. },
  75287. enumerable: true,
  75288. configurable: true
  75289. });
  75290. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  75291. /** Gets or sets value of right stick */
  75292. get: function () {
  75293. return this._buttonRightStick;
  75294. },
  75295. set: function (value) {
  75296. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  75297. },
  75298. enumerable: true,
  75299. configurable: true
  75300. });
  75301. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  75302. /** Gets or sets value of DPad up */
  75303. get: function () {
  75304. return this._dPadUp;
  75305. },
  75306. set: function (value) {
  75307. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  75308. },
  75309. enumerable: true,
  75310. configurable: true
  75311. });
  75312. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  75313. /** Gets or sets value of DPad down */
  75314. get: function () {
  75315. return this._dPadDown;
  75316. },
  75317. set: function (value) {
  75318. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  75319. },
  75320. enumerable: true,
  75321. configurable: true
  75322. });
  75323. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  75324. /** Gets or sets value of DPad left */
  75325. get: function () {
  75326. return this._dPadLeft;
  75327. },
  75328. set: function (value) {
  75329. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  75330. },
  75331. enumerable: true,
  75332. configurable: true
  75333. });
  75334. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  75335. /** Gets or sets value of DPad right */
  75336. get: function () {
  75337. return this._dPadRight;
  75338. },
  75339. set: function (value) {
  75340. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  75341. },
  75342. enumerable: true,
  75343. configurable: true
  75344. });
  75345. /**
  75346. * Force the gamepad to synchronize with device values
  75347. */
  75348. Xbox360Pad.prototype.update = function () {
  75349. _super.prototype.update.call(this);
  75350. if (this._isXboxOnePad) {
  75351. this.buttonA = this.browserGamepad.buttons[0].value;
  75352. this.buttonB = this.browserGamepad.buttons[1].value;
  75353. this.buttonX = this.browserGamepad.buttons[2].value;
  75354. this.buttonY = this.browserGamepad.buttons[3].value;
  75355. this.buttonLB = this.browserGamepad.buttons[4].value;
  75356. this.buttonRB = this.browserGamepad.buttons[5].value;
  75357. this.leftTrigger = this.browserGamepad.axes[2];
  75358. this.rightTrigger = this.browserGamepad.axes[5];
  75359. this.buttonBack = this.browserGamepad.buttons[9].value;
  75360. this.buttonStart = this.browserGamepad.buttons[8].value;
  75361. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  75362. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  75363. this.dPadUp = this.browserGamepad.buttons[11].value;
  75364. this.dPadDown = this.browserGamepad.buttons[12].value;
  75365. this.dPadLeft = this.browserGamepad.buttons[13].value;
  75366. this.dPadRight = this.browserGamepad.buttons[14].value;
  75367. }
  75368. else {
  75369. this.buttonA = this.browserGamepad.buttons[0].value;
  75370. this.buttonB = this.browserGamepad.buttons[1].value;
  75371. this.buttonX = this.browserGamepad.buttons[2].value;
  75372. this.buttonY = this.browserGamepad.buttons[3].value;
  75373. this.buttonLB = this.browserGamepad.buttons[4].value;
  75374. this.buttonRB = this.browserGamepad.buttons[5].value;
  75375. this.leftTrigger = this.browserGamepad.buttons[6].value;
  75376. this.rightTrigger = this.browserGamepad.buttons[7].value;
  75377. this.buttonBack = this.browserGamepad.buttons[8].value;
  75378. this.buttonStart = this.browserGamepad.buttons[9].value;
  75379. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  75380. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  75381. this.dPadUp = this.browserGamepad.buttons[12].value;
  75382. this.dPadDown = this.browserGamepad.buttons[13].value;
  75383. this.dPadLeft = this.browserGamepad.buttons[14].value;
  75384. this.dPadRight = this.browserGamepad.buttons[15].value;
  75385. }
  75386. };
  75387. Xbox360Pad.prototype.dispose = function () {
  75388. _super.prototype.dispose.call(this);
  75389. this.onButtonDownObservable.clear();
  75390. this.onButtonUpObservable.clear();
  75391. this.onPadDownObservable.clear();
  75392. this.onPadUpObservable.clear();
  75393. };
  75394. return Xbox360Pad;
  75395. }(BABYLON.Gamepad));
  75396. BABYLON.Xbox360Pad = Xbox360Pad;
  75397. })(BABYLON || (BABYLON = {}));
  75398. //# sourceMappingURL=babylon.xboxGamepad.js.map
  75399. var BABYLON;
  75400. (function (BABYLON) {
  75401. /**
  75402. * Defines the types of pose enabled controllers that are supported
  75403. */
  75404. var PoseEnabledControllerType;
  75405. (function (PoseEnabledControllerType) {
  75406. /**
  75407. * HTC Vive
  75408. */
  75409. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  75410. /**
  75411. * Oculus Rift
  75412. */
  75413. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  75414. /**
  75415. * Windows mixed reality
  75416. */
  75417. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  75418. /**
  75419. * Samsung gear VR
  75420. */
  75421. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  75422. /**
  75423. * Google Daydream
  75424. */
  75425. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  75426. /**
  75427. * Generic
  75428. */
  75429. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  75430. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  75431. /**
  75432. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  75433. */
  75434. var PoseEnabledControllerHelper = /** @class */ (function () {
  75435. function PoseEnabledControllerHelper() {
  75436. }
  75437. /**
  75438. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  75439. * @param vrGamepad the gamepad to initialized
  75440. * @returns a vr controller of the type the gamepad identified as
  75441. */
  75442. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  75443. // Oculus Touch
  75444. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  75445. return new BABYLON.OculusTouchController(vrGamepad);
  75446. }
  75447. // Windows Mixed Reality controllers
  75448. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  75449. return new BABYLON.WindowsMotionController(vrGamepad);
  75450. }
  75451. // HTC Vive
  75452. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  75453. return new BABYLON.ViveController(vrGamepad);
  75454. }
  75455. // Samsung/Oculus Gear VR or Oculus Go
  75456. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  75457. return new BABYLON.GearVRController(vrGamepad);
  75458. }
  75459. // Google Daydream
  75460. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  75461. return new BABYLON.DaydreamController(vrGamepad);
  75462. }
  75463. // Generic
  75464. else {
  75465. return new BABYLON.GenericController(vrGamepad);
  75466. }
  75467. };
  75468. return PoseEnabledControllerHelper;
  75469. }());
  75470. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  75471. /**
  75472. * Defines the PoseEnabledController object that contains state of a vr capable controller
  75473. */
  75474. var PoseEnabledController = /** @class */ (function (_super) {
  75475. __extends(PoseEnabledController, _super);
  75476. /**
  75477. * Creates a new PoseEnabledController from a gamepad
  75478. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  75479. */
  75480. function PoseEnabledController(browserGamepad) {
  75481. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  75482. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  75483. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  75484. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  75485. /**
  75486. * The device position in babylon space
  75487. */
  75488. _this.devicePosition = BABYLON.Vector3.Zero();
  75489. /**
  75490. * The device rotation in babylon space
  75491. */
  75492. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  75493. /**
  75494. * The scale factor of the device in babylon space
  75495. */
  75496. _this.deviceScaleFactor = 1;
  75497. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  75498. /**
  75499. * Internal, matrix used to convert room space to babylon space
  75500. * @hidden
  75501. */
  75502. _this._deviceToWorld = BABYLON.Matrix.Identity();
  75503. /**
  75504. * Node to be used when casting a ray from the controller
  75505. * @hidden
  75506. */
  75507. _this._pointingPoseNode = null;
  75508. _this._workingMatrix = BABYLON.Matrix.Identity();
  75509. /**
  75510. * @hidden
  75511. */
  75512. _this._meshAttachedObservable = new BABYLON.Observable();
  75513. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  75514. _this.controllerType = PoseEnabledControllerType.GENERIC;
  75515. _this.position = BABYLON.Vector3.Zero();
  75516. _this.rotationQuaternion = new BABYLON.Quaternion();
  75517. _this._calculatedPosition = BABYLON.Vector3.Zero();
  75518. _this._calculatedRotation = new BABYLON.Quaternion();
  75519. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  75520. return _this;
  75521. }
  75522. /**
  75523. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  75524. */
  75525. PoseEnabledController.prototype.update = function () {
  75526. _super.prototype.update.call(this);
  75527. this._updatePoseAndMesh();
  75528. };
  75529. /**
  75530. * Updates only the pose device and mesh without doing any button event checking
  75531. */
  75532. PoseEnabledController.prototype._updatePoseAndMesh = function () {
  75533. var pose = this.browserGamepad.pose;
  75534. this.updateFromDevice(pose);
  75535. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  75536. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  75537. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  75538. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  75539. if (this._mesh) {
  75540. this._mesh.position.copyFrom(this.devicePosition);
  75541. if (this._mesh.rotationQuaternion) {
  75542. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  75543. }
  75544. }
  75545. };
  75546. /**
  75547. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  75548. * @param poseData raw pose fromthe device
  75549. */
  75550. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  75551. if (poseData) {
  75552. this.rawPose = poseData;
  75553. if (poseData.position) {
  75554. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  75555. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  75556. this._deviceRoomPosition.z *= -1;
  75557. }
  75558. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  75559. this._calculatedPosition.addInPlace(this.position);
  75560. }
  75561. var pose = this.rawPose;
  75562. if (poseData.orientation && pose.orientation) {
  75563. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  75564. if (this._mesh) {
  75565. if (this._mesh.getScene().useRightHandedSystem) {
  75566. this._deviceRoomRotationQuaternion.z *= -1;
  75567. this._deviceRoomRotationQuaternion.w *= -1;
  75568. }
  75569. else {
  75570. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  75571. }
  75572. }
  75573. // if the camera is set, rotate to the camera's rotation
  75574. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  75575. }
  75576. }
  75577. };
  75578. /**
  75579. * Attaches a mesh to the controller
  75580. * @param mesh the mesh to be attached
  75581. */
  75582. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  75583. if (this._mesh) {
  75584. this._mesh.parent = null;
  75585. }
  75586. this._mesh = mesh;
  75587. if (this._poseControlledCamera) {
  75588. this._mesh.parent = this._poseControlledCamera;
  75589. }
  75590. if (!this._mesh.rotationQuaternion) {
  75591. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  75592. }
  75593. // 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
  75594. this._updatePoseAndMesh();
  75595. if (this._pointingPoseNode) {
  75596. var parents = [];
  75597. var obj = this._pointingPoseNode;
  75598. while (obj.parent) {
  75599. parents.push(obj.parent);
  75600. obj = obj.parent;
  75601. }
  75602. parents.reverse().forEach(function (p) { p.computeWorldMatrix(true); });
  75603. }
  75604. this._meshAttachedObservable.notifyObservers(mesh);
  75605. };
  75606. /**
  75607. * Attaches the controllers mesh to a camera
  75608. * @param camera the camera the mesh should be attached to
  75609. */
  75610. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  75611. this._poseControlledCamera = camera;
  75612. if (this._mesh) {
  75613. this._mesh.parent = this._poseControlledCamera;
  75614. }
  75615. };
  75616. /**
  75617. * Disposes of the controller
  75618. */
  75619. PoseEnabledController.prototype.dispose = function () {
  75620. if (this._mesh) {
  75621. this._mesh.dispose();
  75622. }
  75623. this._mesh = null;
  75624. _super.prototype.dispose.call(this);
  75625. };
  75626. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  75627. /**
  75628. * The mesh that is attached to the controller
  75629. */
  75630. get: function () {
  75631. return this._mesh;
  75632. },
  75633. enumerable: true,
  75634. configurable: true
  75635. });
  75636. /**
  75637. * Gets the ray of the controller in the direction the controller is pointing
  75638. * @param length the length the resulting ray should be
  75639. * @returns a ray in the direction the controller is pointing
  75640. */
  75641. PoseEnabledController.prototype.getForwardRay = function (length) {
  75642. if (length === void 0) { length = 100; }
  75643. if (!this.mesh) {
  75644. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  75645. }
  75646. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  75647. var origin = m.getTranslation();
  75648. var forward = new BABYLON.Vector3(0, 0, -1);
  75649. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  75650. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  75651. return new BABYLON.Ray(origin, direction, length);
  75652. };
  75653. /**
  75654. * Name of the child mesh that can be used to cast a ray from the controller
  75655. */
  75656. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  75657. return PoseEnabledController;
  75658. }(BABYLON.Gamepad));
  75659. BABYLON.PoseEnabledController = PoseEnabledController;
  75660. })(BABYLON || (BABYLON = {}));
  75661. //# sourceMappingURL=babylon.poseEnabledController.js.map
  75662. var BABYLON;
  75663. (function (BABYLON) {
  75664. /**
  75665. * Defines the WebVRController object that represents controllers tracked in 3D space
  75666. */
  75667. var WebVRController = /** @class */ (function (_super) {
  75668. __extends(WebVRController, _super);
  75669. /**
  75670. * Creates a new WebVRController from a gamepad
  75671. * @param vrGamepad the gamepad that the WebVRController should be created from
  75672. */
  75673. function WebVRController(vrGamepad) {
  75674. var _this = _super.call(this, vrGamepad) || this;
  75675. // Observables
  75676. /**
  75677. * Fired when the trigger state has changed
  75678. */
  75679. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  75680. /**
  75681. * Fired when the main button state has changed
  75682. */
  75683. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  75684. /**
  75685. * Fired when the secondary button state has changed
  75686. */
  75687. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  75688. /**
  75689. * Fired when the pad state has changed
  75690. */
  75691. _this.onPadStateChangedObservable = new BABYLON.Observable();
  75692. /**
  75693. * Fired when controllers stick values have changed
  75694. */
  75695. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  75696. /**
  75697. * X and Y axis corrisponding to the controllers joystick
  75698. */
  75699. _this.pad = { x: 0, y: 0 };
  75700. // avoid GC, store state in a tmp object
  75701. _this._changes = {
  75702. pressChanged: false,
  75703. touchChanged: false,
  75704. valueChanged: false,
  75705. changed: false
  75706. };
  75707. _this._buttons = new Array(vrGamepad.buttons.length);
  75708. _this.hand = vrGamepad.hand;
  75709. return _this;
  75710. }
  75711. /**
  75712. * Fired when a controller button's state has changed
  75713. * @param callback the callback containing the button that was modified
  75714. */
  75715. WebVRController.prototype.onButtonStateChange = function (callback) {
  75716. this._onButtonStateChange = callback;
  75717. };
  75718. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  75719. /**
  75720. * The default controller model for the controller
  75721. */
  75722. get: function () {
  75723. return this._defaultModel;
  75724. },
  75725. enumerable: true,
  75726. configurable: true
  75727. });
  75728. /**
  75729. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  75730. */
  75731. WebVRController.prototype.update = function () {
  75732. _super.prototype.update.call(this);
  75733. for (var index = 0; index < this._buttons.length; index++) {
  75734. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  75735. }
  75736. ;
  75737. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  75738. this.pad.x = this.leftStick.x;
  75739. this.pad.y = this.leftStick.y;
  75740. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  75741. }
  75742. };
  75743. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  75744. if (!newState) {
  75745. newState = {
  75746. pressed: false,
  75747. touched: false,
  75748. value: 0
  75749. };
  75750. }
  75751. if (!currentState) {
  75752. this._buttons[buttonIndex] = {
  75753. pressed: newState.pressed,
  75754. touched: newState.touched,
  75755. value: newState.value
  75756. };
  75757. return;
  75758. }
  75759. this._checkChanges(newState, currentState);
  75760. if (this._changes.changed) {
  75761. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  75762. this._handleButtonChange(buttonIndex, newState, this._changes);
  75763. }
  75764. this._buttons[buttonIndex].pressed = newState.pressed;
  75765. this._buttons[buttonIndex].touched = newState.touched;
  75766. // oculus triggers are never 0, thou not touched.
  75767. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  75768. };
  75769. WebVRController.prototype._checkChanges = function (newState, currentState) {
  75770. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  75771. this._changes.touchChanged = newState.touched !== currentState.touched;
  75772. this._changes.valueChanged = newState.value !== currentState.value;
  75773. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  75774. return this._changes;
  75775. };
  75776. /**
  75777. * Disposes of th webVRCOntroller
  75778. */
  75779. WebVRController.prototype.dispose = function () {
  75780. _super.prototype.dispose.call(this);
  75781. this.onTriggerStateChangedObservable.clear();
  75782. this.onMainButtonStateChangedObservable.clear();
  75783. this.onSecondaryButtonStateChangedObservable.clear();
  75784. this.onPadStateChangedObservable.clear();
  75785. this.onPadValuesChangedObservable.clear();
  75786. };
  75787. return WebVRController;
  75788. }(BABYLON.PoseEnabledController));
  75789. BABYLON.WebVRController = WebVRController;
  75790. })(BABYLON || (BABYLON = {}));
  75791. //# sourceMappingURL=babylon.webVRController.js.map
  75792. var BABYLON;
  75793. (function (BABYLON) {
  75794. /**
  75795. * Oculus Touch Controller
  75796. */
  75797. var OculusTouchController = /** @class */ (function (_super) {
  75798. __extends(OculusTouchController, _super);
  75799. /**
  75800. * Creates a new OculusTouchController from a gamepad
  75801. * @param vrGamepad the gamepad that the controller should be created from
  75802. */
  75803. function OculusTouchController(vrGamepad) {
  75804. var _this = _super.call(this, vrGamepad) || this;
  75805. /**
  75806. * Fired when the secondary trigger on this controller is modified
  75807. */
  75808. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  75809. /**
  75810. * Fired when the thumb rest on this controller is modified
  75811. */
  75812. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  75813. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  75814. return _this;
  75815. }
  75816. /**
  75817. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  75818. * @param scene scene in which to add meshes
  75819. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  75820. */
  75821. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  75822. var _this = this;
  75823. var meshName;
  75824. // Hand
  75825. if (this.hand === 'left') {
  75826. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  75827. }
  75828. else { // Right is the default if no hand is specified
  75829. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  75830. }
  75831. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  75832. /*
  75833. Parent Mesh name: oculus_touch_left
  75834. - body
  75835. - trigger
  75836. - thumbstick
  75837. - grip
  75838. - button_y
  75839. - button_x
  75840. - button_enter
  75841. */
  75842. _this._defaultModel = newMeshes[1];
  75843. _this.attachToMesh(_this._defaultModel);
  75844. if (meshLoaded) {
  75845. meshLoaded(_this._defaultModel);
  75846. }
  75847. });
  75848. };
  75849. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  75850. /**
  75851. * Fired when the A button on this controller is modified
  75852. */
  75853. get: function () {
  75854. if (this.hand === 'right') {
  75855. return this.onMainButtonStateChangedObservable;
  75856. }
  75857. else {
  75858. throw new Error('No A button on left hand');
  75859. }
  75860. },
  75861. enumerable: true,
  75862. configurable: true
  75863. });
  75864. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  75865. /**
  75866. * Fired when the B button on this controller is modified
  75867. */
  75868. get: function () {
  75869. if (this.hand === 'right') {
  75870. return this.onSecondaryButtonStateChangedObservable;
  75871. }
  75872. else {
  75873. throw new Error('No B button on left hand');
  75874. }
  75875. },
  75876. enumerable: true,
  75877. configurable: true
  75878. });
  75879. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  75880. /**
  75881. * Fired when the X button on this controller is modified
  75882. */
  75883. get: function () {
  75884. if (this.hand === 'left') {
  75885. return this.onMainButtonStateChangedObservable;
  75886. }
  75887. else {
  75888. throw new Error('No X button on right hand');
  75889. }
  75890. },
  75891. enumerable: true,
  75892. configurable: true
  75893. });
  75894. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  75895. /**
  75896. * Fired when the Y button on this controller is modified
  75897. */
  75898. get: function () {
  75899. if (this.hand === 'left') {
  75900. return this.onSecondaryButtonStateChangedObservable;
  75901. }
  75902. else {
  75903. throw new Error('No Y button on right hand');
  75904. }
  75905. },
  75906. enumerable: true,
  75907. configurable: true
  75908. });
  75909. /**
  75910. * Called once for each button that changed state since the last frame
  75911. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  75912. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  75913. * 2) secondary trigger (same)
  75914. * 3) A (right) X (left), touch, pressed = value
  75915. * 4) B / Y
  75916. * 5) thumb rest
  75917. * @param buttonIdx Which button index changed
  75918. * @param state New state of the button
  75919. * @param changes Which properties on the state changed since last frame
  75920. */
  75921. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  75922. var notifyObject = state; //{ state: state, changes: changes };
  75923. var triggerDirection = this.hand === 'right' ? -1 : 1;
  75924. switch (buttonIdx) {
  75925. case 0:
  75926. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  75927. return;
  75928. case 1: // index trigger
  75929. if (this._defaultModel) {
  75930. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  75931. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  75932. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  75933. }
  75934. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  75935. return;
  75936. case 2: // secondary trigger
  75937. if (this._defaultModel) {
  75938. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  75939. }
  75940. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  75941. return;
  75942. case 3:
  75943. if (this._defaultModel) {
  75944. if (notifyObject.pressed) {
  75945. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  75946. }
  75947. else {
  75948. (this._defaultModel.getChildren()[1]).position.y = 0;
  75949. }
  75950. }
  75951. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  75952. return;
  75953. case 4:
  75954. if (this._defaultModel) {
  75955. if (notifyObject.pressed) {
  75956. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  75957. }
  75958. else {
  75959. (this._defaultModel.getChildren()[2]).position.y = 0;
  75960. }
  75961. }
  75962. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  75963. return;
  75964. case 5:
  75965. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  75966. return;
  75967. }
  75968. };
  75969. /**
  75970. * Base Url for the controller model.
  75971. */
  75972. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  75973. /**
  75974. * File name for the left controller model.
  75975. */
  75976. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  75977. /**
  75978. * File name for the right controller model.
  75979. */
  75980. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  75981. return OculusTouchController;
  75982. }(BABYLON.WebVRController));
  75983. BABYLON.OculusTouchController = OculusTouchController;
  75984. })(BABYLON || (BABYLON = {}));
  75985. //# sourceMappingURL=babylon.oculusTouchController.js.map
  75986. var BABYLON;
  75987. (function (BABYLON) {
  75988. /**
  75989. * Vive Controller
  75990. */
  75991. var ViveController = /** @class */ (function (_super) {
  75992. __extends(ViveController, _super);
  75993. /**
  75994. * Creates a new ViveController from a gamepad
  75995. * @param vrGamepad the gamepad that the controller should be created from
  75996. */
  75997. function ViveController(vrGamepad) {
  75998. var _this = _super.call(this, vrGamepad) || this;
  75999. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  76000. _this._invertLeftStickY = true;
  76001. return _this;
  76002. }
  76003. /**
  76004. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  76005. * @param scene scene in which to add meshes
  76006. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  76007. */
  76008. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  76009. var _this = this;
  76010. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  76011. /*
  76012. Parent Mesh name: ViveWand
  76013. - body
  76014. - r_gripper
  76015. - l_gripper
  76016. - menu_button
  76017. - system_button
  76018. - trackpad
  76019. - trigger
  76020. - LED
  76021. */
  76022. _this._defaultModel = newMeshes[1];
  76023. _this.attachToMesh(_this._defaultModel);
  76024. if (meshLoaded) {
  76025. meshLoaded(_this._defaultModel);
  76026. }
  76027. });
  76028. };
  76029. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  76030. /**
  76031. * Fired when the left button on this controller is modified
  76032. */
  76033. get: function () {
  76034. return this.onMainButtonStateChangedObservable;
  76035. },
  76036. enumerable: true,
  76037. configurable: true
  76038. });
  76039. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  76040. /**
  76041. * Fired when the right button on this controller is modified
  76042. */
  76043. get: function () {
  76044. return this.onMainButtonStateChangedObservable;
  76045. },
  76046. enumerable: true,
  76047. configurable: true
  76048. });
  76049. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  76050. /**
  76051. * Fired when the menu button on this controller is modified
  76052. */
  76053. get: function () {
  76054. return this.onSecondaryButtonStateChangedObservable;
  76055. },
  76056. enumerable: true,
  76057. configurable: true
  76058. });
  76059. /**
  76060. * Called once for each button that changed state since the last frame
  76061. * Vive mapping:
  76062. * 0: touchpad
  76063. * 1: trigger
  76064. * 2: left AND right buttons
  76065. * 3: menu button
  76066. * @param buttonIdx Which button index changed
  76067. * @param state New state of the button
  76068. * @param changes Which properties on the state changed since last frame
  76069. */
  76070. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  76071. var notifyObject = state; //{ state: state, changes: changes };
  76072. switch (buttonIdx) {
  76073. case 0:
  76074. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  76075. return;
  76076. case 1: // index trigger
  76077. if (this._defaultModel) {
  76078. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  76079. }
  76080. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  76081. return;
  76082. case 2: // left AND right button
  76083. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  76084. return;
  76085. case 3:
  76086. if (this._defaultModel) {
  76087. if (notifyObject.pressed) {
  76088. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  76089. }
  76090. else {
  76091. (this._defaultModel.getChildren()[2]).position.y = 0;
  76092. }
  76093. }
  76094. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  76095. return;
  76096. }
  76097. };
  76098. /**
  76099. * Base Url for the controller model.
  76100. */
  76101. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  76102. /**
  76103. * File name for the controller model.
  76104. */
  76105. ViveController.MODEL_FILENAME = 'wand.babylon';
  76106. return ViveController;
  76107. }(BABYLON.WebVRController));
  76108. BABYLON.ViveController = ViveController;
  76109. })(BABYLON || (BABYLON = {}));
  76110. //# sourceMappingURL=babylon.viveController.js.map
  76111. var BABYLON;
  76112. (function (BABYLON) {
  76113. /**
  76114. * Generic Controller
  76115. */
  76116. var GenericController = /** @class */ (function (_super) {
  76117. __extends(GenericController, _super);
  76118. /**
  76119. * Creates a new GenericController from a gamepad
  76120. * @param vrGamepad the gamepad that the controller should be created from
  76121. */
  76122. function GenericController(vrGamepad) {
  76123. return _super.call(this, vrGamepad) || this;
  76124. }
  76125. /**
  76126. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  76127. * @param scene scene in which to add meshes
  76128. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  76129. */
  76130. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  76131. var _this = this;
  76132. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  76133. _this._defaultModel = newMeshes[1];
  76134. _this.attachToMesh(_this._defaultModel);
  76135. if (meshLoaded) {
  76136. meshLoaded(_this._defaultModel);
  76137. }
  76138. });
  76139. };
  76140. /**
  76141. * Called once for each button that changed state since the last frame
  76142. * @param buttonIdx Which button index changed
  76143. * @param state New state of the button
  76144. * @param changes Which properties on the state changed since last frame
  76145. */
  76146. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  76147. console.log("Button id: " + buttonIdx + "state: ");
  76148. console.dir(state);
  76149. };
  76150. /**
  76151. * Base Url for the controller model.
  76152. */
  76153. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  76154. /**
  76155. * File name for the controller model.
  76156. */
  76157. GenericController.MODEL_FILENAME = 'generic.babylon';
  76158. return GenericController;
  76159. }(BABYLON.WebVRController));
  76160. BABYLON.GenericController = GenericController;
  76161. })(BABYLON || (BABYLON = {}));
  76162. //# sourceMappingURL=babylon.genericController.js.map
  76163. var BABYLON;
  76164. (function (BABYLON) {
  76165. /**
  76166. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  76167. */
  76168. var LoadedMeshInfo = /** @class */ (function () {
  76169. function LoadedMeshInfo() {
  76170. /**
  76171. * Map of the button meshes contained in the controller
  76172. */
  76173. this.buttonMeshes = {};
  76174. /**
  76175. * Map of the axis meshes contained in the controller
  76176. */
  76177. this.axisMeshes = {};
  76178. }
  76179. return LoadedMeshInfo;
  76180. }());
  76181. /**
  76182. * Defines the WindowsMotionController object that the state of the windows motion controller
  76183. */
  76184. var WindowsMotionController = /** @class */ (function (_super) {
  76185. __extends(WindowsMotionController, _super);
  76186. /**
  76187. * Creates a new WindowsMotionController from a gamepad
  76188. * @param vrGamepad the gamepad that the controller should be created from
  76189. */
  76190. function WindowsMotionController(vrGamepad) {
  76191. var _this = _super.call(this, vrGamepad) || this;
  76192. _this._mapping = {
  76193. // Semantic button names
  76194. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  76195. // A mapping of the button name to glTF model node name
  76196. // that should be transformed by button value.
  76197. buttonMeshNames: {
  76198. 'trigger': 'SELECT',
  76199. 'menu': 'MENU',
  76200. 'grip': 'GRASP',
  76201. 'thumbstick': 'THUMBSTICK_PRESS',
  76202. 'trackpad': 'TOUCHPAD_PRESS'
  76203. },
  76204. // This mapping is used to translate from the Motion Controller to Babylon semantics
  76205. buttonObservableNames: {
  76206. 'trigger': 'onTriggerStateChangedObservable',
  76207. 'menu': 'onSecondaryButtonStateChangedObservable',
  76208. 'grip': 'onMainButtonStateChangedObservable',
  76209. 'thumbstick': 'onPadStateChangedObservable',
  76210. 'trackpad': 'onTrackpadChangedObservable'
  76211. },
  76212. // A mapping of the axis name to glTF model node name
  76213. // that should be transformed by axis value.
  76214. // This array mirrors the browserGamepad.axes array, such that
  76215. // the mesh corresponding to axis 0 is in this array index 0.
  76216. axisMeshNames: [
  76217. 'THUMBSTICK_X',
  76218. 'THUMBSTICK_Y',
  76219. 'TOUCHPAD_TOUCH_X',
  76220. 'TOUCHPAD_TOUCH_Y'
  76221. ],
  76222. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  76223. };
  76224. /**
  76225. * Fired when the trackpad on this controller is clicked
  76226. */
  76227. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  76228. /**
  76229. * Fired when the trackpad on this controller is modified
  76230. */
  76231. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  76232. /**
  76233. * The current x and y values of this controller's trackpad
  76234. */
  76235. _this.trackpad = { x: 0, y: 0 };
  76236. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  76237. _this._loadedMeshInfo = null;
  76238. return _this;
  76239. }
  76240. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  76241. /**
  76242. * Fired when the trigger on this controller is modified
  76243. */
  76244. get: function () {
  76245. return this.onTriggerStateChangedObservable;
  76246. },
  76247. enumerable: true,
  76248. configurable: true
  76249. });
  76250. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  76251. /**
  76252. * Fired when the menu button on this controller is modified
  76253. */
  76254. get: function () {
  76255. return this.onSecondaryButtonStateChangedObservable;
  76256. },
  76257. enumerable: true,
  76258. configurable: true
  76259. });
  76260. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  76261. /**
  76262. * Fired when the grip button on this controller is modified
  76263. */
  76264. get: function () {
  76265. return this.onMainButtonStateChangedObservable;
  76266. },
  76267. enumerable: true,
  76268. configurable: true
  76269. });
  76270. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  76271. /**
  76272. * Fired when the thumbstick button on this controller is modified
  76273. */
  76274. get: function () {
  76275. return this.onPadStateChangedObservable;
  76276. },
  76277. enumerable: true,
  76278. configurable: true
  76279. });
  76280. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  76281. /**
  76282. * Fired when the touchpad button on this controller is modified
  76283. */
  76284. get: function () {
  76285. return this.onTrackpadChangedObservable;
  76286. },
  76287. enumerable: true,
  76288. configurable: true
  76289. });
  76290. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  76291. /**
  76292. * Fired when the touchpad values on this controller are modified
  76293. */
  76294. get: function () {
  76295. return this.onTrackpadValuesChangedObservable;
  76296. },
  76297. enumerable: true,
  76298. configurable: true
  76299. });
  76300. WindowsMotionController.prototype._updateTrackpad = function () {
  76301. if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {
  76302. this.trackpad.x = this.browserGamepad["axes"][2];
  76303. this.trackpad.y = this.browserGamepad["axes"][3];
  76304. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  76305. }
  76306. };
  76307. /**
  76308. * Called once per frame by the engine.
  76309. */
  76310. WindowsMotionController.prototype.update = function () {
  76311. _super.prototype.update.call(this);
  76312. if (this.browserGamepad.axes) {
  76313. this._updateTrackpad();
  76314. // Only need to animate axes if there is a loaded mesh
  76315. if (this._loadedMeshInfo) {
  76316. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  76317. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  76318. }
  76319. }
  76320. }
  76321. };
  76322. /**
  76323. * Called once for each button that changed state since the last frame
  76324. * @param buttonIdx Which button index changed
  76325. * @param state New state of the button
  76326. * @param changes Which properties on the state changed since last frame
  76327. */
  76328. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  76329. var buttonName = this._mapping.buttons[buttonIdx];
  76330. if (!buttonName) {
  76331. return;
  76332. }
  76333. // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames
  76334. this._updateTrackpad();
  76335. // Only emit events for buttons that we know how to map from index to name
  76336. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  76337. if (observable) {
  76338. observable.notifyObservers(state);
  76339. }
  76340. this._lerpButtonTransform(buttonName, state.value);
  76341. };
  76342. /**
  76343. * Moves the buttons on the controller mesh based on their current state
  76344. * @param buttonName the name of the button to move
  76345. * @param buttonValue the value of the button which determines the buttons new position
  76346. */
  76347. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  76348. // If there is no loaded mesh, there is nothing to transform.
  76349. if (!this._loadedMeshInfo) {
  76350. return;
  76351. }
  76352. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  76353. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  76354. return;
  76355. }
  76356. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  76357. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  76358. };
  76359. /**
  76360. * Moves the axis on the controller mesh based on its current state
  76361. * @param axis the index of the axis
  76362. * @param axisValue the value of the axis which determines the meshes new position
  76363. * @hidden
  76364. */
  76365. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  76366. if (!this._loadedMeshInfo) {
  76367. return;
  76368. }
  76369. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  76370. if (!meshInfo) {
  76371. return;
  76372. }
  76373. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  76374. return;
  76375. }
  76376. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  76377. var lerpValue = axisValue * 0.5 + 0.5;
  76378. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  76379. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  76380. };
  76381. /**
  76382. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  76383. * @param scene scene in which to add meshes
  76384. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  76385. */
  76386. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  76387. var _this = this;
  76388. if (forceDefault === void 0) { forceDefault = false; }
  76389. var path;
  76390. var filename;
  76391. // Checking if GLB loader is present
  76392. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  76393. // Determine the device specific folder based on the ID suffix
  76394. var device = 'default';
  76395. if (this.id && !forceDefault) {
  76396. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  76397. device = ((match && match[0]) || device);
  76398. }
  76399. // Hand
  76400. if (this.hand === 'left') {
  76401. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  76402. }
  76403. else { // Right is the default if no hand is specified
  76404. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  76405. }
  76406. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  76407. }
  76408. else {
  76409. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  76410. path = BABYLON.GenericController.MODEL_BASE_URL;
  76411. filename = BABYLON.GenericController.MODEL_FILENAME;
  76412. }
  76413. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  76414. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  76415. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  76416. if (!_this._loadedMeshInfo) {
  76417. return;
  76418. }
  76419. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  76420. _this.attachToMesh(_this._defaultModel);
  76421. if (meshLoaded) {
  76422. meshLoaded(_this._defaultModel);
  76423. }
  76424. }, null, function (scene, message) {
  76425. BABYLON.Tools.Log(message);
  76426. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  76427. if (!forceDefault) {
  76428. _this.initControllerMesh(scene, meshLoaded, true);
  76429. }
  76430. });
  76431. };
  76432. /**
  76433. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  76434. * can be transformed by button presses and axes values, based on this._mapping.
  76435. *
  76436. * @param scene scene in which the meshes exist
  76437. * @param meshes list of meshes that make up the controller model to process
  76438. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  76439. */
  76440. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  76441. var loadedMeshInfo = null;
  76442. // Create a new mesh to contain the glTF hierarchy
  76443. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  76444. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  76445. var childMesh = null;
  76446. for (var i = 0; i < meshes.length; i++) {
  76447. var mesh = meshes[i];
  76448. if (!mesh.parent) {
  76449. // Exclude controller meshes from picking results
  76450. mesh.isPickable = false;
  76451. // Handle root node, attach to the new parentMesh
  76452. childMesh = mesh;
  76453. break;
  76454. }
  76455. }
  76456. if (childMesh) {
  76457. childMesh.setParent(parentMesh);
  76458. // Create our mesh info. Note that this method will always return non-null.
  76459. loadedMeshInfo = this.createMeshInfo(parentMesh);
  76460. }
  76461. else {
  76462. BABYLON.Tools.Warn('Could not find root node in model file.');
  76463. }
  76464. return loadedMeshInfo;
  76465. };
  76466. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  76467. var loadedMeshInfo = new LoadedMeshInfo();
  76468. var i;
  76469. loadedMeshInfo.rootNode = rootNode;
  76470. // Reset the caches
  76471. loadedMeshInfo.buttonMeshes = {};
  76472. loadedMeshInfo.axisMeshes = {};
  76473. // Button Meshes
  76474. for (i = 0; i < this._mapping.buttons.length; i++) {
  76475. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  76476. if (!buttonMeshName) {
  76477. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  76478. continue;
  76479. }
  76480. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  76481. if (!buttonMesh) {
  76482. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  76483. continue;
  76484. }
  76485. var buttonMeshInfo = {
  76486. index: i,
  76487. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  76488. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  76489. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  76490. };
  76491. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  76492. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  76493. }
  76494. else {
  76495. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  76496. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  76497. '(VALUE: ' + !!buttonMeshInfo.value +
  76498. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  76499. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  76500. ')');
  76501. }
  76502. }
  76503. // Axis Meshes
  76504. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  76505. var axisMeshName = this._mapping.axisMeshNames[i];
  76506. if (!axisMeshName) {
  76507. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  76508. continue;
  76509. }
  76510. var axisMesh = getChildByName(rootNode, axisMeshName);
  76511. if (!axisMesh) {
  76512. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  76513. continue;
  76514. }
  76515. var axisMeshInfo = {
  76516. index: i,
  76517. value: getImmediateChildByName(axisMesh, 'VALUE'),
  76518. min: getImmediateChildByName(axisMesh, 'MIN'),
  76519. max: getImmediateChildByName(axisMesh, 'MAX')
  76520. };
  76521. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  76522. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  76523. }
  76524. else {
  76525. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  76526. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  76527. '(VALUE: ' + !!axisMeshInfo.value +
  76528. ', MIN: ' + !!axisMeshInfo.min +
  76529. ', MAX:' + !!axisMeshInfo.max +
  76530. ')');
  76531. }
  76532. }
  76533. // Pointing Ray
  76534. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  76535. if (!loadedMeshInfo.pointingPoseNode) {
  76536. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  76537. }
  76538. else {
  76539. this._pointingPoseNode = loadedMeshInfo.pointingPoseNode;
  76540. }
  76541. return loadedMeshInfo;
  76542. // Look through all children recursively. This will return null if no mesh exists with the given name.
  76543. function getChildByName(node, name) {
  76544. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  76545. }
  76546. // Look through only immediate children. This will return null if no mesh exists with the given name.
  76547. function getImmediateChildByName(node, name) {
  76548. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  76549. }
  76550. };
  76551. /**
  76552. * Gets the ray of the controller in the direction the controller is pointing
  76553. * @param length the length the resulting ray should be
  76554. * @returns a ray in the direction the controller is pointing
  76555. */
  76556. WindowsMotionController.prototype.getForwardRay = function (length) {
  76557. if (length === void 0) { length = 100; }
  76558. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  76559. return _super.prototype.getForwardRay.call(this, length);
  76560. }
  76561. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  76562. var origin = m.getTranslation();
  76563. var forward = new BABYLON.Vector3(0, 0, -1);
  76564. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  76565. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  76566. return new BABYLON.Ray(origin, direction, length);
  76567. };
  76568. /**
  76569. * Disposes of the controller
  76570. */
  76571. WindowsMotionController.prototype.dispose = function () {
  76572. _super.prototype.dispose.call(this);
  76573. this.onTrackpadChangedObservable.clear();
  76574. };
  76575. /**
  76576. * The base url used to load the left and right controller models
  76577. */
  76578. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  76579. /**
  76580. * The name of the left controller model file
  76581. */
  76582. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  76583. /**
  76584. * The name of the right controller model file
  76585. */
  76586. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  76587. /**
  76588. * The controller name prefix for this controller type
  76589. */
  76590. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  76591. /**
  76592. * The controller id pattern for this controller type
  76593. */
  76594. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  76595. return WindowsMotionController;
  76596. }(BABYLON.WebVRController));
  76597. BABYLON.WindowsMotionController = WindowsMotionController;
  76598. })(BABYLON || (BABYLON = {}));
  76599. //# sourceMappingURL=babylon.windowsMotionController.js.map
  76600. var BABYLON;
  76601. (function (BABYLON) {
  76602. /**
  76603. * Gear VR Controller
  76604. */
  76605. var GearVRController = /** @class */ (function (_super) {
  76606. __extends(GearVRController, _super);
  76607. /**
  76608. * Creates a new GearVRController from a gamepad
  76609. * @param vrGamepad the gamepad that the controller should be created from
  76610. */
  76611. function GearVRController(vrGamepad) {
  76612. var _this = _super.call(this, vrGamepad) || this;
  76613. _this._maxRotationDistFromHeadset = Math.PI / 5;
  76614. _this._draggedRoomRotation = 0;
  76615. _this._tmpVector = new BABYLON.Vector3();
  76616. _this._buttonIndexToObservableNameMap = [
  76617. 'onTrackpadChangedObservable',
  76618. 'onTriggerStateChangedObservable' // Trigger
  76619. ];
  76620. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  76621. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  76622. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.25);
  76623. return _this;
  76624. }
  76625. /**
  76626. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  76627. * @param poseData raw pose fromthe device
  76628. */
  76629. GearVRController.prototype.updateFromDevice = function (poseData) {
  76630. _super.prototype.updateFromDevice.call(this, poseData);
  76631. if (BABYLON.Engine.LastCreatedScene && BABYLON.Engine.LastCreatedScene.activeCamera) {
  76632. if (BABYLON.Engine.LastCreatedScene.activeCamera.deviceRotationQuaternion) {
  76633. var camera = BABYLON.Engine.LastCreatedScene.activeCamera;
  76634. camera._deviceRoomRotationQuaternion.toEulerAnglesToRef(this._tmpVector);
  76635. // Find the radian distance away that the headset is from the controllers rotation
  76636. var distanceAway = Math.atan2(Math.sin(this._tmpVector.y - this._draggedRoomRotation), Math.cos(this._tmpVector.y - this._draggedRoomRotation));
  76637. if (Math.abs(distanceAway) > this._maxRotationDistFromHeadset) {
  76638. // Only rotate enouph to be within the _maxRotationDistFromHeadset
  76639. var rotationAmount = distanceAway - (distanceAway < 0 ? -this._maxRotationDistFromHeadset : this._maxRotationDistFromHeadset);
  76640. this._draggedRoomRotation += rotationAmount;
  76641. // Rotate controller around headset
  76642. var sin = Math.sin(-rotationAmount);
  76643. var cos = Math.cos(-rotationAmount);
  76644. this._calculatedPosition.x = this._calculatedPosition.x * cos - this._calculatedPosition.z * sin;
  76645. this._calculatedPosition.z = this._calculatedPosition.x * sin + this._calculatedPosition.z * cos;
  76646. }
  76647. }
  76648. }
  76649. };
  76650. /**
  76651. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  76652. * @param scene scene in which to add meshes
  76653. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  76654. */
  76655. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  76656. var _this = this;
  76657. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  76658. // Offset the controller so it will rotate around the users wrist
  76659. var mesh = new BABYLON.Mesh("", scene);
  76660. newMeshes[1].parent = mesh;
  76661. newMeshes[1].position.z = -0.15;
  76662. _this._defaultModel = mesh;
  76663. _this.attachToMesh(_this._defaultModel);
  76664. if (meshLoaded) {
  76665. meshLoaded(_this._defaultModel);
  76666. }
  76667. });
  76668. };
  76669. /**
  76670. * Called once for each button that changed state since the last frame
  76671. * @param buttonIdx Which button index changed
  76672. * @param state New state of the button
  76673. * @param changes Which properties on the state changed since last frame
  76674. */
  76675. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  76676. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  76677. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  76678. // Only emit events for buttons that we know how to map from index to observable
  76679. var observable = this[observableName];
  76680. if (observable) {
  76681. observable.notifyObservers(state);
  76682. }
  76683. }
  76684. };
  76685. /**
  76686. * Base Url for the controller model.
  76687. */
  76688. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  76689. /**
  76690. * File name for the controller model.
  76691. */
  76692. GearVRController.MODEL_FILENAME = 'generic.babylon';
  76693. /**
  76694. * Gamepad Id prefix used to identify this controller.
  76695. */
  76696. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  76697. return GearVRController;
  76698. }(BABYLON.WebVRController));
  76699. BABYLON.GearVRController = GearVRController;
  76700. })(BABYLON || (BABYLON = {}));
  76701. //# sourceMappingURL=babylon.gearVRController.js.map
  76702. var BABYLON;
  76703. (function (BABYLON) {
  76704. /**
  76705. * Google Daydream controller
  76706. */
  76707. var DaydreamController = /** @class */ (function (_super) {
  76708. __extends(DaydreamController, _super);
  76709. /**
  76710. * Creates a new DaydreamController from a gamepad
  76711. * @param vrGamepad the gamepad that the controller should be created from
  76712. */
  76713. function DaydreamController(vrGamepad) {
  76714. var _this = _super.call(this, vrGamepad) || this;
  76715. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  76716. return _this;
  76717. }
  76718. /**
  76719. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  76720. * @param scene scene in which to add meshes
  76721. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  76722. */
  76723. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  76724. var _this = this;
  76725. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  76726. _this._defaultModel = newMeshes[1];
  76727. _this.attachToMesh(_this._defaultModel);
  76728. if (meshLoaded) {
  76729. meshLoaded(_this._defaultModel);
  76730. }
  76731. });
  76732. };
  76733. /**
  76734. * Called once for each button that changed state since the last frame
  76735. * @param buttonIdx Which button index changed
  76736. * @param state New state of the button
  76737. * @param changes Which properties on the state changed since last frame
  76738. */
  76739. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  76740. // Daydream controller only has 1 GamepadButton (on the trackpad).
  76741. if (buttonIdx === 0) {
  76742. var observable = this.onTriggerStateChangedObservable;
  76743. if (observable) {
  76744. observable.notifyObservers(state);
  76745. }
  76746. }
  76747. else {
  76748. // If the app or home buttons are ever made available
  76749. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  76750. }
  76751. };
  76752. /**
  76753. * Base Url for the controller model.
  76754. */
  76755. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  76756. /**
  76757. * File name for the controller model.
  76758. */
  76759. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  76760. /**
  76761. * Gamepad Id prefix used to identify Daydream Controller.
  76762. */
  76763. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  76764. return DaydreamController;
  76765. }(BABYLON.WebVRController));
  76766. BABYLON.DaydreamController = DaydreamController;
  76767. })(BABYLON || (BABYLON = {}));
  76768. //# sourceMappingURL=babylon.daydreamController.js.map
  76769. var BABYLON;
  76770. (function (BABYLON) {
  76771. Object.defineProperty(BABYLON.Scene.prototype, "gamepadManager", {
  76772. get: function () {
  76773. if (!this._gamepadManager) {
  76774. this._gamepadManager = new BABYLON.GamepadManager(this);
  76775. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_GAMEPAD);
  76776. if (!component) {
  76777. component = new GamepadSystemSceneComponent(this);
  76778. this._addComponent(component);
  76779. }
  76780. }
  76781. return this._gamepadManager;
  76782. },
  76783. enumerable: true,
  76784. configurable: true
  76785. });
  76786. BABYLON.FreeCameraInputsManager.prototype.addGamepad = function () {
  76787. this.add(new BABYLON.FreeCameraGamepadInput());
  76788. return this;
  76789. };
  76790. BABYLON.ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  76791. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  76792. return this;
  76793. };
  76794. /**
  76795. * Defines the gamepad scene component responsible to manage gamepads in a given scene
  76796. */
  76797. var GamepadSystemSceneComponent = /** @class */ (function () {
  76798. /**
  76799. * Creates a new instance of the component for the given scene
  76800. * @param scene Defines the scene to register the component in
  76801. */
  76802. function GamepadSystemSceneComponent(scene) {
  76803. /**
  76804. * The component name helpfull to identify the component in the list of scene components.
  76805. */
  76806. this.name = BABYLON.SceneComponentConstants.NAME_GAMEPAD;
  76807. this.scene = scene;
  76808. }
  76809. /**
  76810. * Registers the component in a given scene
  76811. */
  76812. GamepadSystemSceneComponent.prototype.register = function () {
  76813. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD, this, this._beforeCameraUpdate);
  76814. };
  76815. /**
  76816. * Rebuilds the elements related to this component in case of
  76817. * context lost for instance.
  76818. */
  76819. GamepadSystemSceneComponent.prototype.rebuild = function () {
  76820. // Nothing to do for gamepads
  76821. };
  76822. /**
  76823. * Disposes the component and the associated ressources
  76824. */
  76825. GamepadSystemSceneComponent.prototype.dispose = function () {
  76826. var gamepadManager = this.scene._gamepadManager;
  76827. if (gamepadManager) {
  76828. gamepadManager.dispose();
  76829. this.scene._gamepadManager = null;
  76830. }
  76831. };
  76832. GamepadSystemSceneComponent.prototype._beforeCameraUpdate = function () {
  76833. var gamepadManager = this.scene._gamepadManager;
  76834. if (gamepadManager && gamepadManager._isMonitoring) {
  76835. gamepadManager._checkGamepadsStatus();
  76836. }
  76837. };
  76838. return GamepadSystemSceneComponent;
  76839. }());
  76840. BABYLON.GamepadSystemSceneComponent = GamepadSystemSceneComponent;
  76841. })(BABYLON || (BABYLON = {}));
  76842. //# sourceMappingURL=babylon.gamepadSceneComponent.js.map
  76843. var BABYLON;
  76844. (function (BABYLON) {
  76845. BABYLON.Node.AddNodeConstructor("FollowCamera", function (name, scene) {
  76846. return function () { return new FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  76847. });
  76848. BABYLON.Node.AddNodeConstructor("ArcFollowCamera", function (name, scene) {
  76849. return function () { return new ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  76850. });
  76851. var FollowCamera = /** @class */ (function (_super) {
  76852. __extends(FollowCamera, _super);
  76853. function FollowCamera(name, position, scene, lockedTarget) {
  76854. if (lockedTarget === void 0) { lockedTarget = null; }
  76855. var _this = _super.call(this, name, position, scene) || this;
  76856. _this.radius = 12;
  76857. _this.rotationOffset = 0;
  76858. _this.heightOffset = 4;
  76859. _this.cameraAcceleration = 0.05;
  76860. _this.maxCameraSpeed = 20;
  76861. _this.lockedTarget = lockedTarget;
  76862. return _this;
  76863. }
  76864. FollowCamera.prototype.getRadians = function (degrees) {
  76865. return degrees * Math.PI / 180;
  76866. };
  76867. FollowCamera.prototype.follow = function (cameraTarget) {
  76868. if (!cameraTarget)
  76869. return;
  76870. var yRotation;
  76871. if (cameraTarget.rotationQuaternion) {
  76872. var rotMatrix = new BABYLON.Matrix();
  76873. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  76874. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  76875. }
  76876. else {
  76877. yRotation = cameraTarget.rotation.y;
  76878. }
  76879. var radians = this.getRadians(this.rotationOffset) + yRotation;
  76880. var targetPosition = cameraTarget.getAbsolutePosition();
  76881. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  76882. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  76883. var dx = targetX - this.position.x;
  76884. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  76885. var dz = (targetZ) - this.position.z;
  76886. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  76887. var vy = dy * this.cameraAcceleration;
  76888. var vz = dz * this.cameraAcceleration * 2;
  76889. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  76890. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  76891. }
  76892. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  76893. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  76894. }
  76895. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  76896. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  76897. }
  76898. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  76899. this.setTarget(targetPosition);
  76900. };
  76901. /** @hidden */
  76902. FollowCamera.prototype._checkInputs = function () {
  76903. _super.prototype._checkInputs.call(this);
  76904. if (this.lockedTarget) {
  76905. this.follow(this.lockedTarget);
  76906. }
  76907. };
  76908. FollowCamera.prototype.getClassName = function () {
  76909. return "FollowCamera";
  76910. };
  76911. __decorate([
  76912. BABYLON.serialize()
  76913. ], FollowCamera.prototype, "radius", void 0);
  76914. __decorate([
  76915. BABYLON.serialize()
  76916. ], FollowCamera.prototype, "rotationOffset", void 0);
  76917. __decorate([
  76918. BABYLON.serialize()
  76919. ], FollowCamera.prototype, "heightOffset", void 0);
  76920. __decorate([
  76921. BABYLON.serialize()
  76922. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  76923. __decorate([
  76924. BABYLON.serialize()
  76925. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  76926. __decorate([
  76927. BABYLON.serializeAsMeshReference("lockedTargetId")
  76928. ], FollowCamera.prototype, "lockedTarget", void 0);
  76929. return FollowCamera;
  76930. }(BABYLON.TargetCamera));
  76931. BABYLON.FollowCamera = FollowCamera;
  76932. var ArcFollowCamera = /** @class */ (function (_super) {
  76933. __extends(ArcFollowCamera, _super);
  76934. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  76935. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  76936. _this.alpha = alpha;
  76937. _this.beta = beta;
  76938. _this.radius = radius;
  76939. _this.target = target;
  76940. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  76941. _this.follow();
  76942. return _this;
  76943. }
  76944. ArcFollowCamera.prototype.follow = function () {
  76945. if (!this.target) {
  76946. return;
  76947. }
  76948. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  76949. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  76950. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  76951. var targetPosition = this.target.getAbsolutePosition();
  76952. this.position = targetPosition.add(this._cartesianCoordinates);
  76953. this.setTarget(targetPosition);
  76954. };
  76955. /** @hidden */
  76956. ArcFollowCamera.prototype._checkInputs = function () {
  76957. _super.prototype._checkInputs.call(this);
  76958. this.follow();
  76959. };
  76960. ArcFollowCamera.prototype.getClassName = function () {
  76961. return "ArcFollowCamera";
  76962. };
  76963. return ArcFollowCamera;
  76964. }(BABYLON.TargetCamera));
  76965. BABYLON.ArcFollowCamera = ArcFollowCamera;
  76966. })(BABYLON || (BABYLON = {}));
  76967. //# sourceMappingURL=babylon.followCamera.js.map
  76968. var BABYLON;
  76969. (function (BABYLON) {
  76970. // We're mainly based on the logic defined into the FreeCamera code
  76971. var UniversalCamera = /** @class */ (function (_super) {
  76972. __extends(UniversalCamera, _super);
  76973. //-- end properties for backward compatibility for inputs
  76974. function UniversalCamera(name, position, scene) {
  76975. var _this = _super.call(this, name, position, scene) || this;
  76976. _this.inputs.addGamepad();
  76977. return _this;
  76978. }
  76979. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  76980. //-- Begin properties for backward compatibility for inputs
  76981. get: function () {
  76982. var gamepad = this.inputs.attached["gamepad"];
  76983. if (gamepad)
  76984. return gamepad.gamepadAngularSensibility;
  76985. return 0;
  76986. },
  76987. set: function (value) {
  76988. var gamepad = this.inputs.attached["gamepad"];
  76989. if (gamepad)
  76990. gamepad.gamepadAngularSensibility = value;
  76991. },
  76992. enumerable: true,
  76993. configurable: true
  76994. });
  76995. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  76996. get: function () {
  76997. var gamepad = this.inputs.attached["gamepad"];
  76998. if (gamepad)
  76999. return gamepad.gamepadMoveSensibility;
  77000. return 0;
  77001. },
  77002. set: function (value) {
  77003. var gamepad = this.inputs.attached["gamepad"];
  77004. if (gamepad)
  77005. gamepad.gamepadMoveSensibility = value;
  77006. },
  77007. enumerable: true,
  77008. configurable: true
  77009. });
  77010. UniversalCamera.prototype.getClassName = function () {
  77011. return "UniversalCamera";
  77012. };
  77013. return UniversalCamera;
  77014. }(BABYLON.TouchCamera));
  77015. BABYLON.UniversalCamera = UniversalCamera;
  77016. })(BABYLON || (BABYLON = {}));
  77017. //# sourceMappingURL=babylon.universalCamera.js.map
  77018. var BABYLON;
  77019. (function (BABYLON) {
  77020. BABYLON.Node.AddNodeConstructor("GamepadCamera", function (name, scene) {
  77021. return function () { return new GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  77022. });
  77023. // We're mainly based on the logic defined into the FreeCamera code
  77024. var GamepadCamera = /** @class */ (function (_super) {
  77025. __extends(GamepadCamera, _super);
  77026. //-- end properties for backward compatibility for inputs
  77027. function GamepadCamera(name, position, scene) {
  77028. return _super.call(this, name, position, scene) || this;
  77029. }
  77030. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  77031. //-- Begin properties for backward compatibility for inputs
  77032. get: function () {
  77033. var gamepad = this.inputs.attached["gamepad"];
  77034. if (gamepad)
  77035. return gamepad.gamepadAngularSensibility;
  77036. return 0;
  77037. },
  77038. set: function (value) {
  77039. var gamepad = this.inputs.attached["gamepad"];
  77040. if (gamepad)
  77041. gamepad.gamepadAngularSensibility = value;
  77042. },
  77043. enumerable: true,
  77044. configurable: true
  77045. });
  77046. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  77047. get: function () {
  77048. var gamepad = this.inputs.attached["gamepad"];
  77049. if (gamepad)
  77050. return gamepad.gamepadMoveSensibility;
  77051. return 0;
  77052. },
  77053. set: function (value) {
  77054. var gamepad = this.inputs.attached["gamepad"];
  77055. if (gamepad)
  77056. gamepad.gamepadMoveSensibility = value;
  77057. },
  77058. enumerable: true,
  77059. configurable: true
  77060. });
  77061. GamepadCamera.prototype.getClassName = function () {
  77062. return "GamepadCamera";
  77063. };
  77064. return GamepadCamera;
  77065. }(BABYLON.UniversalCamera));
  77066. BABYLON.GamepadCamera = GamepadCamera;
  77067. })(BABYLON || (BABYLON = {}));
  77068. //# sourceMappingURL=babylon.gamepadCamera.js.map
  77069. var BABYLON;
  77070. (function (BABYLON) {
  77071. var PostProcessRenderPipelineManager = /** @class */ (function () {
  77072. function PostProcessRenderPipelineManager() {
  77073. this._renderPipelines = {};
  77074. }
  77075. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  77076. this._renderPipelines[renderPipeline._name] = renderPipeline;
  77077. };
  77078. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  77079. if (unique === void 0) { unique = false; }
  77080. var renderPipeline = this._renderPipelines[renderPipelineName];
  77081. if (!renderPipeline) {
  77082. return;
  77083. }
  77084. renderPipeline._attachCameras(cameras, unique);
  77085. };
  77086. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  77087. var renderPipeline = this._renderPipelines[renderPipelineName];
  77088. if (!renderPipeline) {
  77089. return;
  77090. }
  77091. renderPipeline._detachCameras(cameras);
  77092. };
  77093. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  77094. var renderPipeline = this._renderPipelines[renderPipelineName];
  77095. if (!renderPipeline) {
  77096. return;
  77097. }
  77098. renderPipeline._enableEffect(renderEffectName, cameras);
  77099. };
  77100. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  77101. var renderPipeline = this._renderPipelines[renderPipelineName];
  77102. if (!renderPipeline) {
  77103. return;
  77104. }
  77105. renderPipeline._disableEffect(renderEffectName, cameras);
  77106. };
  77107. PostProcessRenderPipelineManager.prototype.update = function () {
  77108. for (var renderPipelineName in this._renderPipelines) {
  77109. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  77110. var pipeline = this._renderPipelines[renderPipelineName];
  77111. if (!pipeline.isSupported) {
  77112. pipeline.dispose();
  77113. delete this._renderPipelines[renderPipelineName];
  77114. }
  77115. else {
  77116. pipeline._update();
  77117. }
  77118. }
  77119. }
  77120. };
  77121. /** @hidden */
  77122. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  77123. for (var renderPipelineName in this._renderPipelines) {
  77124. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  77125. var pipeline = this._renderPipelines[renderPipelineName];
  77126. pipeline._rebuild();
  77127. }
  77128. }
  77129. };
  77130. PostProcessRenderPipelineManager.prototype.dispose = function () {
  77131. for (var renderPipelineName in this._renderPipelines) {
  77132. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  77133. var pipeline = this._renderPipelines[renderPipelineName];
  77134. pipeline.dispose();
  77135. }
  77136. }
  77137. };
  77138. return PostProcessRenderPipelineManager;
  77139. }());
  77140. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  77141. })(BABYLON || (BABYLON = {}));
  77142. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  77143. var BABYLON;
  77144. (function (BABYLON) {
  77145. Object.defineProperty(BABYLON.Scene.prototype, "postProcessRenderPipelineManager", {
  77146. get: function () {
  77147. if (!this._postProcessRenderPipelineManager) {
  77148. // Register the G Buffer component to the scene.
  77149. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER);
  77150. if (!component) {
  77151. component = new PostProcessRenderPipelineManagerSceneComponent(this);
  77152. this._addComponent(component);
  77153. }
  77154. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  77155. }
  77156. return this._postProcessRenderPipelineManager;
  77157. },
  77158. enumerable: true,
  77159. configurable: true
  77160. });
  77161. /**
  77162. * Defines the Render Pipeline scene component responsible to rendering pipelines
  77163. */
  77164. var PostProcessRenderPipelineManagerSceneComponent = /** @class */ (function () {
  77165. /**
  77166. * Creates a new instance of the component for the given scene
  77167. * @param scene Defines the scene to register the component in
  77168. */
  77169. function PostProcessRenderPipelineManagerSceneComponent(scene) {
  77170. /**
  77171. * The component name helpfull to identify the component in the list of scene components.
  77172. */
  77173. this.name = BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER;
  77174. this.scene = scene;
  77175. }
  77176. /**
  77177. * Registers the component in a given scene
  77178. */
  77179. PostProcessRenderPipelineManagerSceneComponent.prototype.register = function () {
  77180. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER, this, this._gatherRenderTargets);
  77181. };
  77182. /**
  77183. * Rebuilds the elements related to this component in case of
  77184. * context lost for instance.
  77185. */
  77186. PostProcessRenderPipelineManagerSceneComponent.prototype.rebuild = function () {
  77187. if (this.scene._postProcessRenderPipelineManager) {
  77188. this.scene._postProcessRenderPipelineManager._rebuild();
  77189. }
  77190. };
  77191. /**
  77192. * Disposes the component and the associated ressources
  77193. */
  77194. PostProcessRenderPipelineManagerSceneComponent.prototype.dispose = function () {
  77195. if (this.scene._postProcessRenderPipelineManager) {
  77196. this.scene._postProcessRenderPipelineManager.dispose();
  77197. }
  77198. };
  77199. PostProcessRenderPipelineManagerSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  77200. if (this.scene._postProcessRenderPipelineManager) {
  77201. this.scene._postProcessRenderPipelineManager.update();
  77202. }
  77203. };
  77204. return PostProcessRenderPipelineManagerSceneComponent;
  77205. }());
  77206. BABYLON.PostProcessRenderPipelineManagerSceneComponent = PostProcessRenderPipelineManagerSceneComponent;
  77207. })(BABYLON || (BABYLON = {}));
  77208. //# sourceMappingURL=babylon.postProcessRenderPipelineManagerSceneComponent.js.map
  77209. var BABYLON;
  77210. (function (BABYLON) {
  77211. /**
  77212. * This represents a set of one or more post processes in Babylon.
  77213. * A post process can be used to apply a shader to a texture after it is rendered.
  77214. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  77215. */
  77216. var PostProcessRenderEffect = /** @class */ (function () {
  77217. /**
  77218. * Instantiates a post process render effect.
  77219. * A post process can be used to apply a shader to a texture after it is rendered.
  77220. * @param engine The engine the effect is tied to
  77221. * @param name The name of the effect
  77222. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  77223. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  77224. */
  77225. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  77226. this._name = name;
  77227. this._singleInstance = singleInstance || true;
  77228. this._getPostProcesses = getPostProcesses;
  77229. this._cameras = {};
  77230. this._indicesForCamera = {};
  77231. this._postProcesses = {};
  77232. }
  77233. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  77234. /**
  77235. * Checks if all the post processes in the effect are supported.
  77236. */
  77237. get: function () {
  77238. for (var index in this._postProcesses) {
  77239. if (this._postProcesses.hasOwnProperty(index)) {
  77240. var pps = this._postProcesses[index];
  77241. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  77242. if (!pps[ppIndex].isSupported) {
  77243. return false;
  77244. }
  77245. }
  77246. }
  77247. }
  77248. return true;
  77249. },
  77250. enumerable: true,
  77251. configurable: true
  77252. });
  77253. /**
  77254. * Updates the current state of the effect
  77255. * @hidden
  77256. */
  77257. PostProcessRenderEffect.prototype._update = function () {
  77258. };
  77259. /**
  77260. * Attaches the effect on cameras
  77261. * @param cameras The camera to attach to.
  77262. * @hidden
  77263. */
  77264. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  77265. var _this = this;
  77266. var cameraKey;
  77267. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  77268. if (!cams) {
  77269. return;
  77270. }
  77271. for (var i = 0; i < cams.length; i++) {
  77272. var camera = cams[i];
  77273. var cameraName = camera.name;
  77274. if (this._singleInstance) {
  77275. cameraKey = 0;
  77276. }
  77277. else {
  77278. cameraKey = cameraName;
  77279. }
  77280. if (!this._postProcesses[cameraKey]) {
  77281. var postProcess = this._getPostProcesses();
  77282. if (postProcess) {
  77283. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  77284. }
  77285. }
  77286. if (!this._indicesForCamera[cameraName]) {
  77287. this._indicesForCamera[cameraName] = [];
  77288. }
  77289. this._postProcesses[cameraKey].forEach(function (postProcess) {
  77290. var index = camera.attachPostProcess(postProcess);
  77291. _this._indicesForCamera[cameraName].push(index);
  77292. });
  77293. if (!this._cameras[cameraName]) {
  77294. this._cameras[cameraName] = camera;
  77295. }
  77296. }
  77297. };
  77298. /**
  77299. * Detatches the effect on cameras
  77300. * @param cameras The camera to detatch from.
  77301. * @hidden
  77302. */
  77303. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  77304. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  77305. if (!cams) {
  77306. return;
  77307. }
  77308. for (var i = 0; i < cams.length; i++) {
  77309. var camera = cams[i];
  77310. var cameraName = camera.name;
  77311. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  77312. camera.detachPostProcess(postProcess);
  77313. });
  77314. if (this._cameras[cameraName]) {
  77315. //this._indicesForCamera.splice(index, 1);
  77316. this._cameras[cameraName] = null;
  77317. }
  77318. }
  77319. };
  77320. /**
  77321. * Enables the effect on given cameras
  77322. * @param cameras The camera to enable.
  77323. * @hidden
  77324. */
  77325. PostProcessRenderEffect.prototype._enable = function (cameras) {
  77326. var _this = this;
  77327. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  77328. if (!cams) {
  77329. return;
  77330. }
  77331. for (var i = 0; i < cams.length; i++) {
  77332. var camera = cams[i];
  77333. var cameraName = camera.name;
  77334. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  77335. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  77336. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  77337. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  77338. });
  77339. }
  77340. }
  77341. }
  77342. };
  77343. /**
  77344. * Disables the effect on the given cameras
  77345. * @param cameras The camera to disable.
  77346. * @hidden
  77347. */
  77348. PostProcessRenderEffect.prototype._disable = function (cameras) {
  77349. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  77350. if (!cams) {
  77351. return;
  77352. }
  77353. for (var i = 0; i < cams.length; i++) {
  77354. var camera = cams[i];
  77355. var cameraName = camera.name;
  77356. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  77357. camera.detachPostProcess(postProcess);
  77358. });
  77359. }
  77360. };
  77361. /**
  77362. * Gets a list of the post processes contained in the effect.
  77363. * @param camera The camera to get the post processes on.
  77364. * @returns The list of the post processes in the effect.
  77365. */
  77366. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  77367. if (this._singleInstance) {
  77368. return this._postProcesses[0];
  77369. }
  77370. else {
  77371. if (!camera) {
  77372. return null;
  77373. }
  77374. return this._postProcesses[camera.name];
  77375. }
  77376. };
  77377. return PostProcessRenderEffect;
  77378. }());
  77379. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  77380. })(BABYLON || (BABYLON = {}));
  77381. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  77382. var BABYLON;
  77383. (function (BABYLON) {
  77384. var PostProcessRenderPipeline = /** @class */ (function () {
  77385. function PostProcessRenderPipeline(engine, name) {
  77386. this.engine = engine;
  77387. this._name = name;
  77388. this._renderEffects = {};
  77389. this._renderEffectsForIsolatedPass = new Array();
  77390. this._cameras = [];
  77391. }
  77392. PostProcessRenderPipeline.prototype.getClassName = function () {
  77393. return "PostProcessRenderPipeline";
  77394. };
  77395. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  77396. get: function () {
  77397. for (var renderEffectName in this._renderEffects) {
  77398. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  77399. if (!this._renderEffects[renderEffectName].isSupported) {
  77400. return false;
  77401. }
  77402. }
  77403. }
  77404. return true;
  77405. },
  77406. enumerable: true,
  77407. configurable: true
  77408. });
  77409. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  77410. this._renderEffects[renderEffect._name] = renderEffect;
  77411. };
  77412. // private
  77413. /** @hidden */
  77414. PostProcessRenderPipeline.prototype._rebuild = function () {
  77415. };
  77416. /** @hidden */
  77417. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  77418. var renderEffects = this._renderEffects[renderEffectName];
  77419. if (!renderEffects) {
  77420. return;
  77421. }
  77422. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  77423. };
  77424. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  77425. var renderEffects = this._renderEffects[renderEffectName];
  77426. if (!renderEffects) {
  77427. return;
  77428. }
  77429. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  77430. };
  77431. /** @hidden */
  77432. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  77433. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  77434. if (!cams) {
  77435. return;
  77436. }
  77437. var indicesToDelete = [];
  77438. var i;
  77439. for (i = 0; i < cams.length; i++) {
  77440. var camera = cams[i];
  77441. var cameraName = camera.name;
  77442. if (this._cameras.indexOf(camera) === -1) {
  77443. this._cameras[cameraName] = camera;
  77444. }
  77445. else if (unique) {
  77446. indicesToDelete.push(i);
  77447. }
  77448. }
  77449. for (i = 0; i < indicesToDelete.length; i++) {
  77450. cameras.splice(indicesToDelete[i], 1);
  77451. }
  77452. for (var renderEffectName in this._renderEffects) {
  77453. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  77454. this._renderEffects[renderEffectName]._attachCameras(cams);
  77455. }
  77456. }
  77457. };
  77458. /** @hidden */
  77459. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  77460. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  77461. if (!cams) {
  77462. return;
  77463. }
  77464. for (var renderEffectName in this._renderEffects) {
  77465. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  77466. this._renderEffects[renderEffectName]._detachCameras(cams);
  77467. }
  77468. }
  77469. for (var i = 0; i < cams.length; i++) {
  77470. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  77471. }
  77472. };
  77473. /** @hidden */
  77474. PostProcessRenderPipeline.prototype._update = function () {
  77475. for (var renderEffectName in this._renderEffects) {
  77476. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  77477. this._renderEffects[renderEffectName]._update();
  77478. }
  77479. }
  77480. for (var i = 0; i < this._cameras.length; i++) {
  77481. var cameraName = this._cameras[i].name;
  77482. if (this._renderEffectsForIsolatedPass[cameraName]) {
  77483. this._renderEffectsForIsolatedPass[cameraName]._update();
  77484. }
  77485. }
  77486. };
  77487. /** @hidden */
  77488. PostProcessRenderPipeline.prototype._reset = function () {
  77489. this._renderEffects = {};
  77490. this._renderEffectsForIsolatedPass = new Array();
  77491. };
  77492. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  77493. // 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)
  77494. var effectKeys = Object.keys(this._renderEffects);
  77495. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  77496. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  77497. if (postProcesses) {
  77498. postProcesses[0].samples = sampleCount;
  77499. return true;
  77500. }
  77501. }
  77502. return false;
  77503. };
  77504. PostProcessRenderPipeline.prototype.dispose = function () {
  77505. // Must be implemented by children
  77506. };
  77507. __decorate([
  77508. BABYLON.serialize()
  77509. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  77510. return PostProcessRenderPipeline;
  77511. }());
  77512. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  77513. })(BABYLON || (BABYLON = {}));
  77514. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  77515. var BABYLON;
  77516. (function (BABYLON) {
  77517. /**
  77518. * This represents a depth renderer in Babylon.
  77519. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  77520. */
  77521. var DepthRenderer = /** @class */ (function () {
  77522. /**
  77523. * Instantiates a depth renderer
  77524. * @param scene The scene the renderer belongs to
  77525. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  77526. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  77527. */
  77528. function DepthRenderer(scene, type, camera) {
  77529. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  77530. if (camera === void 0) { camera = null; }
  77531. var _this = this;
  77532. /**
  77533. * Specifiess that the depth renderer will only be used within
  77534. * the camera it is created for.
  77535. * This can help forcing its rendering during the camera processing.
  77536. */
  77537. this.useOnlyInActiveCamera = false;
  77538. this._scene = scene;
  77539. // Register the G Buffer component to the scene.
  77540. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER);
  77541. if (!component) {
  77542. component = new BABYLON.DepthRendererSceneComponent(scene);
  77543. scene._addComponent(component);
  77544. }
  77545. this._camera = camera;
  77546. var engine = scene.getEngine();
  77547. // Render target
  77548. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  77549. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77550. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77551. this._depthMap.refreshRate = 1;
  77552. this._depthMap.renderParticles = false;
  77553. this._depthMap.renderList = null;
  77554. // Camera to get depth map from to support multiple concurrent cameras
  77555. this._depthMap.activeCamera = this._camera;
  77556. this._depthMap.ignoreCameraViewport = true;
  77557. this._depthMap.useCameraPostProcesses = false;
  77558. // set default depth value to 1.0 (far away)
  77559. this._depthMap.onClearObservable.add(function (engine) {
  77560. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  77561. });
  77562. // Custom render function
  77563. var renderSubMesh = function (subMesh) {
  77564. var mesh = subMesh.getRenderingMesh();
  77565. var scene = _this._scene;
  77566. var engine = scene.getEngine();
  77567. var material = subMesh.getMaterial();
  77568. if (!material) {
  77569. return;
  77570. }
  77571. // Culling and reverse (right handed system)
  77572. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  77573. // Managing instances
  77574. var batch = mesh._getInstancesRenderList(subMesh._id);
  77575. if (batch.mustReturn) {
  77576. return;
  77577. }
  77578. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  77579. var camera = _this._camera || scene.activeCamera;
  77580. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  77581. engine.enableEffect(_this._effect);
  77582. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  77583. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  77584. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  77585. // Alpha test
  77586. if (material && material.needAlphaTesting()) {
  77587. var alphaTexture = material.getAlphaTestTexture();
  77588. if (alphaTexture) {
  77589. _this._effect.setTexture("diffuseSampler", alphaTexture);
  77590. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  77591. }
  77592. }
  77593. // Bones
  77594. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  77595. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  77596. }
  77597. // Draw
  77598. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  77599. }
  77600. };
  77601. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  77602. var index;
  77603. if (depthOnlySubMeshes.length) {
  77604. engine.setColorWrite(false);
  77605. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  77606. renderSubMesh(depthOnlySubMeshes.data[index]);
  77607. }
  77608. engine.setColorWrite(true);
  77609. }
  77610. for (index = 0; index < opaqueSubMeshes.length; index++) {
  77611. renderSubMesh(opaqueSubMeshes.data[index]);
  77612. }
  77613. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  77614. renderSubMesh(alphaTestSubMeshes.data[index]);
  77615. }
  77616. };
  77617. }
  77618. /**
  77619. * Creates the depth rendering effect and checks if the effect is ready.
  77620. * @param subMesh The submesh to be used to render the depth map of
  77621. * @param useInstances If multiple world instances should be used
  77622. * @returns if the depth renderer is ready to render the depth map
  77623. */
  77624. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  77625. var material = subMesh.getMaterial();
  77626. if (material.disableDepthWrite) {
  77627. return false;
  77628. }
  77629. var defines = [];
  77630. var attribs = [BABYLON.VertexBuffer.PositionKind];
  77631. var mesh = subMesh.getMesh();
  77632. // Alpha test
  77633. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  77634. defines.push("#define ALPHATEST");
  77635. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  77636. attribs.push(BABYLON.VertexBuffer.UVKind);
  77637. defines.push("#define UV1");
  77638. }
  77639. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  77640. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  77641. defines.push("#define UV2");
  77642. }
  77643. }
  77644. // Bones
  77645. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  77646. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  77647. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  77648. if (mesh.numBoneInfluencers > 4) {
  77649. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  77650. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  77651. }
  77652. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  77653. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  77654. }
  77655. else {
  77656. defines.push("#define NUM_BONE_INFLUENCERS 0");
  77657. }
  77658. // Instances
  77659. if (useInstances) {
  77660. defines.push("#define INSTANCES");
  77661. attribs.push("world0");
  77662. attribs.push("world1");
  77663. attribs.push("world2");
  77664. attribs.push("world3");
  77665. }
  77666. // Get correct effect
  77667. var join = defines.join("\n");
  77668. if (this._cachedDefines !== join) {
  77669. this._cachedDefines = join;
  77670. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  77671. }
  77672. return this._effect.isReady();
  77673. };
  77674. /**
  77675. * Gets the texture which the depth map will be written to.
  77676. * @returns The depth map texture
  77677. */
  77678. DepthRenderer.prototype.getDepthMap = function () {
  77679. return this._depthMap;
  77680. };
  77681. /**
  77682. * Disposes of the depth renderer.
  77683. */
  77684. DepthRenderer.prototype.dispose = function () {
  77685. this._depthMap.dispose();
  77686. };
  77687. return DepthRenderer;
  77688. }());
  77689. BABYLON.DepthRenderer = DepthRenderer;
  77690. })(BABYLON || (BABYLON = {}));
  77691. //# sourceMappingURL=babylon.depthRenderer.js.map
  77692. var BABYLON;
  77693. (function (BABYLON) {
  77694. BABYLON.Scene.prototype.enableDepthRenderer = function (camera) {
  77695. camera = camera || this.activeCamera;
  77696. if (!camera) {
  77697. throw "No camera available to enable depth renderer";
  77698. }
  77699. if (!this._depthRenderer) {
  77700. this._depthRenderer = {};
  77701. }
  77702. if (!this._depthRenderer[camera.id]) {
  77703. var textureType = 0;
  77704. if (this.getEngine().getCaps().textureHalfFloatRender) {
  77705. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  77706. }
  77707. else if (this.getEngine().getCaps().textureFloatRender) {
  77708. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  77709. }
  77710. else {
  77711. throw "Depth renderer does not support int texture type";
  77712. }
  77713. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  77714. }
  77715. return this._depthRenderer[camera.id];
  77716. };
  77717. BABYLON.Scene.prototype.disableDepthRenderer = function (camera) {
  77718. camera = camera || this.activeCamera;
  77719. if (!camera || !this._depthRenderer || !this._depthRenderer[camera.id]) {
  77720. return;
  77721. }
  77722. this._depthRenderer[camera.id].dispose();
  77723. delete this._depthRenderer[camera.id];
  77724. };
  77725. /**
  77726. * Defines the Depth Renderer scene component responsible to manage a depth buffer usefull
  77727. * in several rendering techniques.
  77728. */
  77729. var DepthRendererSceneComponent = /** @class */ (function () {
  77730. /**
  77731. * Creates a new instance of the component for the given scene
  77732. * @param scene Defines the scene to register the component in
  77733. */
  77734. function DepthRendererSceneComponent(scene) {
  77735. /**
  77736. * The component name helpfull to identify the component in the list of scene components.
  77737. */
  77738. this.name = BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER;
  77739. this.scene = scene;
  77740. }
  77741. /**
  77742. * Registers the component in a given scene
  77743. */
  77744. DepthRendererSceneComponent.prototype.register = function () {
  77745. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER, this, this._gatherRenderTargets);
  77746. this.scene._gatherActiveCameraRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER, this, this._gatherActiveCameraRenderTargets);
  77747. };
  77748. /**
  77749. * Rebuilds the elements related to this component in case of
  77750. * context lost for instance.
  77751. */
  77752. DepthRendererSceneComponent.prototype.rebuild = function () {
  77753. // Nothing to do for this component
  77754. };
  77755. /**
  77756. * Disposes the component and the associated ressources
  77757. */
  77758. DepthRendererSceneComponent.prototype.dispose = function () {
  77759. for (var key in this.scene._depthRenderer) {
  77760. this.scene._depthRenderer[key].dispose();
  77761. }
  77762. };
  77763. DepthRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  77764. if (this.scene._depthRenderer) {
  77765. for (var key in this.scene._depthRenderer) {
  77766. var depthRenderer = this.scene._depthRenderer[key];
  77767. if (!depthRenderer.useOnlyInActiveCamera) {
  77768. renderTargets.push(depthRenderer.getDepthMap());
  77769. }
  77770. }
  77771. }
  77772. };
  77773. DepthRendererSceneComponent.prototype._gatherActiveCameraRenderTargets = function (renderTargets) {
  77774. if (this.scene._depthRenderer) {
  77775. for (var key in this.scene._depthRenderer) {
  77776. var depthRenderer = this.scene._depthRenderer[key];
  77777. if (depthRenderer.useOnlyInActiveCamera && this.scene.activeCamera.id === key) {
  77778. renderTargets.push(depthRenderer.getDepthMap());
  77779. }
  77780. }
  77781. }
  77782. };
  77783. return DepthRendererSceneComponent;
  77784. }());
  77785. BABYLON.DepthRendererSceneComponent = DepthRendererSceneComponent;
  77786. })(BABYLON || (BABYLON = {}));
  77787. //# sourceMappingURL=babylon.depthRendererSceneComponent.js.map
  77788. var BABYLON;
  77789. (function (BABYLON) {
  77790. /**
  77791. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  77792. */
  77793. var GeometryBufferRenderer = /** @class */ (function () {
  77794. /**
  77795. * Creates a new G Buffer for the scene
  77796. * @param scene The scene the buffer belongs to
  77797. * @param ratio How big is the buffer related to the main canvas.
  77798. */
  77799. function GeometryBufferRenderer(scene, ratio) {
  77800. if (ratio === void 0) { ratio = 1; }
  77801. this._enablePosition = false;
  77802. this._scene = scene;
  77803. this._ratio = ratio;
  77804. // Register the G Buffer component to the scene.
  77805. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER);
  77806. if (!component) {
  77807. component = new BABYLON.GeometryBufferRendererSceneComponent(scene);
  77808. scene._addComponent(component);
  77809. }
  77810. // Render target
  77811. this._createRenderTargets();
  77812. }
  77813. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  77814. /**
  77815. * Set the render list (meshes to be rendered) used in the G buffer.
  77816. */
  77817. set: function (meshes) {
  77818. this._multiRenderTarget.renderList = meshes;
  77819. },
  77820. enumerable: true,
  77821. configurable: true
  77822. });
  77823. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  77824. /**
  77825. * Gets wether or not G buffer are supported by the running hardware.
  77826. * This requires draw buffer supports
  77827. */
  77828. get: function () {
  77829. return this._multiRenderTarget.isSupported;
  77830. },
  77831. enumerable: true,
  77832. configurable: true
  77833. });
  77834. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  77835. /**
  77836. * Gets wether or not position are enabled for the G buffer.
  77837. */
  77838. get: function () {
  77839. return this._enablePosition;
  77840. },
  77841. /**
  77842. * Sets wether or not position are enabled for the G buffer.
  77843. */
  77844. set: function (enable) {
  77845. this._enablePosition = enable;
  77846. this.dispose();
  77847. this._createRenderTargets();
  77848. },
  77849. enumerable: true,
  77850. configurable: true
  77851. });
  77852. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  77853. /**
  77854. * Gets the scene associated with the buffer.
  77855. */
  77856. get: function () {
  77857. return this._scene;
  77858. },
  77859. enumerable: true,
  77860. configurable: true
  77861. });
  77862. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  77863. /**
  77864. * Gets the ratio used by the buffer during its creation.
  77865. * How big is the buffer related to the main canvas.
  77866. */
  77867. get: function () {
  77868. return this._ratio;
  77869. },
  77870. enumerable: true,
  77871. configurable: true
  77872. });
  77873. /**
  77874. * Checks wether everything is ready to render a submesh to the G buffer.
  77875. * @param subMesh the submesh to check readiness for
  77876. * @param useInstances is the mesh drawn using instance or not
  77877. * @returns true if ready otherwise false
  77878. */
  77879. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  77880. var material = subMesh.getMaterial();
  77881. if (material && material.disableDepthWrite) {
  77882. return false;
  77883. }
  77884. var defines = [];
  77885. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  77886. var mesh = subMesh.getMesh();
  77887. // Alpha test
  77888. if (material && material.needAlphaTesting()) {
  77889. defines.push("#define ALPHATEST");
  77890. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  77891. attribs.push(BABYLON.VertexBuffer.UVKind);
  77892. defines.push("#define UV1");
  77893. }
  77894. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  77895. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  77896. defines.push("#define UV2");
  77897. }
  77898. }
  77899. // Buffers
  77900. if (this._enablePosition) {
  77901. defines.push("#define POSITION");
  77902. }
  77903. // Bones
  77904. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  77905. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  77906. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  77907. if (mesh.numBoneInfluencers > 4) {
  77908. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  77909. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  77910. }
  77911. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  77912. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  77913. }
  77914. else {
  77915. defines.push("#define NUM_BONE_INFLUENCERS 0");
  77916. }
  77917. // Instances
  77918. if (useInstances) {
  77919. defines.push("#define INSTANCES");
  77920. attribs.push("world0");
  77921. attribs.push("world1");
  77922. attribs.push("world2");
  77923. attribs.push("world3");
  77924. }
  77925. // Get correct effect
  77926. var join = defines.join("\n");
  77927. if (this._cachedDefines !== join) {
  77928. this._cachedDefines = join;
  77929. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  77930. }
  77931. return this._effect.isReady();
  77932. };
  77933. /**
  77934. * Gets the current underlying G Buffer.
  77935. * @returns the buffer
  77936. */
  77937. GeometryBufferRenderer.prototype.getGBuffer = function () {
  77938. return this._multiRenderTarget;
  77939. };
  77940. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  77941. /**
  77942. * Gets the number of samples used to render the buffer (anti aliasing).
  77943. */
  77944. get: function () {
  77945. return this._multiRenderTarget.samples;
  77946. },
  77947. /**
  77948. * Sets the number of samples used to render the buffer (anti aliasing).
  77949. */
  77950. set: function (value) {
  77951. this._multiRenderTarget.samples = value;
  77952. },
  77953. enumerable: true,
  77954. configurable: true
  77955. });
  77956. /**
  77957. * Disposes the renderer and frees up associated resources.
  77958. */
  77959. GeometryBufferRenderer.prototype.dispose = function () {
  77960. this.getGBuffer().dispose();
  77961. };
  77962. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  77963. var _this = this;
  77964. var engine = this._scene.getEngine();
  77965. var count = this._enablePosition ? 3 : 2;
  77966. 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 });
  77967. if (!this.isSupported) {
  77968. return;
  77969. }
  77970. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77971. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77972. this._multiRenderTarget.refreshRate = 1;
  77973. this._multiRenderTarget.renderParticles = false;
  77974. this._multiRenderTarget.renderList = null;
  77975. // set default depth value to 1.0 (far away)
  77976. this._multiRenderTarget.onClearObservable.add(function (engine) {
  77977. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  77978. });
  77979. // Custom render function
  77980. var renderSubMesh = function (subMesh) {
  77981. var mesh = subMesh.getRenderingMesh();
  77982. var scene = _this._scene;
  77983. var engine = scene.getEngine();
  77984. var material = subMesh.getMaterial();
  77985. if (!material) {
  77986. return;
  77987. }
  77988. // Culling
  77989. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  77990. // Managing instances
  77991. var batch = mesh._getInstancesRenderList(subMesh._id);
  77992. if (batch.mustReturn) {
  77993. return;
  77994. }
  77995. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  77996. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  77997. engine.enableEffect(_this._effect);
  77998. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  77999. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  78000. _this._effect.setMatrix("view", scene.getViewMatrix());
  78001. // Alpha test
  78002. if (material && material.needAlphaTesting()) {
  78003. var alphaTexture = material.getAlphaTestTexture();
  78004. if (alphaTexture) {
  78005. _this._effect.setTexture("diffuseSampler", alphaTexture);
  78006. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  78007. }
  78008. }
  78009. // Bones
  78010. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  78011. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  78012. }
  78013. // Draw
  78014. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  78015. }
  78016. };
  78017. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  78018. var index;
  78019. if (depthOnlySubMeshes.length) {
  78020. engine.setColorWrite(false);
  78021. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  78022. renderSubMesh(depthOnlySubMeshes.data[index]);
  78023. }
  78024. engine.setColorWrite(true);
  78025. }
  78026. for (index = 0; index < opaqueSubMeshes.length; index++) {
  78027. renderSubMesh(opaqueSubMeshes.data[index]);
  78028. }
  78029. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  78030. renderSubMesh(alphaTestSubMeshes.data[index]);
  78031. }
  78032. };
  78033. };
  78034. return GeometryBufferRenderer;
  78035. }());
  78036. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  78037. })(BABYLON || (BABYLON = {}));
  78038. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  78039. var BABYLON;
  78040. (function (BABYLON) {
  78041. Object.defineProperty(BABYLON.Scene.prototype, "geometryBufferRenderer", {
  78042. get: function () {
  78043. this._geometryBufferRenderer;
  78044. },
  78045. set: function (value) {
  78046. if (value && value.isSupported) {
  78047. this._geometryBufferRenderer = value;
  78048. }
  78049. ;
  78050. },
  78051. enumerable: true,
  78052. configurable: true
  78053. });
  78054. BABYLON.Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  78055. if (ratio === void 0) { ratio = 1; }
  78056. if (this._geometryBufferRenderer) {
  78057. return this._geometryBufferRenderer;
  78058. }
  78059. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  78060. if (!this._geometryBufferRenderer.isSupported) {
  78061. this._geometryBufferRenderer = null;
  78062. }
  78063. return this._geometryBufferRenderer;
  78064. };
  78065. BABYLON.Scene.prototype.disableGeometryBufferRenderer = function () {
  78066. if (!this._geometryBufferRenderer) {
  78067. return;
  78068. }
  78069. this._geometryBufferRenderer.dispose();
  78070. this._geometryBufferRenderer = null;
  78071. };
  78072. /**
  78073. * Defines the Geometry Buffer scene component responsible to manage a G-Buffer usefull
  78074. * in several rendering techniques.
  78075. */
  78076. var GeometryBufferRendererSceneComponent = /** @class */ (function () {
  78077. /**
  78078. * Creates a new instance of the component for the given scene
  78079. * @param scene Defines the scene to register the component in
  78080. */
  78081. function GeometryBufferRendererSceneComponent(scene) {
  78082. /**
  78083. * The component name helpfull to identify the component in the list of scene components.
  78084. */
  78085. this.name = BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER;
  78086. this.scene = scene;
  78087. }
  78088. /**
  78089. * Registers the component in a given scene
  78090. */
  78091. GeometryBufferRendererSceneComponent.prototype.register = function () {
  78092. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER, this, this._gatherRenderTargets);
  78093. };
  78094. /**
  78095. * Rebuilds the elements related to this component in case of
  78096. * context lost for instance.
  78097. */
  78098. GeometryBufferRendererSceneComponent.prototype.rebuild = function () {
  78099. // Nothing to do for this component
  78100. };
  78101. /**
  78102. * Disposes the component and the associated ressources
  78103. */
  78104. GeometryBufferRendererSceneComponent.prototype.dispose = function () {
  78105. // Nothing to do for this component
  78106. };
  78107. GeometryBufferRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  78108. if (this.scene._geometryBufferRenderer) {
  78109. renderTargets.push(this.scene._geometryBufferRenderer.getGBuffer());
  78110. }
  78111. };
  78112. return GeometryBufferRendererSceneComponent;
  78113. }());
  78114. BABYLON.GeometryBufferRendererSceneComponent = GeometryBufferRendererSceneComponent;
  78115. })(BABYLON || (BABYLON = {}));
  78116. //# sourceMappingURL=babylon.geometryBufferRendererSceneComponent.js.map
  78117. var BABYLON;
  78118. (function (BABYLON) {
  78119. var SSAORenderingPipeline = /** @class */ (function (_super) {
  78120. __extends(SSAORenderingPipeline, _super);
  78121. /**
  78122. * @constructor
  78123. * @param {string} name - The rendering pipeline name
  78124. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  78125. * @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 }
  78126. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  78127. */
  78128. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  78129. var _this = _super.call(this, scene.getEngine(), name) || this;
  78130. // Members
  78131. /**
  78132. * The PassPostProcess id in the pipeline that contains the original scene color
  78133. */
  78134. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  78135. /**
  78136. * The SSAO PostProcess id in the pipeline
  78137. */
  78138. _this.SSAORenderEffect = "SSAORenderEffect";
  78139. /**
  78140. * The horizontal blur PostProcess id in the pipeline
  78141. */
  78142. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  78143. /**
  78144. * The vertical blur PostProcess id in the pipeline
  78145. */
  78146. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  78147. /**
  78148. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  78149. */
  78150. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  78151. /**
  78152. * The output strength of the SSAO post-process. Default value is 1.0.
  78153. */
  78154. _this.totalStrength = 1.0;
  78155. /**
  78156. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  78157. */
  78158. _this.radius = 0.0001;
  78159. /**
  78160. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  78161. * Must not be equal to fallOff and superior to fallOff.
  78162. * Default value is 0.975
  78163. */
  78164. _this.area = 0.0075;
  78165. /**
  78166. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  78167. * Must not be equal to area and inferior to area.
  78168. * Default value is 0.0
  78169. */
  78170. _this.fallOff = 0.000001;
  78171. /**
  78172. * The base color of the SSAO post-process
  78173. * The final result is "base + ssao" between [0, 1]
  78174. */
  78175. _this.base = 0.5;
  78176. _this._firstUpdate = true;
  78177. _this._scene = scene;
  78178. // Set up assets
  78179. _this._createRandomTexture();
  78180. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  78181. var ssaoRatio = ratio.ssaoRatio || ratio;
  78182. var combineRatio = ratio.combineRatio || ratio;
  78183. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  78184. _this._createSSAOPostProcess(ssaoRatio);
  78185. _this._createBlurPostProcess(ssaoRatio);
  78186. _this._createSSAOCombinePostProcess(combineRatio);
  78187. // Set up pipeline
  78188. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  78189. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  78190. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  78191. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  78192. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  78193. // Finish
  78194. scene.postProcessRenderPipelineManager.addPipeline(_this);
  78195. if (cameras)
  78196. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  78197. return _this;
  78198. }
  78199. // Public Methods
  78200. /**
  78201. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  78202. */
  78203. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  78204. if (disableDepthRender === void 0) { disableDepthRender = false; }
  78205. for (var i = 0; i < this._scene.cameras.length; i++) {
  78206. var camera = this._scene.cameras[i];
  78207. this._originalColorPostProcess.dispose(camera);
  78208. this._ssaoPostProcess.dispose(camera);
  78209. this._blurHPostProcess.dispose(camera);
  78210. this._blurVPostProcess.dispose(camera);
  78211. this._ssaoCombinePostProcess.dispose(camera);
  78212. }
  78213. this._randomTexture.dispose();
  78214. if (disableDepthRender)
  78215. this._scene.disableDepthRenderer();
  78216. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  78217. _super.prototype.dispose.call(this);
  78218. };
  78219. // Private Methods
  78220. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  78221. var _this = this;
  78222. var size = 16;
  78223. 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);
  78224. 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);
  78225. this._blurHPostProcess.onActivateObservable.add(function () {
  78226. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  78227. _this._blurHPostProcess.kernel = size * dw;
  78228. });
  78229. this._blurVPostProcess.onActivateObservable.add(function () {
  78230. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  78231. _this._blurVPostProcess.kernel = size * dw;
  78232. });
  78233. };
  78234. /** @hidden */
  78235. SSAORenderingPipeline.prototype._rebuild = function () {
  78236. this._firstUpdate = true;
  78237. _super.prototype._rebuild.call(this);
  78238. };
  78239. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  78240. var _this = this;
  78241. var numSamples = 16;
  78242. var sampleSphere = [
  78243. 0.5381, 0.1856, -0.4319,
  78244. 0.1379, 0.2486, 0.4430,
  78245. 0.3371, 0.5679, -0.0057,
  78246. -0.6999, -0.0451, -0.0019,
  78247. 0.0689, -0.1598, -0.8547,
  78248. 0.0560, 0.0069, -0.1843,
  78249. -0.0146, 0.1402, 0.0762,
  78250. 0.0100, -0.1924, -0.0344,
  78251. -0.3577, -0.5301, -0.4358,
  78252. -0.3169, 0.1063, 0.0158,
  78253. 0.0103, -0.5869, 0.0046,
  78254. -0.0897, -0.4940, 0.3287,
  78255. 0.7119, -0.0154, -0.0918,
  78256. -0.0533, 0.0596, -0.5411,
  78257. 0.0352, -0.0631, 0.5460,
  78258. -0.4776, 0.2847, -0.0271
  78259. ];
  78260. var samplesFactor = 1.0 / numSamples;
  78261. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  78262. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  78263. "area", "fallOff", "base", "range", "viewport"
  78264. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  78265. this._ssaoPostProcess.onApply = function (effect) {
  78266. if (_this._firstUpdate) {
  78267. effect.setArray3("sampleSphere", sampleSphere);
  78268. effect.setFloat("samplesFactor", samplesFactor);
  78269. effect.setFloat("randTextureTiles", 4.0);
  78270. }
  78271. effect.setFloat("totalStrength", _this.totalStrength);
  78272. effect.setFloat("radius", _this.radius);
  78273. effect.setFloat("area", _this.area);
  78274. effect.setFloat("fallOff", _this.fallOff);
  78275. effect.setFloat("base", _this.base);
  78276. effect.setTexture("textureSampler", _this._depthTexture);
  78277. effect.setTexture("randomSampler", _this._randomTexture);
  78278. };
  78279. };
  78280. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  78281. var _this = this;
  78282. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  78283. this._ssaoCombinePostProcess.onApply = function (effect) {
  78284. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  78285. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  78286. };
  78287. };
  78288. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  78289. var size = 512;
  78290. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  78291. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  78292. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  78293. var context = this._randomTexture.getContext();
  78294. var rand = function (min, max) {
  78295. return Math.random() * (max - min) + min;
  78296. };
  78297. var randVector = BABYLON.Vector3.Zero();
  78298. for (var x = 0; x < size; x++) {
  78299. for (var y = 0; y < size; y++) {
  78300. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  78301. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  78302. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  78303. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  78304. context.fillRect(x, y, 1, 1);
  78305. }
  78306. }
  78307. this._randomTexture.update(false);
  78308. };
  78309. __decorate([
  78310. BABYLON.serialize()
  78311. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  78312. __decorate([
  78313. BABYLON.serialize()
  78314. ], SSAORenderingPipeline.prototype, "radius", void 0);
  78315. __decorate([
  78316. BABYLON.serialize()
  78317. ], SSAORenderingPipeline.prototype, "area", void 0);
  78318. __decorate([
  78319. BABYLON.serialize()
  78320. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  78321. __decorate([
  78322. BABYLON.serialize()
  78323. ], SSAORenderingPipeline.prototype, "base", void 0);
  78324. return SSAORenderingPipeline;
  78325. }(BABYLON.PostProcessRenderPipeline));
  78326. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  78327. })(BABYLON || (BABYLON = {}));
  78328. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  78329. var BABYLON;
  78330. (function (BABYLON) {
  78331. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  78332. __extends(SSAO2RenderingPipeline, _super);
  78333. /**
  78334. * @constructor
  78335. * @param {string} name - The rendering pipeline name
  78336. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  78337. * @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 }
  78338. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  78339. */
  78340. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  78341. var _this = _super.call(this, scene.getEngine(), name) || this;
  78342. // Members
  78343. /**
  78344. * The PassPostProcess id in the pipeline that contains the original scene color
  78345. */
  78346. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  78347. /**
  78348. * The SSAO PostProcess id in the pipeline
  78349. */
  78350. _this.SSAORenderEffect = "SSAORenderEffect";
  78351. /**
  78352. * The horizontal blur PostProcess id in the pipeline
  78353. */
  78354. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  78355. /**
  78356. * The vertical blur PostProcess id in the pipeline
  78357. */
  78358. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  78359. /**
  78360. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  78361. */
  78362. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  78363. /**
  78364. * The output strength of the SSAO post-process. Default value is 1.0.
  78365. */
  78366. _this.totalStrength = 1.0;
  78367. /**
  78368. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  78369. */
  78370. _this.maxZ = 100.0;
  78371. /**
  78372. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  78373. */
  78374. _this.minZAspect = 0.2;
  78375. _this._samples = 8;
  78376. _this._textureSamples = 1;
  78377. /**
  78378. * Are we using bilateral blur ?
  78379. */
  78380. _this._expensiveBlur = true;
  78381. /**
  78382. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  78383. */
  78384. _this.radius = 2.0;
  78385. /**
  78386. * The base color of the SSAO post-process
  78387. * The final result is "base + ssao" between [0, 1]
  78388. */
  78389. _this.base = 0;
  78390. _this._firstUpdate = true;
  78391. _this._bits = new Uint32Array(1);
  78392. _this._scene = scene;
  78393. _this._ratio = ratio;
  78394. if (!_this.isSupported) {
  78395. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  78396. return _this;
  78397. }
  78398. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  78399. var blurRatio = _this._ratio.blurRatio || ratio;
  78400. // Set up assets
  78401. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  78402. _this._createRandomTexture();
  78403. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  78404. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  78405. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  78406. _this._originalColorPostProcess.samples = _this.textureSamples;
  78407. _this._createSSAOPostProcess(1.0);
  78408. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  78409. _this._createSSAOCombinePostProcess(blurRatio);
  78410. // Set up pipeline
  78411. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  78412. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  78413. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  78414. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  78415. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  78416. // Finish
  78417. scene.postProcessRenderPipelineManager.addPipeline(_this);
  78418. if (cameras)
  78419. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  78420. return _this;
  78421. }
  78422. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  78423. get: function () {
  78424. return this._samples;
  78425. },
  78426. /**
  78427. * Number of samples used for the SSAO calculations. Default value is 8
  78428. */
  78429. set: function (n) {
  78430. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  78431. this._samples = n;
  78432. this._sampleSphere = this._generateHemisphere();
  78433. this._firstUpdate = true;
  78434. },
  78435. enumerable: true,
  78436. configurable: true
  78437. });
  78438. Object.defineProperty(SSAO2RenderingPipeline.prototype, "textureSamples", {
  78439. get: function () {
  78440. return this._textureSamples;
  78441. },
  78442. /**
  78443. * Number of samples to use for antialiasing
  78444. */
  78445. set: function (n) {
  78446. this._textureSamples = n;
  78447. this._originalColorPostProcess.samples = n;
  78448. this._blurHPostProcess.samples = n;
  78449. this._blurVPostProcess.samples = n;
  78450. this._ssaoPostProcess.samples = n;
  78451. this._ssaoCombinePostProcess.samples = n;
  78452. },
  78453. enumerable: true,
  78454. configurable: true
  78455. });
  78456. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  78457. get: function () {
  78458. return this._expensiveBlur;
  78459. },
  78460. set: function (b) {
  78461. 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"]);
  78462. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  78463. this._expensiveBlur = b;
  78464. this._firstUpdate = true;
  78465. },
  78466. enumerable: true,
  78467. configurable: true
  78468. });
  78469. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  78470. /**
  78471. * Support test.
  78472. */
  78473. get: function () {
  78474. var engine = BABYLON.Engine.LastCreatedEngine;
  78475. if (!engine) {
  78476. return false;
  78477. }
  78478. return engine.getCaps().drawBuffersExtension;
  78479. },
  78480. enumerable: true,
  78481. configurable: true
  78482. });
  78483. // Public Methods
  78484. /**
  78485. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  78486. */
  78487. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  78488. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  78489. for (var i = 0; i < this._scene.cameras.length; i++) {
  78490. var camera = this._scene.cameras[i];
  78491. this._originalColorPostProcess.dispose(camera);
  78492. this._ssaoPostProcess.dispose(camera);
  78493. this._blurHPostProcess.dispose(camera);
  78494. this._blurVPostProcess.dispose(camera);
  78495. this._ssaoCombinePostProcess.dispose(camera);
  78496. }
  78497. this._randomTexture.dispose();
  78498. if (disableGeometryBufferRenderer)
  78499. this._scene.disableGeometryBufferRenderer();
  78500. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  78501. _super.prototype.dispose.call(this);
  78502. };
  78503. // Private Methods
  78504. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  78505. var _this = this;
  78506. this._samplerOffsets = [];
  78507. var expensive = this.expensiveBlur;
  78508. for (var i = -8; i < 8; i++) {
  78509. this._samplerOffsets.push(i * 2 + 0.5);
  78510. }
  78511. 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");
  78512. this._blurHPostProcess.onApply = function (effect) {
  78513. if (!_this._scene.activeCamera) {
  78514. return;
  78515. }
  78516. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  78517. effect.setFloat("near", _this._scene.activeCamera.minZ);
  78518. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  78519. effect.setFloat("radius", _this.radius);
  78520. effect.setTexture("depthSampler", _this._depthTexture);
  78521. if (_this._firstUpdate) {
  78522. effect.setArray("samplerOffsets", _this._samplerOffsets);
  78523. }
  78524. };
  78525. 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");
  78526. this._blurVPostProcess.onApply = function (effect) {
  78527. if (!_this._scene.activeCamera) {
  78528. return;
  78529. }
  78530. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  78531. effect.setFloat("near", _this._scene.activeCamera.minZ);
  78532. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  78533. effect.setFloat("radius", _this.radius);
  78534. effect.setTexture("depthSampler", _this._depthTexture);
  78535. if (_this._firstUpdate) {
  78536. effect.setArray("samplerOffsets", _this._samplerOffsets);
  78537. _this._firstUpdate = false;
  78538. }
  78539. };
  78540. this._blurHPostProcess.samples = this.textureSamples;
  78541. this._blurVPostProcess.samples = this.textureSamples;
  78542. };
  78543. /** @hidden */
  78544. SSAO2RenderingPipeline.prototype._rebuild = function () {
  78545. this._firstUpdate = true;
  78546. _super.prototype._rebuild.call(this);
  78547. };
  78548. //Van der Corput radical inverse
  78549. SSAO2RenderingPipeline.prototype._radicalInverse_VdC = function (i) {
  78550. this._bits[0] = i;
  78551. this._bits[0] = ((this._bits[0] << 16) | (this._bits[0] >> 16)) >>> 0;
  78552. this._bits[0] = ((this._bits[0] & 0x55555555) << 1) | ((this._bits[0] & 0xAAAAAAAA) >>> 1) >>> 0;
  78553. this._bits[0] = ((this._bits[0] & 0x33333333) << 2) | ((this._bits[0] & 0xCCCCCCCC) >>> 2) >>> 0;
  78554. this._bits[0] = ((this._bits[0] & 0x0F0F0F0F) << 4) | ((this._bits[0] & 0xF0F0F0F0) >>> 4) >>> 0;
  78555. this._bits[0] = ((this._bits[0] & 0x00FF00FF) << 8) | ((this._bits[0] & 0xFF00FF00) >>> 8) >>> 0;
  78556. return this._bits[0] * 2.3283064365386963e-10; // / 0x100000000 or / 4294967296
  78557. };
  78558. SSAO2RenderingPipeline.prototype._hammersley = function (i, n) {
  78559. return [i / n, this._radicalInverse_VdC(i)];
  78560. };
  78561. SSAO2RenderingPipeline.prototype._hemisphereSample_uniform = function (u, v) {
  78562. var phi = v * 2.0 * Math.PI;
  78563. // rejecting samples that are close to tangent plane to avoid z-fighting artifacts
  78564. var cosTheta = 1.0 - (u * 0.85 + 0.15);
  78565. var sinTheta = Math.sqrt(1.0 - cosTheta * cosTheta);
  78566. return new BABYLON.Vector3(Math.cos(phi) * sinTheta, Math.sin(phi) * sinTheta, cosTheta);
  78567. };
  78568. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  78569. var numSamples = this.samples;
  78570. var result = [];
  78571. var vector;
  78572. var i = 0;
  78573. while (i < numSamples) {
  78574. if (numSamples < 16) {
  78575. vector = this._hemisphereSample_uniform(Math.random(), Math.random());
  78576. }
  78577. else {
  78578. var rand = this._hammersley(i, numSamples);
  78579. vector = this._hemisphereSample_uniform(rand[0], rand[1]);
  78580. }
  78581. result.push(vector.x, vector.y, vector.z);
  78582. i++;
  78583. }
  78584. return result;
  78585. };
  78586. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  78587. var _this = this;
  78588. var numSamples = this.samples;
  78589. this._sampleSphere = this._generateHemisphere();
  78590. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  78591. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  78592. "base", "range", "projection", "near", "far", "texelSize",
  78593. "xViewport", "yViewport", "maxZ", "minZAspect"
  78594. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  78595. this._ssaoPostProcess.onApply = function (effect) {
  78596. if (_this._firstUpdate) {
  78597. effect.setArray3("sampleSphere", _this._sampleSphere);
  78598. effect.setFloat("randTextureTiles", 32.0);
  78599. }
  78600. if (!_this._scene.activeCamera) {
  78601. return;
  78602. }
  78603. effect.setFloat("samplesFactor", 1 / _this.samples);
  78604. effect.setFloat("totalStrength", _this.totalStrength);
  78605. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  78606. effect.setFloat("radius", _this.radius);
  78607. effect.setFloat("maxZ", _this.maxZ);
  78608. effect.setFloat("minZAspect", _this.minZAspect);
  78609. effect.setFloat("base", _this.base);
  78610. effect.setFloat("near", _this._scene.activeCamera.minZ);
  78611. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  78612. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  78613. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  78614. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  78615. effect.setTexture("textureSampler", _this._depthTexture);
  78616. effect.setTexture("normalSampler", _this._normalTexture);
  78617. effect.setTexture("randomSampler", _this._randomTexture);
  78618. };
  78619. this._ssaoPostProcess.samples = this.textureSamples;
  78620. };
  78621. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  78622. var _this = this;
  78623. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  78624. this._ssaoCombinePostProcess.onApply = function (effect) {
  78625. var viewport = _this._scene.activeCamera.viewport;
  78626. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  78627. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  78628. };
  78629. this._ssaoCombinePostProcess.samples = this.textureSamples;
  78630. };
  78631. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  78632. var size = 128;
  78633. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  78634. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  78635. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  78636. var context = this._randomTexture.getContext();
  78637. var rand = function (min, max) {
  78638. return Math.random() * (max - min) + min;
  78639. };
  78640. var randVector = BABYLON.Vector3.Zero();
  78641. for (var x = 0; x < size; x++) {
  78642. for (var y = 0; y < size; y++) {
  78643. randVector.x = rand(0.0, 1.0);
  78644. randVector.y = rand(0.0, 1.0);
  78645. randVector.z = 0.0;
  78646. randVector.normalize();
  78647. randVector.scaleInPlace(255);
  78648. randVector.x = Math.floor(randVector.x);
  78649. randVector.y = Math.floor(randVector.y);
  78650. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  78651. context.fillRect(x, y, 1, 1);
  78652. }
  78653. }
  78654. this._randomTexture.update(false);
  78655. };
  78656. /**
  78657. * Serialize the rendering pipeline (Used when exporting)
  78658. * @returns the serialized object
  78659. */
  78660. SSAO2RenderingPipeline.prototype.serialize = function () {
  78661. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  78662. serializationObject.customType = "SSAO2RenderingPipeline";
  78663. return serializationObject;
  78664. };
  78665. /**
  78666. * Parse the serialized pipeline
  78667. * @param source Source pipeline.
  78668. * @param scene The scene to load the pipeline to.
  78669. * @param rootUrl The URL of the serialized pipeline.
  78670. * @returns An instantiated pipeline from the serialized object.
  78671. */
  78672. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  78673. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  78674. };
  78675. __decorate([
  78676. BABYLON.serialize()
  78677. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  78678. __decorate([
  78679. BABYLON.serialize()
  78680. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  78681. __decorate([
  78682. BABYLON.serialize()
  78683. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  78684. __decorate([
  78685. BABYLON.serialize("samples")
  78686. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  78687. __decorate([
  78688. BABYLON.serialize("textureSamples")
  78689. ], SSAO2RenderingPipeline.prototype, "_textureSamples", void 0);
  78690. __decorate([
  78691. BABYLON.serialize()
  78692. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  78693. __decorate([
  78694. BABYLON.serialize("expensiveBlur")
  78695. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  78696. __decorate([
  78697. BABYLON.serialize()
  78698. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  78699. __decorate([
  78700. BABYLON.serialize()
  78701. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  78702. return SSAO2RenderingPipeline;
  78703. }(BABYLON.PostProcessRenderPipeline));
  78704. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  78705. })(BABYLON || (BABYLON = {}));
  78706. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  78707. // BABYLON.JS Chromatic Aberration GLSL Shader
  78708. // Author: Olivier Guyot
  78709. // Separates very slightly R, G and B colors on the edges of the screen
  78710. // Inspired by Francois Tarlier & Martins Upitis
  78711. var BABYLON;
  78712. (function (BABYLON) {
  78713. var LensRenderingPipeline = /** @class */ (function (_super) {
  78714. __extends(LensRenderingPipeline, _super);
  78715. /**
  78716. * @constructor
  78717. *
  78718. * Effect parameters are as follow:
  78719. * {
  78720. * chromatic_aberration: number; // from 0 to x (1 for realism)
  78721. * edge_blur: number; // from 0 to x (1 for realism)
  78722. * distortion: number; // from 0 to x (1 for realism)
  78723. * grain_amount: number; // from 0 to 1
  78724. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  78725. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  78726. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  78727. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  78728. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  78729. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  78730. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  78731. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  78732. * }
  78733. * Note: if an effect parameter is unset, effect is disabled
  78734. *
  78735. * @param {string} name - The rendering pipeline name
  78736. * @param {object} parameters - An object containing all parameters (see above)
  78737. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  78738. * @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)
  78739. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  78740. */
  78741. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  78742. if (ratio === void 0) { ratio = 1.0; }
  78743. var _this = _super.call(this, scene.getEngine(), name) || this;
  78744. // Lens effects can be of the following:
  78745. // - chromatic aberration (slight shift of RGB colors)
  78746. // - blur on the edge of the lens
  78747. // - lens distortion
  78748. // - depth-of-field blur & highlights enhancing
  78749. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  78750. // - grain effect (noise or custom texture)
  78751. // Two additional texture samplers are needed:
  78752. // - depth map (for depth-of-field)
  78753. // - grain texture
  78754. /**
  78755. * The chromatic aberration PostProcess id in the pipeline
  78756. */
  78757. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  78758. /**
  78759. * The highlights enhancing PostProcess id in the pipeline
  78760. */
  78761. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  78762. /**
  78763. * The depth-of-field PostProcess id in the pipeline
  78764. */
  78765. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  78766. _this._scene = scene;
  78767. // Fetch texture samplers
  78768. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  78769. if (parameters.grain_texture) {
  78770. _this._grainTexture = parameters.grain_texture;
  78771. }
  78772. else {
  78773. _this._createGrainTexture();
  78774. }
  78775. // save parameters
  78776. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  78777. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  78778. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  78779. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  78780. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  78781. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  78782. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  78783. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  78784. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  78785. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  78786. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  78787. // Create effects
  78788. _this._createChromaticAberrationPostProcess(ratio);
  78789. _this._createHighlightsPostProcess(ratio);
  78790. _this._createDepthOfFieldPostProcess(ratio / 4);
  78791. // Set up pipeline
  78792. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  78793. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  78794. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  78795. if (_this._highlightsGain === -1) {
  78796. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  78797. }
  78798. // Finish
  78799. scene.postProcessRenderPipelineManager.addPipeline(_this);
  78800. if (cameras) {
  78801. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  78802. }
  78803. return _this;
  78804. }
  78805. // public methods (self explanatory)
  78806. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  78807. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  78808. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  78809. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  78810. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  78811. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  78812. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  78813. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  78814. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  78815. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  78816. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  78817. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  78818. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  78819. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  78820. };
  78821. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  78822. this._highlightsPostProcess.updateEffect();
  78823. };
  78824. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  78825. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  78826. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  78827. this._highlightsGain = amount;
  78828. };
  78829. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  78830. if (this._highlightsGain === -1) {
  78831. this._highlightsGain = 1.0;
  78832. }
  78833. this._highlightsThreshold = amount;
  78834. };
  78835. LensRenderingPipeline.prototype.disableHighlights = function () {
  78836. this._highlightsGain = -1;
  78837. };
  78838. /**
  78839. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  78840. */
  78841. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  78842. if (disableDepthRender === void 0) { disableDepthRender = false; }
  78843. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  78844. this._chromaticAberrationPostProcess = null;
  78845. this._highlightsPostProcess = null;
  78846. this._depthOfFieldPostProcess = null;
  78847. this._grainTexture.dispose();
  78848. if (disableDepthRender)
  78849. this._scene.disableDepthRenderer();
  78850. };
  78851. // colors shifting and distortion
  78852. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  78853. var _this = this;
  78854. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  78855. [], // samplers
  78856. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  78857. this._chromaticAberrationPostProcess.onApply = function (effect) {
  78858. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  78859. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  78860. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  78861. effect.setFloat('radialIntensity', 1);
  78862. effect.setFloat2('direction', 17, 17);
  78863. effect.setFloat2('centerPosition', 0.5, 0.5);
  78864. };
  78865. };
  78866. // highlights enhancing
  78867. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  78868. var _this = this;
  78869. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  78870. [], // samplers
  78871. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  78872. this._highlightsPostProcess.onApply = function (effect) {
  78873. effect.setFloat('gain', _this._highlightsGain);
  78874. effect.setFloat('threshold', _this._highlightsThreshold);
  78875. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  78876. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  78877. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  78878. };
  78879. };
  78880. // colors shifting and distortion
  78881. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  78882. var _this = this;
  78883. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  78884. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  78885. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  78886. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  78887. this._depthOfFieldPostProcess.onApply = function (effect) {
  78888. effect.setTexture("depthSampler", _this._depthTexture);
  78889. effect.setTexture("grainSampler", _this._grainTexture);
  78890. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  78891. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  78892. effect.setFloat('grain_amount', _this._grainAmount);
  78893. effect.setBool('blur_noise', _this._blurNoise);
  78894. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  78895. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  78896. effect.setFloat('distortion', _this._distortion);
  78897. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  78898. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  78899. effect.setFloat('aperture', _this._dofAperture);
  78900. effect.setFloat('darken', _this._dofDarken);
  78901. effect.setFloat('edge_blur', _this._edgeBlur);
  78902. effect.setBool('highlights', (_this._highlightsGain !== -1));
  78903. if (_this._scene.activeCamera) {
  78904. effect.setFloat('near', _this._scene.activeCamera.minZ);
  78905. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  78906. }
  78907. };
  78908. };
  78909. // creates a black and white random noise texture, 512x512
  78910. LensRenderingPipeline.prototype._createGrainTexture = function () {
  78911. var size = 512;
  78912. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  78913. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  78914. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  78915. var context = this._grainTexture.getContext();
  78916. var rand = function (min, max) {
  78917. return Math.random() * (max - min) + min;
  78918. };
  78919. var value;
  78920. for (var x = 0; x < size; x++) {
  78921. for (var y = 0; y < size; y++) {
  78922. value = Math.floor(rand(0.42, 0.58) * 255);
  78923. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  78924. context.fillRect(x, y, 1, 1);
  78925. }
  78926. }
  78927. this._grainTexture.update(false);
  78928. };
  78929. return LensRenderingPipeline;
  78930. }(BABYLON.PostProcessRenderPipeline));
  78931. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  78932. })(BABYLON || (BABYLON = {}));
  78933. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  78934. var BABYLON;
  78935. (function (BABYLON) {
  78936. var StandardRenderingPipeline = /** @class */ (function (_super) {
  78937. __extends(StandardRenderingPipeline, _super);
  78938. /**
  78939. * @constructor
  78940. * @param {string} name - The rendering pipeline name
  78941. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  78942. * @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)
  78943. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  78944. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  78945. */
  78946. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  78947. if (originalPostProcess === void 0) { originalPostProcess = null; }
  78948. var _this = _super.call(this, scene.getEngine(), name) || this;
  78949. /**
  78950. * Post-process used to down scale an image x4
  78951. */
  78952. _this.downSampleX4PostProcess = null;
  78953. /**
  78954. * Post-process used to calculate the illuminated surfaces controlled by a threshold
  78955. */
  78956. _this.brightPassPostProcess = null;
  78957. /**
  78958. * Post-process array storing all the horizontal blur post-processes used by the pipeline
  78959. */
  78960. _this.blurHPostProcesses = [];
  78961. /**
  78962. * Post-process array storing all the vertical blur post-processes used by the pipeline
  78963. */
  78964. _this.blurVPostProcesses = [];
  78965. /**
  78966. * Post-process used to add colors of 2 textures (typically brightness + real scene color)
  78967. */
  78968. _this.textureAdderPostProcess = null;
  78969. /**
  78970. * Post-process used to create volumetric lighting effect
  78971. */
  78972. _this.volumetricLightPostProcess = null;
  78973. /**
  78974. * Post-process used to smooth the previous volumetric light post-process on the X axis
  78975. */
  78976. _this.volumetricLightSmoothXPostProcess = null;
  78977. /**
  78978. * Post-process used to smooth the previous volumetric light post-process on the Y axis
  78979. */
  78980. _this.volumetricLightSmoothYPostProcess = null;
  78981. /**
  78982. * Post-process used to merge the volumetric light effect and the real scene color
  78983. */
  78984. _this.volumetricLightMergePostProces = null;
  78985. /**
  78986. * Post-process used to store the final volumetric light post-process (attach/detach for debug purpose)
  78987. */
  78988. _this.volumetricLightFinalPostProcess = null;
  78989. /**
  78990. * Base post-process used to calculate the average luminance of the final image for HDR
  78991. */
  78992. _this.luminancePostProcess = null;
  78993. /**
  78994. * Post-processes used to create down sample post-processes in order to get
  78995. * the average luminance of the final image for HDR
  78996. * Array of length "StandardRenderingPipeline.LuminanceSteps"
  78997. */
  78998. _this.luminanceDownSamplePostProcesses = [];
  78999. /**
  79000. * Post-process used to create a HDR effect (light adaptation)
  79001. */
  79002. _this.hdrPostProcess = null;
  79003. /**
  79004. * Post-process used to store the final texture adder post-process (attach/detach for debug purpose)
  79005. */
  79006. _this.textureAdderFinalPostProcess = null;
  79007. /**
  79008. * Post-process used to store the final lens flare post-process (attach/detach for debug purpose)
  79009. */
  79010. _this.lensFlareFinalPostProcess = null;
  79011. /**
  79012. * Post-process used to merge the final HDR post-process and the real scene color
  79013. */
  79014. _this.hdrFinalPostProcess = null;
  79015. /**
  79016. * Post-process used to create a lens flare effect
  79017. */
  79018. _this.lensFlarePostProcess = null;
  79019. /**
  79020. * Post-process that merges the result of the lens flare post-process and the real scene color
  79021. */
  79022. _this.lensFlareComposePostProcess = null;
  79023. /**
  79024. * Post-process used to create a motion blur effect
  79025. */
  79026. _this.motionBlurPostProcess = null;
  79027. /**
  79028. * Post-process used to create a depth of field effect
  79029. */
  79030. _this.depthOfFieldPostProcess = null;
  79031. /**
  79032. * The Fast Approximate Anti-Aliasing post process which attemps to remove aliasing from an image.
  79033. */
  79034. _this.fxaaPostProcess = null;
  79035. // Values
  79036. /**
  79037. * Represents the brightness threshold in order to configure the illuminated surfaces
  79038. */
  79039. _this.brightThreshold = 1.0;
  79040. /**
  79041. * Configures the blur intensity used for surexposed surfaces are highlighted surfaces (light halo)
  79042. */
  79043. _this.blurWidth = 512.0;
  79044. /**
  79045. * Sets if the blur for highlighted surfaces must be only horizontal
  79046. */
  79047. _this.horizontalBlur = false;
  79048. /**
  79049. * Sets the overall exposure used by the pipeline
  79050. */
  79051. _this.exposure = 1.0;
  79052. /**
  79053. * Texture used typically to simulate "dirty" on camera lens
  79054. */
  79055. _this.lensTexture = null;
  79056. /**
  79057. * Represents the offset coefficient based on Rayleigh principle. Typically in interval [-0.2, 0.2]
  79058. */
  79059. _this.volumetricLightCoefficient = 0.2;
  79060. /**
  79061. * The overall power of volumetric lights, typically in interval [0, 10] maximum
  79062. */
  79063. _this.volumetricLightPower = 4.0;
  79064. /**
  79065. * Used the set the blur intensity to smooth the volumetric lights
  79066. */
  79067. _this.volumetricLightBlurScale = 64.0;
  79068. /**
  79069. * Light (spot or directional) used to generate the volumetric lights rays
  79070. * The source light must have a shadow generate so the pipeline can get its
  79071. * depth map
  79072. */
  79073. _this.sourceLight = null;
  79074. /**
  79075. * For eye adaptation, represents the minimum luminance the eye can see
  79076. */
  79077. _this.hdrMinimumLuminance = 1.0;
  79078. /**
  79079. * For eye adaptation, represents the decrease luminance speed
  79080. */
  79081. _this.hdrDecreaseRate = 0.5;
  79082. /**
  79083. * For eye adaptation, represents the increase luminance speed
  79084. */
  79085. _this.hdrIncreaseRate = 0.5;
  79086. /**
  79087. * Lens color texture used by the lens flare effect. Mandatory if lens flare effect enabled
  79088. */
  79089. _this.lensColorTexture = null;
  79090. /**
  79091. * The overall strengh for the lens flare effect
  79092. */
  79093. _this.lensFlareStrength = 20.0;
  79094. /**
  79095. * Dispersion coefficient for lens flare ghosts
  79096. */
  79097. _this.lensFlareGhostDispersal = 1.4;
  79098. /**
  79099. * Main lens flare halo width
  79100. */
  79101. _this.lensFlareHaloWidth = 0.7;
  79102. /**
  79103. * Based on the lens distortion effect, defines how much the lens flare result
  79104. * is distorted
  79105. */
  79106. _this.lensFlareDistortionStrength = 16.0;
  79107. /**
  79108. * Lens star texture must be used to simulate rays on the flares and is available
  79109. * in the documentation
  79110. */
  79111. _this.lensStarTexture = null;
  79112. /**
  79113. * As the "lensTexture" (can be the same texture or different), it is used to apply the lens
  79114. * flare effect by taking account of the dirt texture
  79115. */
  79116. _this.lensFlareDirtTexture = null;
  79117. /**
  79118. * Represents the focal length for the depth of field effect
  79119. */
  79120. _this.depthOfFieldDistance = 10.0;
  79121. /**
  79122. * Represents the blur intensity for the blurred part of the depth of field effect
  79123. */
  79124. _this.depthOfFieldBlurWidth = 64.0;
  79125. /**
  79126. * For motion blur, defines how much the image is blurred by the movement
  79127. */
  79128. _this.motionStrength = 1.0;
  79129. /**
  79130. * List of animations for the pipeline (IAnimatable implementation)
  79131. */
  79132. _this.animations = [];
  79133. _this._currentDepthOfFieldSource = null;
  79134. _this._hdrCurrentLuminance = 1.0;
  79135. // Getters and setters
  79136. _this._bloomEnabled = false;
  79137. _this._depthOfFieldEnabled = false;
  79138. _this._vlsEnabled = false;
  79139. _this._lensFlareEnabled = false;
  79140. _this._hdrEnabled = false;
  79141. _this._motionBlurEnabled = false;
  79142. _this._fxaaEnabled = false;
  79143. _this._motionBlurSamples = 64.0;
  79144. _this._volumetricLightStepsCount = 50.0;
  79145. _this._samples = 1;
  79146. _this._cameras = cameras || [];
  79147. // Initialize
  79148. _this._scene = scene;
  79149. _this._basePostProcess = originalPostProcess;
  79150. _this._ratio = ratio;
  79151. // Misc
  79152. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  79153. // Finish
  79154. scene.postProcessRenderPipelineManager.addPipeline(_this);
  79155. _this._buildPipeline();
  79156. return _this;
  79157. }
  79158. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  79159. /**
  79160. * Specifies if the bloom pipeline is enabled
  79161. */
  79162. get: function () {
  79163. return this._bloomEnabled;
  79164. },
  79165. set: function (enabled) {
  79166. if (this._bloomEnabled === enabled) {
  79167. return;
  79168. }
  79169. this._bloomEnabled = enabled;
  79170. this._buildPipeline();
  79171. },
  79172. enumerable: true,
  79173. configurable: true
  79174. });
  79175. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  79176. /**
  79177. * Specifies if the depth of field pipeline is enabed
  79178. */
  79179. get: function () {
  79180. return this._depthOfFieldEnabled;
  79181. },
  79182. set: function (enabled) {
  79183. if (this._depthOfFieldEnabled === enabled) {
  79184. return;
  79185. }
  79186. this._depthOfFieldEnabled = enabled;
  79187. this._buildPipeline();
  79188. },
  79189. enumerable: true,
  79190. configurable: true
  79191. });
  79192. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  79193. /**
  79194. * Specifies if the lens flare pipeline is enabed
  79195. */
  79196. get: function () {
  79197. return this._lensFlareEnabled;
  79198. },
  79199. set: function (enabled) {
  79200. if (this._lensFlareEnabled === enabled) {
  79201. return;
  79202. }
  79203. this._lensFlareEnabled = enabled;
  79204. this._buildPipeline();
  79205. },
  79206. enumerable: true,
  79207. configurable: true
  79208. });
  79209. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  79210. /**
  79211. * Specifies if the HDR pipeline is enabled
  79212. */
  79213. get: function () {
  79214. return this._hdrEnabled;
  79215. },
  79216. set: function (enabled) {
  79217. if (this._hdrEnabled === enabled) {
  79218. return;
  79219. }
  79220. this._hdrEnabled = enabled;
  79221. this._buildPipeline();
  79222. },
  79223. enumerable: true,
  79224. configurable: true
  79225. });
  79226. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  79227. /**
  79228. * Specifies if the volumetric lights scattering effect is enabled
  79229. */
  79230. get: function () {
  79231. return this._vlsEnabled;
  79232. },
  79233. set: function (enabled) {
  79234. if (this._vlsEnabled === enabled) {
  79235. return;
  79236. }
  79237. if (enabled) {
  79238. var geometry = this._scene.enableGeometryBufferRenderer();
  79239. if (!geometry) {
  79240. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  79241. return;
  79242. }
  79243. }
  79244. this._vlsEnabled = enabled;
  79245. this._buildPipeline();
  79246. },
  79247. enumerable: true,
  79248. configurable: true
  79249. });
  79250. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  79251. /**
  79252. * Specifies if the motion blur effect is enabled
  79253. */
  79254. get: function () {
  79255. return this._motionBlurEnabled;
  79256. },
  79257. set: function (enabled) {
  79258. if (this._motionBlurEnabled === enabled) {
  79259. return;
  79260. }
  79261. this._motionBlurEnabled = enabled;
  79262. this._buildPipeline();
  79263. },
  79264. enumerable: true,
  79265. configurable: true
  79266. });
  79267. Object.defineProperty(StandardRenderingPipeline.prototype, "fxaaEnabled", {
  79268. /**
  79269. * Specifies if anti-aliasing is enabled
  79270. */
  79271. get: function () {
  79272. return this._fxaaEnabled;
  79273. },
  79274. set: function (enabled) {
  79275. if (this._fxaaEnabled === enabled) {
  79276. return;
  79277. }
  79278. this._fxaaEnabled = enabled;
  79279. this._buildPipeline();
  79280. },
  79281. enumerable: true,
  79282. configurable: true
  79283. });
  79284. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  79285. /**
  79286. * Specifies the number of steps used to calculate the volumetric lights
  79287. * Typically in interval [50, 200]
  79288. */
  79289. get: function () {
  79290. return this._volumetricLightStepsCount;
  79291. },
  79292. set: function (count) {
  79293. if (this.volumetricLightPostProcess) {
  79294. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  79295. }
  79296. this._volumetricLightStepsCount = count;
  79297. },
  79298. enumerable: true,
  79299. configurable: true
  79300. });
  79301. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  79302. /**
  79303. * Specifies the number of samples used for the motion blur effect
  79304. * Typically in interval [16, 64]
  79305. */
  79306. get: function () {
  79307. return this._motionBlurSamples;
  79308. },
  79309. set: function (samples) {
  79310. if (this.motionBlurPostProcess) {
  79311. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  79312. }
  79313. this._motionBlurSamples = samples;
  79314. },
  79315. enumerable: true,
  79316. configurable: true
  79317. });
  79318. Object.defineProperty(StandardRenderingPipeline.prototype, "samples", {
  79319. /**
  79320. * Specifies MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  79321. */
  79322. get: function () {
  79323. return this._samples;
  79324. },
  79325. set: function (sampleCount) {
  79326. if (this._samples === sampleCount) {
  79327. return;
  79328. }
  79329. this._samples = sampleCount;
  79330. this._buildPipeline();
  79331. },
  79332. enumerable: true,
  79333. configurable: true
  79334. });
  79335. StandardRenderingPipeline.prototype._buildPipeline = function () {
  79336. var _this = this;
  79337. var ratio = this._ratio;
  79338. var scene = this._scene;
  79339. this._disposePostProcesses();
  79340. this._reset();
  79341. // Create pass post-process
  79342. if (!this._basePostProcess) {
  79343. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  79344. this.originalPostProcess.onApply = function (effect) {
  79345. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  79346. };
  79347. }
  79348. else {
  79349. this.originalPostProcess = this._basePostProcess;
  79350. }
  79351. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  79352. this._currentDepthOfFieldSource = this.originalPostProcess;
  79353. if (this._bloomEnabled) {
  79354. // Create down sample X4 post-process
  79355. this._createDownSampleX4PostProcess(scene, ratio / 2);
  79356. // Create bright pass post-process
  79357. this._createBrightPassPostProcess(scene, ratio / 2);
  79358. // Create gaussian blur post-processes (down sampling blurs)
  79359. this._createBlurPostProcesses(scene, ratio / 4, 1);
  79360. // Create texture adder post-process
  79361. this._createTextureAdderPostProcess(scene, ratio);
  79362. // Create depth-of-field source post-process
  79363. 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);
  79364. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  79365. }
  79366. if (this._vlsEnabled) {
  79367. // Create volumetric light
  79368. this._createVolumetricLightPostProcess(scene, ratio);
  79369. // Create volumetric light final post-process
  79370. 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);
  79371. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  79372. }
  79373. if (this._lensFlareEnabled) {
  79374. // Create lens flare post-process
  79375. this._createLensFlarePostProcess(scene, ratio);
  79376. // Create depth-of-field source post-process post lens-flare and disable it now
  79377. 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);
  79378. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  79379. }
  79380. if (this._hdrEnabled) {
  79381. // Create luminance
  79382. this._createLuminancePostProcesses(scene, this._floatTextureType);
  79383. // Create HDR
  79384. this._createHdrPostProcess(scene, ratio);
  79385. // Create depth-of-field source post-process post hdr and disable it now
  79386. 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);
  79387. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  79388. }
  79389. if (this._depthOfFieldEnabled) {
  79390. // Create gaussian blur used by depth-of-field
  79391. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  79392. // Create depth-of-field post-process
  79393. this._createDepthOfFieldPostProcess(scene, ratio);
  79394. }
  79395. if (this._motionBlurEnabled) {
  79396. // Create motion blur post-process
  79397. this._createMotionBlurPostProcess(scene, ratio);
  79398. }
  79399. if (this._fxaaEnabled) {
  79400. // Create fxaa post-process
  79401. this.fxaaPostProcess = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  79402. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRFxaa", function () { return _this.fxaaPostProcess; }, true));
  79403. }
  79404. if (this._cameras !== null) {
  79405. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  79406. }
  79407. if (!this._enableMSAAOnFirstPostProcess(this._samples) && this._samples > 1) {
  79408. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  79409. }
  79410. };
  79411. // Down Sample X4 Post-Processs
  79412. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  79413. var _this = this;
  79414. var downSampleX4Offsets = new Array(32);
  79415. 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);
  79416. this.downSampleX4PostProcess.onApply = function (effect) {
  79417. var id = 0;
  79418. var width = _this.downSampleX4PostProcess.width;
  79419. var height = _this.downSampleX4PostProcess.height;
  79420. for (var i = -2; i < 2; i++) {
  79421. for (var j = -2; j < 2; j++) {
  79422. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  79423. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  79424. id += 2;
  79425. }
  79426. }
  79427. effect.setArray2("dsOffsets", downSampleX4Offsets);
  79428. };
  79429. // Add to pipeline
  79430. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  79431. };
  79432. // Brightpass Post-Process
  79433. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  79434. var _this = this;
  79435. var brightOffsets = new Array(8);
  79436. 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);
  79437. this.brightPassPostProcess.onApply = function (effect) {
  79438. var sU = (1.0 / _this.brightPassPostProcess.width);
  79439. var sV = (1.0 / _this.brightPassPostProcess.height);
  79440. brightOffsets[0] = -0.5 * sU;
  79441. brightOffsets[1] = 0.5 * sV;
  79442. brightOffsets[2] = 0.5 * sU;
  79443. brightOffsets[3] = 0.5 * sV;
  79444. brightOffsets[4] = -0.5 * sU;
  79445. brightOffsets[5] = -0.5 * sV;
  79446. brightOffsets[6] = 0.5 * sU;
  79447. brightOffsets[7] = -0.5 * sV;
  79448. effect.setArray2("dsOffsets", brightOffsets);
  79449. effect.setFloat("brightThreshold", _this.brightThreshold);
  79450. };
  79451. // Add to pipeline
  79452. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  79453. };
  79454. // Create blur H&V post-processes
  79455. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  79456. var _this = this;
  79457. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  79458. var engine = scene.getEngine();
  79459. 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);
  79460. 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);
  79461. blurX.onActivateObservable.add(function () {
  79462. var dw = blurX.width / engine.getRenderWidth();
  79463. blurX.kernel = _this[blurWidthKey] * dw;
  79464. });
  79465. blurY.onActivateObservable.add(function () {
  79466. var dw = blurY.height / engine.getRenderHeight();
  79467. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  79468. });
  79469. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  79470. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  79471. this.blurHPostProcesses.push(blurX);
  79472. this.blurVPostProcesses.push(blurY);
  79473. };
  79474. // Create texture adder post-process
  79475. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  79476. var _this = this;
  79477. 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);
  79478. this.textureAdderPostProcess.onApply = function (effect) {
  79479. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  79480. effect.setTexture("lensSampler", _this.lensTexture);
  79481. effect.setFloat("exposure", _this.exposure);
  79482. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  79483. };
  79484. // Add to pipeline
  79485. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  79486. };
  79487. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  79488. var _this = this;
  79489. var geometryRenderer = scene.enableGeometryBufferRenderer();
  79490. geometryRenderer.enablePosition = true;
  79491. var geometry = geometryRenderer.getGBuffer();
  79492. // Base post-process
  79493. 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));
  79494. var depthValues = BABYLON.Vector2.Zero();
  79495. this.volumetricLightPostProcess.onApply = function (effect) {
  79496. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  79497. var generator = _this.sourceLight.getShadowGenerator();
  79498. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  79499. effect.setTexture("positionSampler", geometry.textures[2]);
  79500. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  79501. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  79502. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  79503. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  79504. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  79505. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  79506. depthValues.x = _this.sourceLight.getDepthMinZ(_this._scene.activeCamera);
  79507. depthValues.y = _this.sourceLight.getDepthMaxZ(_this._scene.activeCamera);
  79508. effect.setVector2("depthValues", depthValues);
  79509. }
  79510. };
  79511. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  79512. // Smooth
  79513. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  79514. // Merge
  79515. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  79516. this.volumetricLightMergePostProces.onApply = function (effect) {
  79517. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  79518. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  79519. };
  79520. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  79521. };
  79522. // Create luminance
  79523. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  79524. var _this = this;
  79525. // Create luminance
  79526. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  79527. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  79528. var offsets = [];
  79529. this.luminancePostProcess.onApply = function (effect) {
  79530. var sU = (1.0 / _this.luminancePostProcess.width);
  79531. var sV = (1.0 / _this.luminancePostProcess.height);
  79532. offsets[0] = -0.5 * sU;
  79533. offsets[1] = 0.5 * sV;
  79534. offsets[2] = 0.5 * sU;
  79535. offsets[3] = 0.5 * sV;
  79536. offsets[4] = -0.5 * sU;
  79537. offsets[5] = -0.5 * sV;
  79538. offsets[6] = 0.5 * sU;
  79539. offsets[7] = -0.5 * sV;
  79540. effect.setArray2("lumOffsets", offsets);
  79541. };
  79542. // Add to pipeline
  79543. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  79544. // Create down sample luminance
  79545. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  79546. var size = Math.pow(3, i);
  79547. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  79548. if (i === 0) {
  79549. defines += "#define FINAL_DOWN_SAMPLER";
  79550. }
  79551. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  79552. this.luminanceDownSamplePostProcesses.push(postProcess);
  79553. }
  79554. // Create callbacks and add effects
  79555. var lastLuminance = this.luminancePostProcess;
  79556. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  79557. var downSampleOffsets = new Array(18);
  79558. pp.onApply = function (effect) {
  79559. if (!lastLuminance) {
  79560. return;
  79561. }
  79562. var id = 0;
  79563. for (var x = -1; x < 2; x++) {
  79564. for (var y = -1; y < 2; y++) {
  79565. downSampleOffsets[id] = x / lastLuminance.width;
  79566. downSampleOffsets[id + 1] = y / lastLuminance.height;
  79567. id += 2;
  79568. }
  79569. }
  79570. effect.setArray2("dsOffsets", downSampleOffsets);
  79571. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  79572. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  79573. lastLuminance = _this.luminancePostProcess;
  79574. }
  79575. else {
  79576. lastLuminance = pp;
  79577. }
  79578. };
  79579. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  79580. pp.onAfterRender = function (effect) {
  79581. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  79582. 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);
  79583. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  79584. };
  79585. }
  79586. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  79587. });
  79588. };
  79589. // Create HDR post-process
  79590. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  79591. var _this = this;
  79592. 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);
  79593. var outputLiminance = 1;
  79594. var time = 0;
  79595. var lastTime = 0;
  79596. this.hdrPostProcess.onApply = function (effect) {
  79597. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  79598. time += scene.getEngine().getDeltaTime();
  79599. if (outputLiminance < 0) {
  79600. outputLiminance = _this._hdrCurrentLuminance;
  79601. }
  79602. else {
  79603. var dt = (lastTime - time) / 1000.0;
  79604. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  79605. outputLiminance += _this.hdrDecreaseRate * dt;
  79606. }
  79607. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  79608. outputLiminance -= _this.hdrIncreaseRate * dt;
  79609. }
  79610. else {
  79611. outputLiminance = _this._hdrCurrentLuminance;
  79612. }
  79613. }
  79614. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  79615. effect.setFloat("averageLuminance", outputLiminance);
  79616. lastTime = time;
  79617. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  79618. };
  79619. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  79620. };
  79621. // Create lens flare post-process
  79622. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  79623. var _this = this;
  79624. 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);
  79625. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  79626. this._createBlurPostProcesses(scene, ratio / 4, 2);
  79627. 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);
  79628. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  79629. var resolution = new BABYLON.Vector2(0, 0);
  79630. // Lens flare
  79631. this.lensFlarePostProcess.onApply = function (effect) {
  79632. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  79633. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  79634. effect.setFloat("strength", _this.lensFlareStrength);
  79635. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  79636. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  79637. // Shift
  79638. resolution.x = _this.lensFlarePostProcess.width;
  79639. resolution.y = _this.lensFlarePostProcess.height;
  79640. effect.setVector2("resolution", resolution);
  79641. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  79642. };
  79643. // Compose
  79644. 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);
  79645. 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);
  79646. this.lensFlareComposePostProcess.onApply = function (effect) {
  79647. if (!_this._scene.activeCamera) {
  79648. return;
  79649. }
  79650. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  79651. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  79652. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  79653. // Lens start rotation matrix
  79654. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  79655. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  79656. 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));
  79657. camRot *= 4.0;
  79658. 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);
  79659. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  79660. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  79661. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  79662. };
  79663. };
  79664. // Create depth-of-field post-process
  79665. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  79666. var _this = this;
  79667. 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);
  79668. this.depthOfFieldPostProcess.onApply = function (effect) {
  79669. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  79670. effect.setTexture("depthSampler", _this._getDepthTexture());
  79671. effect.setFloat("distance", _this.depthOfFieldDistance);
  79672. };
  79673. // Add to pipeline
  79674. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  79675. };
  79676. // Create motion blur post-process
  79677. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  79678. var _this = this;
  79679. 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);
  79680. var motionScale = 0;
  79681. var prevViewProjection = BABYLON.Matrix.Identity();
  79682. var invViewProjection = BABYLON.Matrix.Identity();
  79683. var viewProjection = BABYLON.Matrix.Identity();
  79684. var screenSize = BABYLON.Vector2.Zero();
  79685. this.motionBlurPostProcess.onApply = function (effect) {
  79686. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  79687. viewProjection.invertToRef(invViewProjection);
  79688. effect.setMatrix("inverseViewProjection", invViewProjection);
  79689. effect.setMatrix("prevViewProjection", prevViewProjection);
  79690. prevViewProjection = viewProjection;
  79691. screenSize.x = _this.motionBlurPostProcess.width;
  79692. screenSize.y = _this.motionBlurPostProcess.height;
  79693. effect.setVector2("screenSize", screenSize);
  79694. motionScale = scene.getEngine().getFps() / 60.0;
  79695. effect.setFloat("motionScale", motionScale);
  79696. effect.setFloat("motionStrength", _this.motionStrength);
  79697. effect.setTexture("depthSampler", _this._getDepthTexture());
  79698. };
  79699. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  79700. };
  79701. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  79702. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  79703. var renderer = this._scene.enableGeometryBufferRenderer();
  79704. return renderer.getGBuffer().textures[0];
  79705. }
  79706. return this._scene.enableDepthRenderer().getDepthMap();
  79707. };
  79708. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  79709. for (var i = 0; i < this._cameras.length; i++) {
  79710. var camera = this._cameras[i];
  79711. if (this.originalPostProcess) {
  79712. this.originalPostProcess.dispose(camera);
  79713. }
  79714. if (this.downSampleX4PostProcess) {
  79715. this.downSampleX4PostProcess.dispose(camera);
  79716. }
  79717. if (this.brightPassPostProcess) {
  79718. this.brightPassPostProcess.dispose(camera);
  79719. }
  79720. if (this.textureAdderPostProcess) {
  79721. this.textureAdderPostProcess.dispose(camera);
  79722. }
  79723. if (this.textureAdderFinalPostProcess) {
  79724. this.textureAdderFinalPostProcess.dispose(camera);
  79725. }
  79726. if (this.volumetricLightPostProcess) {
  79727. this.volumetricLightPostProcess.dispose(camera);
  79728. }
  79729. if (this.volumetricLightSmoothXPostProcess) {
  79730. this.volumetricLightSmoothXPostProcess.dispose(camera);
  79731. }
  79732. if (this.volumetricLightSmoothYPostProcess) {
  79733. this.volumetricLightSmoothYPostProcess.dispose(camera);
  79734. }
  79735. if (this.volumetricLightMergePostProces) {
  79736. this.volumetricLightMergePostProces.dispose(camera);
  79737. }
  79738. if (this.volumetricLightFinalPostProcess) {
  79739. this.volumetricLightFinalPostProcess.dispose(camera);
  79740. }
  79741. if (this.lensFlarePostProcess) {
  79742. this.lensFlarePostProcess.dispose(camera);
  79743. }
  79744. if (this.lensFlareComposePostProcess) {
  79745. this.lensFlareComposePostProcess.dispose(camera);
  79746. }
  79747. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  79748. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  79749. }
  79750. if (this.luminancePostProcess) {
  79751. this.luminancePostProcess.dispose(camera);
  79752. }
  79753. if (this.hdrPostProcess) {
  79754. this.hdrPostProcess.dispose(camera);
  79755. }
  79756. if (this.hdrFinalPostProcess) {
  79757. this.hdrFinalPostProcess.dispose(camera);
  79758. }
  79759. if (this.depthOfFieldPostProcess) {
  79760. this.depthOfFieldPostProcess.dispose(camera);
  79761. }
  79762. if (this.motionBlurPostProcess) {
  79763. this.motionBlurPostProcess.dispose(camera);
  79764. }
  79765. if (this.fxaaPostProcess) {
  79766. this.fxaaPostProcess.dispose(camera);
  79767. }
  79768. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  79769. this.blurHPostProcesses[j].dispose(camera);
  79770. }
  79771. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  79772. this.blurVPostProcesses[j].dispose(camera);
  79773. }
  79774. }
  79775. this.originalPostProcess = null;
  79776. this.downSampleX4PostProcess = null;
  79777. this.brightPassPostProcess = null;
  79778. this.textureAdderPostProcess = null;
  79779. this.textureAdderFinalPostProcess = null;
  79780. this.volumetricLightPostProcess = null;
  79781. this.volumetricLightSmoothXPostProcess = null;
  79782. this.volumetricLightSmoothYPostProcess = null;
  79783. this.volumetricLightMergePostProces = null;
  79784. this.volumetricLightFinalPostProcess = null;
  79785. this.lensFlarePostProcess = null;
  79786. this.lensFlareComposePostProcess = null;
  79787. this.luminancePostProcess = null;
  79788. this.hdrPostProcess = null;
  79789. this.hdrFinalPostProcess = null;
  79790. this.depthOfFieldPostProcess = null;
  79791. this.motionBlurPostProcess = null;
  79792. this.fxaaPostProcess = null;
  79793. this.luminanceDownSamplePostProcesses = [];
  79794. this.blurHPostProcesses = [];
  79795. this.blurVPostProcesses = [];
  79796. };
  79797. /**
  79798. * Dispose of the pipeline and stop all post processes
  79799. */
  79800. StandardRenderingPipeline.prototype.dispose = function () {
  79801. this._disposePostProcesses();
  79802. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  79803. _super.prototype.dispose.call(this);
  79804. };
  79805. /**
  79806. * Serialize the rendering pipeline (Used when exporting)
  79807. * @returns the serialized object
  79808. */
  79809. StandardRenderingPipeline.prototype.serialize = function () {
  79810. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  79811. if (this.sourceLight) {
  79812. serializationObject.sourceLightId = this.sourceLight.id;
  79813. }
  79814. serializationObject.customType = "StandardRenderingPipeline";
  79815. return serializationObject;
  79816. };
  79817. /**
  79818. * Parse the serialized pipeline
  79819. * @param source Source pipeline.
  79820. * @param scene The scene to load the pipeline to.
  79821. * @param rootUrl The URL of the serialized pipeline.
  79822. * @returns An instantiated pipeline from the serialized object.
  79823. */
  79824. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  79825. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  79826. if (source.sourceLightId) {
  79827. p.sourceLight = scene.getLightByID(source.sourceLightId);
  79828. }
  79829. return p;
  79830. };
  79831. // Luminance steps
  79832. StandardRenderingPipeline.LuminanceSteps = 6;
  79833. __decorate([
  79834. BABYLON.serialize()
  79835. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  79836. __decorate([
  79837. BABYLON.serialize()
  79838. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  79839. __decorate([
  79840. BABYLON.serialize()
  79841. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  79842. __decorate([
  79843. BABYLON.serialize()
  79844. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  79845. __decorate([
  79846. BABYLON.serializeAsTexture("lensTexture")
  79847. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  79848. __decorate([
  79849. BABYLON.serialize()
  79850. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  79851. __decorate([
  79852. BABYLON.serialize()
  79853. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  79854. __decorate([
  79855. BABYLON.serialize()
  79856. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  79857. __decorate([
  79858. BABYLON.serialize()
  79859. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  79860. __decorate([
  79861. BABYLON.serialize()
  79862. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  79863. __decorate([
  79864. BABYLON.serialize()
  79865. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  79866. __decorate([
  79867. BABYLON.serializeAsTexture("lensColorTexture")
  79868. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  79869. __decorate([
  79870. BABYLON.serialize()
  79871. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  79872. __decorate([
  79873. BABYLON.serialize()
  79874. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  79875. __decorate([
  79876. BABYLON.serialize()
  79877. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  79878. __decorate([
  79879. BABYLON.serialize()
  79880. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  79881. __decorate([
  79882. BABYLON.serializeAsTexture("lensStarTexture")
  79883. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  79884. __decorate([
  79885. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  79886. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  79887. __decorate([
  79888. BABYLON.serialize()
  79889. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  79890. __decorate([
  79891. BABYLON.serialize()
  79892. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  79893. __decorate([
  79894. BABYLON.serialize()
  79895. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  79896. __decorate([
  79897. BABYLON.serialize()
  79898. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  79899. __decorate([
  79900. BABYLON.serialize()
  79901. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  79902. __decorate([
  79903. BABYLON.serialize()
  79904. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  79905. __decorate([
  79906. BABYLON.serialize()
  79907. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  79908. __decorate([
  79909. BABYLON.serialize()
  79910. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  79911. __decorate([
  79912. BABYLON.serialize()
  79913. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  79914. __decorate([
  79915. BABYLON.serialize()
  79916. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  79917. __decorate([
  79918. BABYLON.serialize()
  79919. ], StandardRenderingPipeline.prototype, "fxaaEnabled", null);
  79920. __decorate([
  79921. BABYLON.serialize()
  79922. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  79923. __decorate([
  79924. BABYLON.serialize()
  79925. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  79926. __decorate([
  79927. BABYLON.serialize()
  79928. ], StandardRenderingPipeline.prototype, "samples", null);
  79929. return StandardRenderingPipeline;
  79930. }(BABYLON.PostProcessRenderPipeline));
  79931. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  79932. })(BABYLON || (BABYLON = {}));
  79933. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  79934. var BABYLON;
  79935. (function (BABYLON) {
  79936. var FxaaPostProcess = /** @class */ (function (_super) {
  79937. __extends(FxaaPostProcess, _super);
  79938. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  79939. if (camera === void 0) { camera = null; }
  79940. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  79941. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  79942. var defines = _this._getDefines();
  79943. _this.updateEffect(defines);
  79944. _this.onApplyObservable.add(function (effect) {
  79945. var texelSize = _this.texelSize;
  79946. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  79947. });
  79948. return _this;
  79949. }
  79950. FxaaPostProcess.prototype._getDefines = function () {
  79951. var engine = this.getEngine();
  79952. if (!engine) {
  79953. return null;
  79954. }
  79955. var glInfo = engine.getGlInfo();
  79956. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  79957. return "#define MALI 1\n";
  79958. }
  79959. return null;
  79960. };
  79961. return FxaaPostProcess;
  79962. }(BABYLON.PostProcess));
  79963. BABYLON.FxaaPostProcess = FxaaPostProcess;
  79964. })(BABYLON || (BABYLON = {}));
  79965. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  79966. var BABYLON;
  79967. (function (BABYLON) {
  79968. /**
  79969. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  79970. */
  79971. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  79972. __extends(ChromaticAberrationPostProcess, _super);
  79973. /**
  79974. * Creates a new instance ChromaticAberrationPostProcess
  79975. * @param name The name of the effect.
  79976. * @param screenWidth The width of the screen to apply the effect on.
  79977. * @param screenHeight The height of the screen to apply the effect on.
  79978. * @param options The required width/height ratio to downsize to before computing the render pass.
  79979. * @param camera The camera to apply the render pass to.
  79980. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  79981. * @param engine The engine which the post process will be applied. (default: current engine)
  79982. * @param reusable If the post process can be reused on the same frame. (default: false)
  79983. * @param textureType Type of textures used when performing the post process. (default: 0)
  79984. * @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)
  79985. */
  79986. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  79987. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  79988. if (blockCompilation === void 0) { blockCompilation = false; }
  79989. 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;
  79990. /**
  79991. * The amount of seperation of rgb channels (default: 30)
  79992. */
  79993. _this.aberrationAmount = 30;
  79994. /**
  79995. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  79996. */
  79997. _this.radialIntensity = 0;
  79998. /**
  79999. * 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))
  80000. */
  80001. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  80002. /**
  80003. * 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))
  80004. */
  80005. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  80006. _this.onApplyObservable.add(function (effect) {
  80007. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  80008. effect.setFloat('screen_width', screenWidth);
  80009. effect.setFloat('screen_height', screenHeight);
  80010. effect.setFloat('radialIntensity', _this.radialIntensity);
  80011. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  80012. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  80013. });
  80014. return _this;
  80015. }
  80016. return ChromaticAberrationPostProcess;
  80017. }(BABYLON.PostProcess));
  80018. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  80019. })(BABYLON || (BABYLON = {}));
  80020. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  80021. var BABYLON;
  80022. (function (BABYLON) {
  80023. /**
  80024. * The GrainPostProcess adds noise to the image at mid luminance levels
  80025. */
  80026. var GrainPostProcess = /** @class */ (function (_super) {
  80027. __extends(GrainPostProcess, _super);
  80028. /**
  80029. * Creates a new instance of @see GrainPostProcess
  80030. * @param name The name of the effect.
  80031. * @param options The required width/height ratio to downsize to before computing the render pass.
  80032. * @param camera The camera to apply the render pass to.
  80033. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  80034. * @param engine The engine which the post process will be applied. (default: current engine)
  80035. * @param reusable If the post process can be reused on the same frame. (default: false)
  80036. * @param textureType Type of textures used when performing the post process. (default: 0)
  80037. * @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)
  80038. */
  80039. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  80040. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80041. if (blockCompilation === void 0) { blockCompilation = false; }
  80042. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  80043. /**
  80044. * The intensity of the grain added (default: 30)
  80045. */
  80046. _this.intensity = 30;
  80047. /**
  80048. * If the grain should be randomized on every frame
  80049. */
  80050. _this.animated = false;
  80051. _this.onApplyObservable.add(function (effect) {
  80052. effect.setFloat('intensity', _this.intensity);
  80053. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  80054. });
  80055. return _this;
  80056. }
  80057. return GrainPostProcess;
  80058. }(BABYLON.PostProcess));
  80059. BABYLON.GrainPostProcess = GrainPostProcess;
  80060. })(BABYLON || (BABYLON = {}));
  80061. //# sourceMappingURL=babylon.grainPostProcess.js.map
  80062. var BABYLON;
  80063. (function (BABYLON) {
  80064. /**
  80065. * The SharpenPostProcess applies a sharpen kernel to every pixel
  80066. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  80067. */
  80068. var SharpenPostProcess = /** @class */ (function (_super) {
  80069. __extends(SharpenPostProcess, _super);
  80070. /**
  80071. * Creates a new instance ConvolutionPostProcess
  80072. * @param name The name of the effect.
  80073. * @param options The required width/height ratio to downsize to before computing the render pass.
  80074. * @param camera The camera to apply the render pass to.
  80075. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  80076. * @param engine The engine which the post process will be applied. (default: current engine)
  80077. * @param reusable If the post process can be reused on the same frame. (default: false)
  80078. * @param textureType Type of textures used when performing the post process. (default: 0)
  80079. * @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)
  80080. */
  80081. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  80082. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80083. if (blockCompilation === void 0) { blockCompilation = false; }
  80084. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  80085. /**
  80086. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  80087. */
  80088. _this.colorAmount = 1.0;
  80089. /**
  80090. * How much sharpness should be applied (default: 0.3)
  80091. */
  80092. _this.edgeAmount = 0.3;
  80093. _this.onApply = function (effect) {
  80094. effect.setFloat2("screenSize", _this.width, _this.height);
  80095. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  80096. };
  80097. return _this;
  80098. }
  80099. return SharpenPostProcess;
  80100. }(BABYLON.PostProcess));
  80101. BABYLON.SharpenPostProcess = SharpenPostProcess;
  80102. })(BABYLON || (BABYLON = {}));
  80103. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  80104. var BABYLON;
  80105. (function (BABYLON) {
  80106. /**
  80107. * The Blur Post Process which blurs an image based on a kernel and direction.
  80108. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  80109. */
  80110. var BlurPostProcess = /** @class */ (function (_super) {
  80111. __extends(BlurPostProcess, _super);
  80112. /**
  80113. * Creates a new instance BlurPostProcess
  80114. * @param name The name of the effect.
  80115. * @param direction The direction in which to blur the image.
  80116. * @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.
  80117. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  80118. * @param camera The camera to apply the render pass to.
  80119. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  80120. * @param engine The engine which the post process will be applied. (default: current engine)
  80121. * @param reusable If the post process can be reused on the same frame. (default: false)
  80122. * @param textureType Type of textures used when performing the post process. (default: 0)
  80123. * @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)
  80124. */
  80125. function BlurPostProcess(name,
  80126. /** The direction in which to blur the image. */
  80127. direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  80128. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  80129. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80130. if (defines === void 0) { defines = ""; }
  80131. if (blockCompilation === void 0) { blockCompilation = false; }
  80132. 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;
  80133. _this.direction = direction;
  80134. _this.blockCompilation = blockCompilation;
  80135. _this._packedFloat = false;
  80136. _this._staticDefines = "";
  80137. _this._staticDefines = defines;
  80138. _this.onApplyObservable.add(function (effect) {
  80139. if (_this._outputTexture) {
  80140. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  80141. }
  80142. else {
  80143. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  80144. }
  80145. });
  80146. _this.kernel = kernel;
  80147. return _this;
  80148. }
  80149. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  80150. /**
  80151. * Gets the length in pixels of the blur sample region
  80152. */
  80153. get: function () {
  80154. return this._idealKernel;
  80155. },
  80156. /**
  80157. * Sets the length in pixels of the blur sample region
  80158. */
  80159. set: function (v) {
  80160. if (this._idealKernel === v) {
  80161. return;
  80162. }
  80163. v = Math.max(v, 1);
  80164. this._idealKernel = v;
  80165. this._kernel = this._nearestBestKernel(v);
  80166. if (!this.blockCompilation) {
  80167. this._updateParameters();
  80168. }
  80169. },
  80170. enumerable: true,
  80171. configurable: true
  80172. });
  80173. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  80174. /**
  80175. * Gets wether or not the blur is unpacking/repacking floats
  80176. */
  80177. get: function () {
  80178. return this._packedFloat;
  80179. },
  80180. /**
  80181. * Sets wether or not the blur needs to unpack/repack floats
  80182. */
  80183. set: function (v) {
  80184. if (this._packedFloat === v) {
  80185. return;
  80186. }
  80187. this._packedFloat = v;
  80188. if (!this.blockCompilation) {
  80189. this._updateParameters();
  80190. }
  80191. },
  80192. enumerable: true,
  80193. configurable: true
  80194. });
  80195. /**
  80196. * Updates the effect with the current post process compile time values and recompiles the shader.
  80197. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  80198. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  80199. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  80200. * @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
  80201. * @param onCompiled Called when the shader has been compiled.
  80202. * @param onError Called if there is an error when compiling a shader.
  80203. */
  80204. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  80205. if (defines === void 0) { defines = null; }
  80206. if (uniforms === void 0) { uniforms = null; }
  80207. if (samplers === void 0) { samplers = null; }
  80208. this._updateParameters(onCompiled, onError);
  80209. };
  80210. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  80211. // Generate sampling offsets and weights
  80212. var N = this._kernel;
  80213. var centerIndex = (N - 1) / 2;
  80214. // Generate Gaussian sampling weights over kernel
  80215. var offsets = [];
  80216. var weights = [];
  80217. var totalWeight = 0;
  80218. for (var i = 0; i < N; i++) {
  80219. var u = i / (N - 1);
  80220. var w = this._gaussianWeight(u * 2.0 - 1);
  80221. offsets[i] = (i - centerIndex);
  80222. weights[i] = w;
  80223. totalWeight += w;
  80224. }
  80225. // Normalize weights
  80226. for (var i = 0; i < weights.length; i++) {
  80227. weights[i] /= totalWeight;
  80228. }
  80229. // Optimize: combine samples to take advantage of hardware linear sampling
  80230. // Walk from left to center, combining pairs (symmetrically)
  80231. var linearSamplingWeights = [];
  80232. var linearSamplingOffsets = [];
  80233. var linearSamplingMap = [];
  80234. for (var i = 0; i <= centerIndex; i += 2) {
  80235. var j = Math.min(i + 1, Math.floor(centerIndex));
  80236. var singleCenterSample = i === j;
  80237. if (singleCenterSample) {
  80238. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  80239. }
  80240. else {
  80241. var sharedCell = j === centerIndex;
  80242. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  80243. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  80244. if (offsetLinear === 0) {
  80245. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  80246. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  80247. }
  80248. else {
  80249. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  80250. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  80251. }
  80252. }
  80253. }
  80254. for (var i = 0; i < linearSamplingMap.length; i++) {
  80255. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  80256. linearSamplingWeights[i] = linearSamplingMap[i].w;
  80257. }
  80258. // Replace with optimized
  80259. offsets = linearSamplingOffsets;
  80260. weights = linearSamplingWeights;
  80261. // Generate shaders
  80262. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  80263. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  80264. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  80265. var defines = "";
  80266. defines += this._staticDefines;
  80267. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  80268. if (this._staticDefines.indexOf("DOF") != -1) {
  80269. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  80270. varyingCount--;
  80271. }
  80272. for (var i = 0; i < varyingCount; i++) {
  80273. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  80274. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  80275. }
  80276. var depCount = 0;
  80277. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  80278. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  80279. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  80280. depCount++;
  80281. }
  80282. if (this.packedFloat) {
  80283. defines += "#define PACKEDFLOAT 1";
  80284. }
  80285. this.blockCompilation = false;
  80286. _super.prototype.updateEffect.call(this, defines, null, null, {
  80287. varyingCount: varyingCount,
  80288. depCount: depCount
  80289. }, onCompiled, onError);
  80290. };
  80291. /**
  80292. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  80293. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  80294. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  80295. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  80296. * The gaps between physical kernels are compensated for in the weighting of the samples
  80297. * @param idealKernel Ideal blur kernel.
  80298. * @return Nearest best kernel.
  80299. */
  80300. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  80301. var v = Math.round(idealKernel);
  80302. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  80303. var k = _a[_i];
  80304. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  80305. return Math.max(k, 3);
  80306. }
  80307. }
  80308. return Math.max(v, 3);
  80309. };
  80310. /**
  80311. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  80312. * @param x The point on the Gaussian distribution to sample.
  80313. * @return the value of the Gaussian function at x.
  80314. */
  80315. BlurPostProcess.prototype._gaussianWeight = function (x) {
  80316. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  80317. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  80318. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  80319. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  80320. // truncated at around 1.3% of peak strength.
  80321. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  80322. var sigma = (1 / 3);
  80323. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  80324. var exponent = -((x * x) / (2.0 * sigma * sigma));
  80325. var weight = (1.0 / denominator) * Math.exp(exponent);
  80326. return weight;
  80327. };
  80328. /**
  80329. * Generates a string that can be used as a floating point number in GLSL.
  80330. * @param x Value to print.
  80331. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  80332. * @return GLSL float string.
  80333. */
  80334. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  80335. if (decimalFigures === void 0) { decimalFigures = 8; }
  80336. return x.toFixed(decimalFigures).replace(/0+$/, '');
  80337. };
  80338. return BlurPostProcess;
  80339. }(BABYLON.PostProcess));
  80340. BABYLON.BlurPostProcess = BlurPostProcess;
  80341. })(BABYLON || (BABYLON = {}));
  80342. //# sourceMappingURL=babylon.blurPostProcess.js.map
  80343. var BABYLON;
  80344. (function (BABYLON) {
  80345. /**
  80346. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  80347. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  80348. * based on samples that have a large difference in distance than the center pixel.
  80349. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  80350. */
  80351. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  80352. __extends(DepthOfFieldBlurPostProcess, _super);
  80353. /**
  80354. * Creates a new instance CircleOfConfusionPostProcess
  80355. * @param name The name of the effect.
  80356. * @param scene The scene the effect belongs to.
  80357. * @param direction The direction the blur should be applied.
  80358. * @param kernel The size of the kernel used to blur.
  80359. * @param options The required width/height ratio to downsize to before computing the render pass.
  80360. * @param camera The camera to apply the render pass to.
  80361. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  80362. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  80363. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  80364. * @param engine The engine which the post process will be applied. (default: current engine)
  80365. * @param reusable If the post process can be reused on the same frame. (default: false)
  80366. * @param textureType Type of textures used when performing the post process. (default: 0)
  80367. * @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)
  80368. */
  80369. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  80370. if (imageToBlur === void 0) { imageToBlur = null; }
  80371. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  80372. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80373. if (blockCompilation === void 0) { blockCompilation = false; }
  80374. 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;
  80375. _this.direction = direction;
  80376. _this.onApplyObservable.add(function (effect) {
  80377. if (imageToBlur != null) {
  80378. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  80379. }
  80380. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  80381. if (scene.activeCamera) {
  80382. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  80383. }
  80384. });
  80385. return _this;
  80386. }
  80387. return DepthOfFieldBlurPostProcess;
  80388. }(BABYLON.BlurPostProcess));
  80389. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  80390. })(BABYLON || (BABYLON = {}));
  80391. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  80392. var BABYLON;
  80393. (function (BABYLON) {
  80394. /**
  80395. * Options to be set when merging outputs from the default pipeline.
  80396. */
  80397. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  80398. function DepthOfFieldMergePostProcessOptions() {
  80399. }
  80400. return DepthOfFieldMergePostProcessOptions;
  80401. }());
  80402. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  80403. /**
  80404. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  80405. */
  80406. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  80407. __extends(DepthOfFieldMergePostProcess, _super);
  80408. /**
  80409. * Creates a new instance of DepthOfFieldMergePostProcess
  80410. * @param name The name of the effect.
  80411. * @param originalFromInput Post process which's input will be used for the merge.
  80412. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  80413. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  80414. * @param options The required width/height ratio to downsize to before computing the render pass.
  80415. * @param camera The camera to apply the render pass to.
  80416. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  80417. * @param engine The engine which the post process will be applied. (default: current engine)
  80418. * @param reusable If the post process can be reused on the same frame. (default: false)
  80419. * @param textureType Type of textures used when performing the post process. (default: 0)
  80420. * @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)
  80421. */
  80422. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  80423. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80424. if (blockCompilation === void 0) { blockCompilation = false; }
  80425. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  80426. _this.blurSteps = blurSteps;
  80427. _this.onApplyObservable.add(function (effect) {
  80428. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  80429. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  80430. blurSteps.forEach(function (step, index) {
  80431. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  80432. });
  80433. });
  80434. if (!blockCompilation) {
  80435. _this.updateEffect();
  80436. }
  80437. return _this;
  80438. }
  80439. /**
  80440. * Updates the effect with the current post process compile time values and recompiles the shader.
  80441. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  80442. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  80443. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  80444. * @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
  80445. * @param onCompiled Called when the shader has been compiled.
  80446. * @param onError Called if there is an error when compiling a shader.
  80447. */
  80448. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  80449. if (defines === void 0) { defines = null; }
  80450. if (uniforms === void 0) { uniforms = null; }
  80451. if (samplers === void 0) { samplers = null; }
  80452. if (!defines) {
  80453. defines = "";
  80454. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  80455. }
  80456. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  80457. };
  80458. return DepthOfFieldMergePostProcess;
  80459. }(BABYLON.PostProcess));
  80460. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  80461. })(BABYLON || (BABYLON = {}));
  80462. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  80463. var BABYLON;
  80464. (function (BABYLON) {
  80465. /**
  80466. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  80467. */
  80468. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  80469. __extends(CircleOfConfusionPostProcess, _super);
  80470. /**
  80471. * Creates a new instance CircleOfConfusionPostProcess
  80472. * @param name The name of the effect.
  80473. * @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.
  80474. * @param options The required width/height ratio to downsize to before computing the render pass.
  80475. * @param camera The camera to apply the render pass to.
  80476. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  80477. * @param engine The engine which the post process will be applied. (default: current engine)
  80478. * @param reusable If the post process can be reused on the same frame. (default: false)
  80479. * @param textureType Type of textures used when performing the post process. (default: 0)
  80480. * @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)
  80481. */
  80482. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  80483. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80484. if (blockCompilation === void 0) { blockCompilation = false; }
  80485. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  80486. /**
  80487. * 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.
  80488. */
  80489. _this.lensSize = 50;
  80490. /**
  80491. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  80492. */
  80493. _this.fStop = 1.4;
  80494. /**
  80495. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  80496. */
  80497. _this.focusDistance = 2000;
  80498. /**
  80499. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  80500. */
  80501. _this.focalLength = 50;
  80502. _this._depthTexture = null;
  80503. _this._depthTexture = depthTexture;
  80504. _this.onApplyObservable.add(function (effect) {
  80505. if (!_this._depthTexture) {
  80506. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  80507. return;
  80508. }
  80509. effect.setTexture("depthSampler", _this._depthTexture);
  80510. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  80511. var aperture = _this.lensSize / _this.fStop;
  80512. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  80513. effect.setFloat('focusDistance', _this.focusDistance);
  80514. effect.setFloat('cocPrecalculation', cocPrecalculation);
  80515. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  80516. });
  80517. return _this;
  80518. }
  80519. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  80520. /**
  80521. * 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.
  80522. */
  80523. set: function (value) {
  80524. this._depthTexture = value;
  80525. },
  80526. enumerable: true,
  80527. configurable: true
  80528. });
  80529. return CircleOfConfusionPostProcess;
  80530. }(BABYLON.PostProcess));
  80531. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  80532. })(BABYLON || (BABYLON = {}));
  80533. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  80534. var BABYLON;
  80535. (function (BABYLON) {
  80536. /**
  80537. * Specifies the level of max blur that should be applied when using the depth of field effect
  80538. */
  80539. var DepthOfFieldEffectBlurLevel;
  80540. (function (DepthOfFieldEffectBlurLevel) {
  80541. /**
  80542. * Subtle blur
  80543. */
  80544. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  80545. /**
  80546. * Medium blur
  80547. */
  80548. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  80549. /**
  80550. * Large blur
  80551. */
  80552. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  80553. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  80554. ;
  80555. /**
  80556. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  80557. */
  80558. var DepthOfFieldEffect = /** @class */ (function (_super) {
  80559. __extends(DepthOfFieldEffect, _super);
  80560. /**
  80561. * Creates a new instance DepthOfFieldEffect
  80562. * @param scene The scene the effect belongs to.
  80563. * @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.
  80564. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  80565. * @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)
  80566. */
  80567. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  80568. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  80569. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  80570. if (blockCompilation === void 0) { blockCompilation = false; }
  80571. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  80572. return _this._effects;
  80573. }, true) || this;
  80574. /**
  80575. * @hidden Internal post processes in depth of field effect
  80576. */
  80577. _this._effects = [];
  80578. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  80579. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  80580. // 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)
  80581. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  80582. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  80583. _this._depthOfFieldBlurY = [];
  80584. _this._depthOfFieldBlurX = [];
  80585. var blurCount = 1;
  80586. var kernelSize = 15;
  80587. switch (blurLevel) {
  80588. case DepthOfFieldEffectBlurLevel.High: {
  80589. blurCount = 3;
  80590. kernelSize = 51;
  80591. break;
  80592. }
  80593. case DepthOfFieldEffectBlurLevel.Medium: {
  80594. blurCount = 2;
  80595. kernelSize = 31;
  80596. break;
  80597. }
  80598. default: {
  80599. kernelSize = 15;
  80600. blurCount = 1;
  80601. break;
  80602. }
  80603. }
  80604. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  80605. var ratio = 1.0;
  80606. for (var i = 0; i < blurCount; i++) {
  80607. 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);
  80608. blurY.autoClear = false;
  80609. ratio = 0.75 / Math.pow(2, i);
  80610. 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);
  80611. blurX.autoClear = false;
  80612. _this._depthOfFieldBlurY.push(blurY);
  80613. _this._depthOfFieldBlurX.push(blurX);
  80614. }
  80615. // Set all post processes on the effect.
  80616. _this._effects = [_this._circleOfConfusion];
  80617. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  80618. _this._effects.push(_this._depthOfFieldBlurY[i]);
  80619. _this._effects.push(_this._depthOfFieldBlurX[i]);
  80620. }
  80621. // Merge blurred images with original image based on circleOfConfusion
  80622. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  80623. _this._dofMerge.autoClear = false;
  80624. _this._effects.push(_this._dofMerge);
  80625. return _this;
  80626. }
  80627. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  80628. get: function () {
  80629. return this._circleOfConfusion.focalLength;
  80630. },
  80631. /**
  80632. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  80633. */
  80634. set: function (value) {
  80635. this._circleOfConfusion.focalLength = value;
  80636. },
  80637. enumerable: true,
  80638. configurable: true
  80639. });
  80640. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  80641. get: function () {
  80642. return this._circleOfConfusion.fStop;
  80643. },
  80644. /**
  80645. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  80646. */
  80647. set: function (value) {
  80648. this._circleOfConfusion.fStop = value;
  80649. },
  80650. enumerable: true,
  80651. configurable: true
  80652. });
  80653. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  80654. get: function () {
  80655. return this._circleOfConfusion.focusDistance;
  80656. },
  80657. /**
  80658. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  80659. */
  80660. set: function (value) {
  80661. this._circleOfConfusion.focusDistance = value;
  80662. },
  80663. enumerable: true,
  80664. configurable: true
  80665. });
  80666. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  80667. get: function () {
  80668. return this._circleOfConfusion.lensSize;
  80669. },
  80670. /**
  80671. * 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.
  80672. */
  80673. set: function (value) {
  80674. this._circleOfConfusion.lensSize = value;
  80675. },
  80676. enumerable: true,
  80677. configurable: true
  80678. });
  80679. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  80680. /**
  80681. * 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.
  80682. */
  80683. set: function (value) {
  80684. this._circleOfConfusion.depthTexture = value;
  80685. },
  80686. enumerable: true,
  80687. configurable: true
  80688. });
  80689. /**
  80690. * Disposes each of the internal effects for a given camera.
  80691. * @param camera The camera to dispose the effect on.
  80692. */
  80693. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  80694. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  80695. this._effects[effectIndex].dispose(camera);
  80696. }
  80697. };
  80698. /**
  80699. * @hidden Internal
  80700. */
  80701. DepthOfFieldEffect.prototype._updateEffects = function () {
  80702. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  80703. this._effects[effectIndex].updateEffect();
  80704. }
  80705. };
  80706. /**
  80707. * Internal
  80708. * @returns if all the contained post processes are ready.
  80709. * @hidden
  80710. */
  80711. DepthOfFieldEffect.prototype._isReady = function () {
  80712. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  80713. if (!this._effects[effectIndex].isReady()) {
  80714. return false;
  80715. }
  80716. }
  80717. return true;
  80718. };
  80719. return DepthOfFieldEffect;
  80720. }(BABYLON.PostProcessRenderEffect));
  80721. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  80722. })(BABYLON || (BABYLON = {}));
  80723. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  80724. var BABYLON;
  80725. (function (BABYLON) {
  80726. /**
  80727. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  80728. */
  80729. var BloomMergePostProcess = /** @class */ (function (_super) {
  80730. __extends(BloomMergePostProcess, _super);
  80731. /**
  80732. * Creates a new instance of @see BloomMergePostProcess
  80733. * @param name The name of the effect.
  80734. * @param originalFromInput Post process which's input will be used for the merge.
  80735. * @param blurred Blurred highlights post process which's output will be used.
  80736. * @param weight Weight of the bloom to be added to the original input.
  80737. * @param options The required width/height ratio to downsize to before computing the render pass.
  80738. * @param camera The camera to apply the render pass to.
  80739. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  80740. * @param engine The engine which the post process will be applied. (default: current engine)
  80741. * @param reusable If the post process can be reused on the same frame. (default: false)
  80742. * @param textureType Type of textures used when performing the post process. (default: 0)
  80743. * @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)
  80744. */
  80745. function BloomMergePostProcess(name, originalFromInput, blurred,
  80746. /** Weight of the bloom to be added to the original input. */
  80747. weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  80748. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80749. if (blockCompilation === void 0) { blockCompilation = false; }
  80750. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  80751. _this.weight = weight;
  80752. _this.onApplyObservable.add(function (effect) {
  80753. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  80754. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  80755. effect.setFloat("bloomWeight", _this.weight);
  80756. });
  80757. if (!blockCompilation) {
  80758. _this.updateEffect();
  80759. }
  80760. return _this;
  80761. }
  80762. return BloomMergePostProcess;
  80763. }(BABYLON.PostProcess));
  80764. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  80765. })(BABYLON || (BABYLON = {}));
  80766. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  80767. var BABYLON;
  80768. (function (BABYLON) {
  80769. /**
  80770. * 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.
  80771. */
  80772. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  80773. __extends(ExtractHighlightsPostProcess, _super);
  80774. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  80775. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80776. if (blockCompilation === void 0) { blockCompilation = false; }
  80777. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  80778. /**
  80779. * The luminance threshold, pixels below this value will be set to black.
  80780. */
  80781. _this.threshold = 0.9;
  80782. /** @hidden */
  80783. _this._exposure = 1;
  80784. /**
  80785. * Post process which has the input texture to be used when performing highlight extraction
  80786. * @hidden
  80787. */
  80788. _this._inputPostProcess = null;
  80789. _this.onApplyObservable.add(function (effect) {
  80790. if (_this._inputPostProcess) {
  80791. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  80792. }
  80793. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  80794. effect.setFloat('exposure', _this._exposure);
  80795. });
  80796. return _this;
  80797. }
  80798. return ExtractHighlightsPostProcess;
  80799. }(BABYLON.PostProcess));
  80800. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  80801. })(BABYLON || (BABYLON = {}));
  80802. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  80803. var BABYLON;
  80804. (function (BABYLON) {
  80805. /**
  80806. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  80807. */
  80808. var BloomEffect = /** @class */ (function (_super) {
  80809. __extends(BloomEffect, _super);
  80810. /**
  80811. * Creates a new instance of @see BloomEffect
  80812. * @param scene The scene the effect belongs to.
  80813. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  80814. * @param bloomKernel The size of the kernel to be used when applying the blur.
  80815. * @param bloomWeight The the strength of bloom.
  80816. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  80817. * @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)
  80818. */
  80819. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  80820. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  80821. if (blockCompilation === void 0) { blockCompilation = false; }
  80822. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  80823. return _this._effects;
  80824. }, true) || this;
  80825. _this.bloomScale = bloomScale;
  80826. /**
  80827. * @hidden Internal
  80828. */
  80829. _this._effects = [];
  80830. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  80831. _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);
  80832. _this._blurX.alwaysForcePOT = true;
  80833. _this._blurX.autoClear = false;
  80834. _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);
  80835. _this._blurY.alwaysForcePOT = true;
  80836. _this._blurY.autoClear = false;
  80837. _this.kernel = bloomKernel;
  80838. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  80839. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  80840. _this._merge.autoClear = false;
  80841. _this._effects.push(_this._merge);
  80842. return _this;
  80843. }
  80844. Object.defineProperty(BloomEffect.prototype, "threshold", {
  80845. /**
  80846. * The luminance threshold to find bright areas of the image to bloom.
  80847. */
  80848. get: function () {
  80849. return this._downscale.threshold;
  80850. },
  80851. set: function (value) {
  80852. this._downscale.threshold = value;
  80853. },
  80854. enumerable: true,
  80855. configurable: true
  80856. });
  80857. Object.defineProperty(BloomEffect.prototype, "weight", {
  80858. /**
  80859. * The strength of the bloom.
  80860. */
  80861. get: function () {
  80862. return this._merge.weight;
  80863. },
  80864. set: function (value) {
  80865. this._merge.weight = value;
  80866. },
  80867. enumerable: true,
  80868. configurable: true
  80869. });
  80870. Object.defineProperty(BloomEffect.prototype, "kernel", {
  80871. /**
  80872. * Specifies the size of the bloom blur kernel, relative to the final output size
  80873. */
  80874. get: function () {
  80875. return this._blurX.kernel / this.bloomScale;
  80876. },
  80877. set: function (value) {
  80878. this._blurX.kernel = value * this.bloomScale;
  80879. this._blurY.kernel = value * this.bloomScale;
  80880. },
  80881. enumerable: true,
  80882. configurable: true
  80883. });
  80884. /**
  80885. * Disposes each of the internal effects for a given camera.
  80886. * @param camera The camera to dispose the effect on.
  80887. */
  80888. BloomEffect.prototype.disposeEffects = function (camera) {
  80889. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  80890. this._effects[effectIndex].dispose(camera);
  80891. }
  80892. };
  80893. /**
  80894. * @hidden Internal
  80895. */
  80896. BloomEffect.prototype._updateEffects = function () {
  80897. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  80898. this._effects[effectIndex].updateEffect();
  80899. }
  80900. };
  80901. /**
  80902. * Internal
  80903. * @returns if all the contained post processes are ready.
  80904. * @hidden
  80905. */
  80906. BloomEffect.prototype._isReady = function () {
  80907. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  80908. if (!this._effects[effectIndex].isReady()) {
  80909. return false;
  80910. }
  80911. }
  80912. return true;
  80913. };
  80914. return BloomEffect;
  80915. }(BABYLON.PostProcessRenderEffect));
  80916. BABYLON.BloomEffect = BloomEffect;
  80917. })(BABYLON || (BABYLON = {}));
  80918. //# sourceMappingURL=babylon.bloomEffect.js.map
  80919. var BABYLON;
  80920. (function (BABYLON) {
  80921. /**
  80922. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  80923. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  80924. */
  80925. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  80926. __extends(DefaultRenderingPipeline, _super);
  80927. /**
  80928. * @constructor
  80929. * @param {string} name - The rendering pipeline name (default: "")
  80930. * @param {boolean} hdr - If high dynamic range textures should be used (default: true)
  80931. * @param {BABYLON.Scene} scene - The scene linked to this pipeline (default: the last created scene)
  80932. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  80933. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  80934. */
  80935. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  80936. if (name === void 0) { name = ""; }
  80937. if (hdr === void 0) { hdr = true; }
  80938. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  80939. if (automaticBuild === void 0) { automaticBuild = true; }
  80940. var _this = _super.call(this, scene.getEngine(), name) || this;
  80941. _this._camerasToBeAttached = [];
  80942. /**
  80943. * ID of the sharpen post process,
  80944. */
  80945. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  80946. /**
  80947. * ID of the image processing post process;
  80948. */
  80949. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  80950. /**
  80951. * ID of the Fast Approximate Anti-Aliasing post process;
  80952. */
  80953. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  80954. /**
  80955. * ID of the chromatic aberration post process,
  80956. */
  80957. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  80958. /**
  80959. * ID of the grain post process
  80960. */
  80961. _this.GrainPostProcessId = "GrainPostProcessEffect";
  80962. /**
  80963. * Glow post process which adds a glow to emmisive areas of the image
  80964. */
  80965. _this._glowLayer = null;
  80966. /**
  80967. * Animations which can be used to tweak settings over a period of time
  80968. */
  80969. _this.animations = [];
  80970. _this._imageProcessingConfigurationObserver = null;
  80971. // Values
  80972. _this._sharpenEnabled = false;
  80973. _this._bloomEnabled = false;
  80974. _this._depthOfFieldEnabled = false;
  80975. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  80976. _this._fxaaEnabled = false;
  80977. _this._imageProcessingEnabled = true;
  80978. _this._bloomScale = 0.5;
  80979. _this._chromaticAberrationEnabled = false;
  80980. _this._grainEnabled = false;
  80981. _this._buildAllowed = true;
  80982. _this._resizeObserver = null;
  80983. _this._hardwareScaleLevel = 1.0;
  80984. _this._bloomKernel = 64;
  80985. /**
  80986. * Specifies the weight of the bloom in the final rendering
  80987. */
  80988. _this._bloomWeight = 0.15;
  80989. /**
  80990. * Specifies the luma threshold for the area that will be blurred by the bloom
  80991. */
  80992. _this._bloomThreshold = 0.9;
  80993. _this._samples = 1;
  80994. _this._hasCleared = false;
  80995. _this._prevPostProcess = null;
  80996. _this._prevPrevPostProcess = null;
  80997. _this._depthOfFieldSceneObserver = null;
  80998. _this._cameras = cameras || scene.cameras;
  80999. _this._cameras = _this._cameras.slice();
  81000. _this._camerasToBeAttached = _this._cameras.slice();
  81001. _this._buildAllowed = automaticBuild;
  81002. // Initialize
  81003. _this._scene = scene;
  81004. var caps = _this._scene.getEngine().getCaps();
  81005. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  81006. // Misc
  81007. if (_this._hdr) {
  81008. if (caps.textureHalfFloatRender) {
  81009. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  81010. }
  81011. else if (caps.textureFloatRender) {
  81012. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  81013. }
  81014. }
  81015. else {
  81016. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  81017. }
  81018. // Attach
  81019. scene.postProcessRenderPipelineManager.addPipeline(_this);
  81020. var engine = _this._scene.getEngine();
  81021. // Create post processes before hand so they can be modified before enabled.
  81022. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  81023. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  81024. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  81025. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  81026. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  81027. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  81028. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  81029. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  81030. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  81031. _this._resizeObserver = engine.onResizeObservable.add(function () {
  81032. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  81033. _this.bloomKernel = _this.bloomKernel;
  81034. });
  81035. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  81036. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  81037. });
  81038. _this._buildPipeline();
  81039. return _this;
  81040. }
  81041. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  81042. get: function () {
  81043. return this._sharpenEnabled;
  81044. },
  81045. /**
  81046. * Enable or disable the sharpen process from the pipeline
  81047. */
  81048. set: function (enabled) {
  81049. if (this._sharpenEnabled === enabled) {
  81050. return;
  81051. }
  81052. this._sharpenEnabled = enabled;
  81053. this._buildPipeline();
  81054. },
  81055. enumerable: true,
  81056. configurable: true
  81057. });
  81058. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  81059. /**
  81060. * Specifies the size of the bloom blur kernel, relative to the final output size
  81061. */
  81062. get: function () {
  81063. return this._bloomKernel;
  81064. },
  81065. set: function (value) {
  81066. this._bloomKernel = value;
  81067. this.bloom.kernel = value / this._hardwareScaleLevel;
  81068. },
  81069. enumerable: true,
  81070. configurable: true
  81071. });
  81072. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  81073. get: function () {
  81074. return this._bloomWeight;
  81075. },
  81076. /**
  81077. * The strength of the bloom.
  81078. */
  81079. set: function (value) {
  81080. if (this._bloomWeight === value) {
  81081. return;
  81082. }
  81083. this.bloom.weight = value;
  81084. this._bloomWeight = value;
  81085. },
  81086. enumerable: true,
  81087. configurable: true
  81088. });
  81089. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  81090. get: function () {
  81091. return this._bloomThreshold;
  81092. },
  81093. /**
  81094. * The strength of the bloom.
  81095. */
  81096. set: function (value) {
  81097. if (this._bloomThreshold === value) {
  81098. return;
  81099. }
  81100. this.bloom.threshold = value;
  81101. this._bloomThreshold = value;
  81102. },
  81103. enumerable: true,
  81104. configurable: true
  81105. });
  81106. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  81107. get: function () {
  81108. return this._bloomScale;
  81109. },
  81110. /**
  81111. * The scale of the bloom, lower value will provide better performance.
  81112. */
  81113. set: function (value) {
  81114. if (this._bloomScale === value) {
  81115. return;
  81116. }
  81117. this._bloomScale = value;
  81118. // recreate bloom and dispose old as this setting is not dynamic
  81119. this._rebuildBloom();
  81120. this._buildPipeline();
  81121. },
  81122. enumerable: true,
  81123. configurable: true
  81124. });
  81125. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  81126. get: function () {
  81127. return this._bloomEnabled;
  81128. },
  81129. /**
  81130. * Enable or disable the bloom from the pipeline
  81131. */
  81132. set: function (enabled) {
  81133. if (this._bloomEnabled === enabled) {
  81134. return;
  81135. }
  81136. this._bloomEnabled = enabled;
  81137. this._buildPipeline();
  81138. },
  81139. enumerable: true,
  81140. configurable: true
  81141. });
  81142. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  81143. // recreate bloom and dispose old as this setting is not dynamic
  81144. var oldBloom = this.bloom;
  81145. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  81146. this.bloom.threshold = oldBloom.threshold;
  81147. for (var i = 0; i < this._cameras.length; i++) {
  81148. oldBloom.disposeEffects(this._cameras[i]);
  81149. }
  81150. };
  81151. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  81152. /**
  81153. * If the depth of field is enabled.
  81154. */
  81155. get: function () {
  81156. return this._depthOfFieldEnabled;
  81157. },
  81158. set: function (enabled) {
  81159. if (this._depthOfFieldEnabled === enabled) {
  81160. return;
  81161. }
  81162. this._depthOfFieldEnabled = enabled;
  81163. this._buildPipeline();
  81164. },
  81165. enumerable: true,
  81166. configurable: true
  81167. });
  81168. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  81169. /**
  81170. * Blur level of the depth of field effect. (Higher blur will effect performance)
  81171. */
  81172. get: function () {
  81173. return this._depthOfFieldBlurLevel;
  81174. },
  81175. set: function (value) {
  81176. if (this._depthOfFieldBlurLevel === value) {
  81177. return;
  81178. }
  81179. this._depthOfFieldBlurLevel = value;
  81180. // recreate dof and dispose old as this setting is not dynamic
  81181. var oldDof = this.depthOfField;
  81182. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  81183. this.depthOfField.focalLength = oldDof.focalLength;
  81184. this.depthOfField.focusDistance = oldDof.focusDistance;
  81185. this.depthOfField.fStop = oldDof.fStop;
  81186. this.depthOfField.lensSize = oldDof.lensSize;
  81187. for (var i = 0; i < this._cameras.length; i++) {
  81188. oldDof.disposeEffects(this._cameras[i]);
  81189. }
  81190. this._buildPipeline();
  81191. },
  81192. enumerable: true,
  81193. configurable: true
  81194. });
  81195. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  81196. get: function () {
  81197. return this._fxaaEnabled;
  81198. },
  81199. /**
  81200. * If the anti aliasing is enabled.
  81201. */
  81202. set: function (enabled) {
  81203. if (this._fxaaEnabled === enabled) {
  81204. return;
  81205. }
  81206. this._fxaaEnabled = enabled;
  81207. this._buildPipeline();
  81208. },
  81209. enumerable: true,
  81210. configurable: true
  81211. });
  81212. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  81213. get: function () {
  81214. return this._samples;
  81215. },
  81216. /**
  81217. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  81218. */
  81219. set: function (sampleCount) {
  81220. if (this._samples === sampleCount) {
  81221. return;
  81222. }
  81223. this._samples = sampleCount;
  81224. this._buildPipeline();
  81225. },
  81226. enumerable: true,
  81227. configurable: true
  81228. });
  81229. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  81230. get: function () {
  81231. return this._imageProcessingEnabled;
  81232. },
  81233. /**
  81234. * If image processing is enabled.
  81235. */
  81236. set: function (enabled) {
  81237. if (this._imageProcessingEnabled === enabled) {
  81238. return;
  81239. }
  81240. this._imageProcessingEnabled = enabled;
  81241. this._buildPipeline();
  81242. },
  81243. enumerable: true,
  81244. configurable: true
  81245. });
  81246. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  81247. get: function () {
  81248. return this._glowLayer == null;
  81249. },
  81250. /**
  81251. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  81252. */
  81253. set: function (enabled) {
  81254. if (enabled && !this._glowLayer) {
  81255. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  81256. }
  81257. else if (!enabled && this._glowLayer) {
  81258. this._glowLayer.dispose();
  81259. this._glowLayer = null;
  81260. }
  81261. },
  81262. enumerable: true,
  81263. configurable: true
  81264. });
  81265. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  81266. get: function () {
  81267. return this._chromaticAberrationEnabled;
  81268. },
  81269. /**
  81270. * Enable or disable the chromaticAberration process from the pipeline
  81271. */
  81272. set: function (enabled) {
  81273. if (this._chromaticAberrationEnabled === enabled) {
  81274. return;
  81275. }
  81276. this._chromaticAberrationEnabled = enabled;
  81277. this._buildPipeline();
  81278. },
  81279. enumerable: true,
  81280. configurable: true
  81281. });
  81282. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  81283. get: function () {
  81284. return this._grainEnabled;
  81285. },
  81286. /**
  81287. * Enable or disable the grain process from the pipeline
  81288. */
  81289. set: function (enabled) {
  81290. if (this._grainEnabled === enabled) {
  81291. return;
  81292. }
  81293. this._grainEnabled = enabled;
  81294. this._buildPipeline();
  81295. },
  81296. enumerable: true,
  81297. configurable: true
  81298. });
  81299. /**
  81300. * Force the compilation of the entire pipeline.
  81301. */
  81302. DefaultRenderingPipeline.prototype.prepare = function () {
  81303. var previousState = this._buildAllowed;
  81304. this._buildAllowed = true;
  81305. this._buildPipeline();
  81306. this._buildAllowed = previousState;
  81307. };
  81308. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  81309. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  81310. if (this._hasCleared) {
  81311. postProcess.autoClear = false;
  81312. }
  81313. else {
  81314. postProcess.autoClear = true;
  81315. this._scene.autoClear = false;
  81316. this._hasCleared = true;
  81317. }
  81318. if (!skipTextureSharing) {
  81319. if (this._prevPrevPostProcess) {
  81320. postProcess.shareOutputWith(this._prevPrevPostProcess);
  81321. }
  81322. else {
  81323. postProcess.useOwnOutput();
  81324. }
  81325. if (this._prevPostProcess) {
  81326. this._prevPrevPostProcess = this._prevPostProcess;
  81327. }
  81328. this._prevPostProcess = postProcess;
  81329. }
  81330. };
  81331. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  81332. var _this = this;
  81333. if (!this._buildAllowed) {
  81334. return;
  81335. }
  81336. this._scene.autoClear = true;
  81337. var engine = this._scene.getEngine();
  81338. this._disposePostProcesses();
  81339. if (this._cameras !== null) {
  81340. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  81341. // get back cameras to be used to reattach pipeline
  81342. this._cameras = this._camerasToBeAttached.slice();
  81343. }
  81344. this._reset();
  81345. this._prevPostProcess = null;
  81346. this._prevPrevPostProcess = null;
  81347. this._hasCleared = false;
  81348. if (this.depthOfFieldEnabled) {
  81349. // Multi camera suport
  81350. if (this._cameras.length > 1) {
  81351. for (var _i = 0, _a = this._cameras; _i < _a.length; _i++) {
  81352. var camera = _a[_i];
  81353. var depthRenderer = this._scene.enableDepthRenderer(camera);
  81354. depthRenderer.useOnlyInActiveCamera = true;
  81355. }
  81356. this._depthOfFieldSceneObserver = this._scene.onAfterRenderTargetsRenderObservable.add(function (scene) {
  81357. if (_this._cameras.indexOf(scene.activeCamera) > -1) {
  81358. _this.depthOfField.depthTexture = scene.enableDepthRenderer(scene.activeCamera).getDepthMap();
  81359. }
  81360. });
  81361. }
  81362. else {
  81363. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  81364. var depthRenderer = this._scene.enableDepthRenderer(this._cameras[0]);
  81365. this.depthOfField.depthTexture = depthRenderer.getDepthMap();
  81366. }
  81367. if (!this.depthOfField._isReady()) {
  81368. this.depthOfField._updateEffects();
  81369. }
  81370. this.addEffect(this.depthOfField);
  81371. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  81372. }
  81373. else {
  81374. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  81375. }
  81376. if (this.bloomEnabled) {
  81377. if (!this.bloom._isReady()) {
  81378. this.bloom._updateEffects();
  81379. }
  81380. this.addEffect(this.bloom);
  81381. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  81382. }
  81383. if (this._imageProcessingEnabled) {
  81384. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  81385. if (this._hdr) {
  81386. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  81387. this._setAutoClearAndTextureSharing(this.imageProcessing);
  81388. }
  81389. else {
  81390. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  81391. }
  81392. }
  81393. if (this.sharpenEnabled) {
  81394. if (!this.sharpen.isReady()) {
  81395. this.sharpen.updateEffect();
  81396. }
  81397. this.addEffect(this._sharpenEffect);
  81398. this._setAutoClearAndTextureSharing(this.sharpen);
  81399. }
  81400. if (this.grainEnabled) {
  81401. if (!this.grain.isReady()) {
  81402. this.grain.updateEffect();
  81403. }
  81404. this.addEffect(this._grainEffect);
  81405. this._setAutoClearAndTextureSharing(this.grain);
  81406. }
  81407. if (this.chromaticAberrationEnabled) {
  81408. if (!this.chromaticAberration.isReady()) {
  81409. this.chromaticAberration.updateEffect();
  81410. }
  81411. this.addEffect(this._chromaticAberrationEffect);
  81412. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  81413. }
  81414. if (this.fxaaEnabled) {
  81415. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  81416. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  81417. this._setAutoClearAndTextureSharing(this.fxaa, true);
  81418. }
  81419. if (this._cameras !== null) {
  81420. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  81421. }
  81422. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  81423. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  81424. }
  81425. };
  81426. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  81427. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  81428. for (var i = 0; i < this._cameras.length; i++) {
  81429. var camera = this._cameras[i];
  81430. if (this.imageProcessing) {
  81431. this.imageProcessing.dispose(camera);
  81432. }
  81433. if (this.fxaa) {
  81434. this.fxaa.dispose(camera);
  81435. }
  81436. // These are created in the constructor and should not be disposed on every pipeline change
  81437. if (disposeNonRecreated) {
  81438. if (this.sharpen) {
  81439. this.sharpen.dispose(camera);
  81440. }
  81441. if (this.depthOfField) {
  81442. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  81443. this.depthOfField.disposeEffects(camera);
  81444. }
  81445. if (this.bloom) {
  81446. this.bloom.disposeEffects(camera);
  81447. }
  81448. if (this.chromaticAberration) {
  81449. this.chromaticAberration.dispose(camera);
  81450. }
  81451. if (this.grain) {
  81452. this.grain.dispose(camera);
  81453. }
  81454. if (this._glowLayer) {
  81455. this._glowLayer.dispose();
  81456. }
  81457. }
  81458. }
  81459. this.imageProcessing = null;
  81460. this.fxaa = null;
  81461. if (disposeNonRecreated) {
  81462. this.sharpen = null;
  81463. this._sharpenEffect = null;
  81464. this.depthOfField = null;
  81465. this.bloom = null;
  81466. this.chromaticAberration = null;
  81467. this._chromaticAberrationEffect = null;
  81468. this.grain = null;
  81469. this._grainEffect = null;
  81470. this._glowLayer = null;
  81471. }
  81472. };
  81473. /**
  81474. * Adds a camera to the pipeline
  81475. * @param camera the camera to be added
  81476. */
  81477. DefaultRenderingPipeline.prototype.addCamera = function (camera) {
  81478. this._camerasToBeAttached.push(camera);
  81479. this._buildPipeline();
  81480. };
  81481. /**
  81482. * Removes a camera from the pipeline
  81483. * @param camera the camera to remove
  81484. */
  81485. DefaultRenderingPipeline.prototype.removeCamera = function (camera) {
  81486. var index = this._camerasToBeAttached.indexOf(camera);
  81487. this._camerasToBeAttached.splice(index, 1);
  81488. this._buildPipeline();
  81489. };
  81490. /**
  81491. * Dispose of the pipeline and stop all post processes
  81492. */
  81493. DefaultRenderingPipeline.prototype.dispose = function () {
  81494. this._disposePostProcesses(true);
  81495. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  81496. this._scene.autoClear = true;
  81497. if (this._resizeObserver) {
  81498. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  81499. this._resizeObserver = null;
  81500. }
  81501. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  81502. _super.prototype.dispose.call(this);
  81503. };
  81504. /**
  81505. * Serialize the rendering pipeline (Used when exporting)
  81506. * @returns the serialized object
  81507. */
  81508. DefaultRenderingPipeline.prototype.serialize = function () {
  81509. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  81510. serializationObject.customType = "DefaultRenderingPipeline";
  81511. return serializationObject;
  81512. };
  81513. /**
  81514. * Parse the serialized pipeline
  81515. * @param source Source pipeline.
  81516. * @param scene The scene to load the pipeline to.
  81517. * @param rootUrl The URL of the serialized pipeline.
  81518. * @returns An instantiated pipeline from the serialized object.
  81519. */
  81520. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  81521. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  81522. };
  81523. __decorate([
  81524. BABYLON.serialize()
  81525. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  81526. __decorate([
  81527. BABYLON.serialize()
  81528. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  81529. __decorate([
  81530. BABYLON.serialize()
  81531. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  81532. __decorate([
  81533. BABYLON.serialize()
  81534. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  81535. __decorate([
  81536. BABYLON.serialize()
  81537. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  81538. __decorate([
  81539. BABYLON.serialize()
  81540. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  81541. __decorate([
  81542. BABYLON.serialize()
  81543. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  81544. __decorate([
  81545. BABYLON.serialize()
  81546. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  81547. __decorate([
  81548. BABYLON.serialize()
  81549. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  81550. __decorate([
  81551. BABYLON.serialize()
  81552. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  81553. __decorate([
  81554. BABYLON.serialize()
  81555. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  81556. __decorate([
  81557. BABYLON.serialize()
  81558. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  81559. __decorate([
  81560. BABYLON.serialize()
  81561. ], DefaultRenderingPipeline.prototype, "samples", null);
  81562. __decorate([
  81563. BABYLON.serialize()
  81564. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  81565. __decorate([
  81566. BABYLON.serialize()
  81567. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  81568. __decorate([
  81569. BABYLON.serialize()
  81570. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  81571. __decorate([
  81572. BABYLON.serialize()
  81573. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  81574. return DefaultRenderingPipeline;
  81575. }(BABYLON.PostProcessRenderPipeline));
  81576. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  81577. })(BABYLON || (BABYLON = {}));
  81578. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  81579. var BABYLON;
  81580. (function (BABYLON) {
  81581. /**
  81582. * @hidden
  81583. */
  81584. var ImageProcessingConfigurationDefines = /** @class */ (function (_super) {
  81585. __extends(ImageProcessingConfigurationDefines, _super);
  81586. function ImageProcessingConfigurationDefines() {
  81587. var _this = _super.call(this) || this;
  81588. _this.IMAGEPROCESSING = false;
  81589. _this.VIGNETTE = false;
  81590. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  81591. _this.VIGNETTEBLENDMODEOPAQUE = false;
  81592. _this.TONEMAPPING = false;
  81593. _this.TONEMAPPING_ACES = false;
  81594. _this.CONTRAST = false;
  81595. _this.COLORCURVES = false;
  81596. _this.COLORGRADING = false;
  81597. _this.COLORGRADING3D = false;
  81598. _this.SAMPLER3DGREENDEPTH = false;
  81599. _this.SAMPLER3DBGRMAP = false;
  81600. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  81601. _this.EXPOSURE = false;
  81602. _this.rebuild();
  81603. return _this;
  81604. }
  81605. return ImageProcessingConfigurationDefines;
  81606. }(BABYLON.MaterialDefines));
  81607. BABYLON.ImageProcessingConfigurationDefines = ImageProcessingConfigurationDefines;
  81608. /**
  81609. * This groups together the common properties used for image processing either in direct forward pass
  81610. * or through post processing effect depending on the use of the image processing pipeline in your scene
  81611. * or not.
  81612. */
  81613. var ImageProcessingConfiguration = /** @class */ (function () {
  81614. function ImageProcessingConfiguration() {
  81615. /**
  81616. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  81617. */
  81618. this.colorCurves = new BABYLON.ColorCurves();
  81619. this._colorCurvesEnabled = false;
  81620. this._colorGradingEnabled = false;
  81621. this._colorGradingWithGreenDepth = true;
  81622. this._colorGradingBGR = true;
  81623. /** @hidden */
  81624. this._exposure = 1.0;
  81625. this._toneMappingEnabled = false;
  81626. this._toneMappingType = ImageProcessingConfiguration.TONEMAPPING_STANDARD;
  81627. this._contrast = 1.0;
  81628. /**
  81629. * Vignette stretch size.
  81630. */
  81631. this.vignetteStretch = 0;
  81632. /**
  81633. * Vignette centre X Offset.
  81634. */
  81635. this.vignetteCentreX = 0;
  81636. /**
  81637. * Vignette centre Y Offset.
  81638. */
  81639. this.vignetteCentreY = 0;
  81640. /**
  81641. * Vignette weight or intensity of the vignette effect.
  81642. */
  81643. this.vignetteWeight = 1.5;
  81644. /**
  81645. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  81646. * if vignetteEnabled is set to true.
  81647. */
  81648. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  81649. /**
  81650. * Camera field of view used by the Vignette effect.
  81651. */
  81652. this.vignetteCameraFov = 0.5;
  81653. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  81654. this._vignetteEnabled = false;
  81655. this._applyByPostProcess = false;
  81656. this._isEnabled = true;
  81657. /**
  81658. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  81659. */
  81660. this.onUpdateParameters = new BABYLON.Observable();
  81661. }
  81662. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  81663. /**
  81664. * Gets wether the color curves effect is enabled.
  81665. */
  81666. get: function () {
  81667. return this._colorCurvesEnabled;
  81668. },
  81669. /**
  81670. * Sets wether the color curves effect is enabled.
  81671. */
  81672. set: function (value) {
  81673. if (this._colorCurvesEnabled === value) {
  81674. return;
  81675. }
  81676. this._colorCurvesEnabled = value;
  81677. this._updateParameters();
  81678. },
  81679. enumerable: true,
  81680. configurable: true
  81681. });
  81682. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  81683. /**
  81684. * Gets wether the color grading effect is enabled.
  81685. */
  81686. get: function () {
  81687. return this._colorGradingEnabled;
  81688. },
  81689. /**
  81690. * Sets wether the color grading effect is enabled.
  81691. */
  81692. set: function (value) {
  81693. if (this._colorGradingEnabled === value) {
  81694. return;
  81695. }
  81696. this._colorGradingEnabled = value;
  81697. this._updateParameters();
  81698. },
  81699. enumerable: true,
  81700. configurable: true
  81701. });
  81702. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  81703. /**
  81704. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  81705. */
  81706. get: function () {
  81707. return this._colorGradingWithGreenDepth;
  81708. },
  81709. /**
  81710. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  81711. */
  81712. set: function (value) {
  81713. if (this._colorGradingWithGreenDepth === value) {
  81714. return;
  81715. }
  81716. this._colorGradingWithGreenDepth = value;
  81717. this._updateParameters();
  81718. },
  81719. enumerable: true,
  81720. configurable: true
  81721. });
  81722. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  81723. /**
  81724. * Gets wether the color grading texture contains BGR values.
  81725. */
  81726. get: function () {
  81727. return this._colorGradingBGR;
  81728. },
  81729. /**
  81730. * Sets wether the color grading texture contains BGR values.
  81731. */
  81732. set: function (value) {
  81733. if (this._colorGradingBGR === value) {
  81734. return;
  81735. }
  81736. this._colorGradingBGR = value;
  81737. this._updateParameters();
  81738. },
  81739. enumerable: true,
  81740. configurable: true
  81741. });
  81742. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  81743. /**
  81744. * Gets the Exposure used in the effect.
  81745. */
  81746. get: function () {
  81747. return this._exposure;
  81748. },
  81749. /**
  81750. * Sets the Exposure used in the effect.
  81751. */
  81752. set: function (value) {
  81753. if (this._exposure === value) {
  81754. return;
  81755. }
  81756. this._exposure = value;
  81757. this._updateParameters();
  81758. },
  81759. enumerable: true,
  81760. configurable: true
  81761. });
  81762. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  81763. /**
  81764. * Gets wether the tone mapping effect is enabled.
  81765. */
  81766. get: function () {
  81767. return this._toneMappingEnabled;
  81768. },
  81769. /**
  81770. * Sets wether the tone mapping effect is enabled.
  81771. */
  81772. set: function (value) {
  81773. if (this._toneMappingEnabled === value) {
  81774. return;
  81775. }
  81776. this._toneMappingEnabled = value;
  81777. this._updateParameters();
  81778. },
  81779. enumerable: true,
  81780. configurable: true
  81781. });
  81782. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingType", {
  81783. /**
  81784. * Gets the type of tone mapping effect.
  81785. */
  81786. get: function () {
  81787. return this._toneMappingType;
  81788. },
  81789. /**
  81790. * Sets the type of tone mapping effect used in BabylonJS.
  81791. */
  81792. set: function (value) {
  81793. if (this._toneMappingType === value) {
  81794. return;
  81795. }
  81796. this._toneMappingType = value;
  81797. this._updateParameters();
  81798. },
  81799. enumerable: true,
  81800. configurable: true
  81801. });
  81802. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  81803. /**
  81804. * Gets the contrast used in the effect.
  81805. */
  81806. get: function () {
  81807. return this._contrast;
  81808. },
  81809. /**
  81810. * Sets the contrast used in the effect.
  81811. */
  81812. set: function (value) {
  81813. if (this._contrast === value) {
  81814. return;
  81815. }
  81816. this._contrast = value;
  81817. this._updateParameters();
  81818. },
  81819. enumerable: true,
  81820. configurable: true
  81821. });
  81822. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  81823. /**
  81824. * Gets the vignette blend mode allowing different kind of effect.
  81825. */
  81826. get: function () {
  81827. return this._vignetteBlendMode;
  81828. },
  81829. /**
  81830. * Sets the vignette blend mode allowing different kind of effect.
  81831. */
  81832. set: function (value) {
  81833. if (this._vignetteBlendMode === value) {
  81834. return;
  81835. }
  81836. this._vignetteBlendMode = value;
  81837. this._updateParameters();
  81838. },
  81839. enumerable: true,
  81840. configurable: true
  81841. });
  81842. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  81843. /**
  81844. * Gets wether the vignette effect is enabled.
  81845. */
  81846. get: function () {
  81847. return this._vignetteEnabled;
  81848. },
  81849. /**
  81850. * Sets wether the vignette effect is enabled.
  81851. */
  81852. set: function (value) {
  81853. if (this._vignetteEnabled === value) {
  81854. return;
  81855. }
  81856. this._vignetteEnabled = value;
  81857. this._updateParameters();
  81858. },
  81859. enumerable: true,
  81860. configurable: true
  81861. });
  81862. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  81863. /**
  81864. * Gets wether the image processing is applied through a post process or not.
  81865. */
  81866. get: function () {
  81867. return this._applyByPostProcess;
  81868. },
  81869. /**
  81870. * Sets wether the image processing is applied through a post process or not.
  81871. */
  81872. set: function (value) {
  81873. if (this._applyByPostProcess === value) {
  81874. return;
  81875. }
  81876. this._applyByPostProcess = value;
  81877. this._updateParameters();
  81878. },
  81879. enumerable: true,
  81880. configurable: true
  81881. });
  81882. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  81883. /**
  81884. * Gets wether the image processing is enabled or not.
  81885. */
  81886. get: function () {
  81887. return this._isEnabled;
  81888. },
  81889. /**
  81890. * Sets wether the image processing is enabled or not.
  81891. */
  81892. set: function (value) {
  81893. if (this._isEnabled === value) {
  81894. return;
  81895. }
  81896. this._isEnabled = value;
  81897. this._updateParameters();
  81898. },
  81899. enumerable: true,
  81900. configurable: true
  81901. });
  81902. /**
  81903. * Method called each time the image processing information changes requires to recompile the effect.
  81904. */
  81905. ImageProcessingConfiguration.prototype._updateParameters = function () {
  81906. this.onUpdateParameters.notifyObservers(this);
  81907. };
  81908. ImageProcessingConfiguration.prototype.getClassName = function () {
  81909. return "ImageProcessingConfiguration";
  81910. };
  81911. /**
  81912. * Prepare the list of uniforms associated with the Image Processing effects.
  81913. * @param uniformsList The list of uniforms used in the effect
  81914. * @param defines the list of defines currently in use
  81915. */
  81916. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  81917. if (defines.EXPOSURE) {
  81918. uniforms.push("exposureLinear");
  81919. }
  81920. if (defines.CONTRAST) {
  81921. uniforms.push("contrast");
  81922. }
  81923. if (defines.COLORGRADING) {
  81924. uniforms.push("colorTransformSettings");
  81925. }
  81926. if (defines.VIGNETTE) {
  81927. uniforms.push("vInverseScreenSize");
  81928. uniforms.push("vignetteSettings1");
  81929. uniforms.push("vignetteSettings2");
  81930. }
  81931. if (defines.COLORCURVES) {
  81932. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  81933. }
  81934. };
  81935. /**
  81936. * Prepare the list of samplers associated with the Image Processing effects.
  81937. * @param uniformsList The list of uniforms used in the effect
  81938. * @param defines the list of defines currently in use
  81939. */
  81940. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  81941. if (defines.COLORGRADING) {
  81942. samplersList.push("txColorTransform");
  81943. }
  81944. };
  81945. /**
  81946. * Prepare the list of defines associated to the shader.
  81947. * @param defines the list of defines to complete
  81948. */
  81949. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  81950. if (forPostProcess === void 0) { forPostProcess = false; }
  81951. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  81952. defines.VIGNETTE = false;
  81953. defines.TONEMAPPING = false;
  81954. defines.TONEMAPPING_ACES = false;
  81955. defines.CONTRAST = false;
  81956. defines.EXPOSURE = false;
  81957. defines.COLORCURVES = false;
  81958. defines.COLORGRADING = false;
  81959. defines.COLORGRADING3D = false;
  81960. defines.IMAGEPROCESSING = false;
  81961. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  81962. return;
  81963. }
  81964. defines.VIGNETTE = this.vignetteEnabled;
  81965. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  81966. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  81967. defines.TONEMAPPING = this.toneMappingEnabled;
  81968. switch (this._toneMappingType) {
  81969. case ImageProcessingConfiguration.TONEMAPPING_ACES:
  81970. defines.TONEMAPPING_ACES = true;
  81971. break;
  81972. }
  81973. defines.CONTRAST = (this.contrast !== 1.0);
  81974. defines.EXPOSURE = (this.exposure !== 1.0);
  81975. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  81976. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  81977. if (defines.COLORGRADING) {
  81978. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  81979. }
  81980. else {
  81981. defines.COLORGRADING3D = false;
  81982. }
  81983. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  81984. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  81985. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  81986. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  81987. };
  81988. /**
  81989. * Returns true if all the image processing information are ready.
  81990. */
  81991. ImageProcessingConfiguration.prototype.isReady = function () {
  81992. // Color Grading texure can not be none blocking.
  81993. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  81994. };
  81995. /**
  81996. * Binds the image processing to the shader.
  81997. * @param effect The effect to bind to
  81998. */
  81999. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  82000. if (aspectRatio === void 0) { aspectRatio = 1; }
  82001. // Color Curves
  82002. if (this._colorCurvesEnabled && this.colorCurves) {
  82003. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  82004. }
  82005. // Vignette
  82006. if (this._vignetteEnabled) {
  82007. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  82008. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  82009. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  82010. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  82011. var vignetteScaleX = vignetteScaleY * aspectRatio;
  82012. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  82013. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  82014. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  82015. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  82016. var vignettePower = -2.0 * this.vignetteWeight;
  82017. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  82018. }
  82019. // Exposure
  82020. effect.setFloat("exposureLinear", this.exposure);
  82021. // Contrast
  82022. effect.setFloat("contrast", this.contrast);
  82023. // Color transform settings
  82024. if (this.colorGradingTexture) {
  82025. effect.setTexture("txColorTransform", this.colorGradingTexture);
  82026. var textureSize = this.colorGradingTexture.getSize().height;
  82027. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  82028. 0.5 / textureSize, // textureOffset
  82029. textureSize, // textureSize
  82030. this.colorGradingTexture.level // weight
  82031. );
  82032. }
  82033. };
  82034. /**
  82035. * Clones the current image processing instance.
  82036. * @return The cloned image processing
  82037. */
  82038. ImageProcessingConfiguration.prototype.clone = function () {
  82039. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  82040. };
  82041. /**
  82042. * Serializes the current image processing instance to a json representation.
  82043. * @return a JSON representation
  82044. */
  82045. ImageProcessingConfiguration.prototype.serialize = function () {
  82046. return BABYLON.SerializationHelper.Serialize(this);
  82047. };
  82048. /**
  82049. * Parses the image processing from a json representation.
  82050. * @param source the JSON source to parse
  82051. * @return The parsed image processing
  82052. */
  82053. ImageProcessingConfiguration.Parse = function (source) {
  82054. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  82055. };
  82056. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  82057. /**
  82058. * Used to apply the vignette as a mix with the pixel color.
  82059. */
  82060. get: function () {
  82061. return this._VIGNETTEMODE_MULTIPLY;
  82062. },
  82063. enumerable: true,
  82064. configurable: true
  82065. });
  82066. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  82067. /**
  82068. * Used to apply the vignette as a replacement of the pixel color.
  82069. */
  82070. get: function () {
  82071. return this._VIGNETTEMODE_OPAQUE;
  82072. },
  82073. enumerable: true,
  82074. configurable: true
  82075. });
  82076. /**
  82077. * Default tone mapping applied in BabylonJS.
  82078. */
  82079. ImageProcessingConfiguration.TONEMAPPING_STANDARD = 0;
  82080. /**
  82081. * ACES Tone mapping (used by default in unreal and unity). This can help getting closer
  82082. * to other engines rendering to increase portability.
  82083. */
  82084. ImageProcessingConfiguration.TONEMAPPING_ACES = 1;
  82085. // Static constants associated to the image processing.
  82086. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  82087. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  82088. __decorate([
  82089. BABYLON.serializeAsColorCurves()
  82090. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  82091. __decorate([
  82092. BABYLON.serialize()
  82093. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  82094. __decorate([
  82095. BABYLON.serializeAsTexture()
  82096. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  82097. __decorate([
  82098. BABYLON.serialize()
  82099. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  82100. __decorate([
  82101. BABYLON.serialize()
  82102. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  82103. __decorate([
  82104. BABYLON.serialize()
  82105. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  82106. __decorate([
  82107. BABYLON.serialize()
  82108. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  82109. __decorate([
  82110. BABYLON.serialize()
  82111. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  82112. __decorate([
  82113. BABYLON.serialize()
  82114. ], ImageProcessingConfiguration.prototype, "_toneMappingType", void 0);
  82115. __decorate([
  82116. BABYLON.serialize()
  82117. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  82118. __decorate([
  82119. BABYLON.serialize()
  82120. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  82121. __decorate([
  82122. BABYLON.serialize()
  82123. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  82124. __decorate([
  82125. BABYLON.serialize()
  82126. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  82127. __decorate([
  82128. BABYLON.serialize()
  82129. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  82130. __decorate([
  82131. BABYLON.serializeAsColor4()
  82132. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  82133. __decorate([
  82134. BABYLON.serialize()
  82135. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  82136. __decorate([
  82137. BABYLON.serialize()
  82138. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  82139. __decorate([
  82140. BABYLON.serialize()
  82141. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  82142. __decorate([
  82143. BABYLON.serialize()
  82144. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  82145. __decorate([
  82146. BABYLON.serialize()
  82147. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  82148. return ImageProcessingConfiguration;
  82149. }());
  82150. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  82151. })(BABYLON || (BABYLON = {}));
  82152. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  82153. var BABYLON;
  82154. (function (BABYLON) {
  82155. /**
  82156. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  82157. * It can help converting any input color in a desired output one. This can then be used to create effects
  82158. * from sepia, black and white to sixties or futuristic rendering...
  82159. *
  82160. * The only supported format is currently 3dl.
  82161. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  82162. */
  82163. var ColorGradingTexture = /** @class */ (function (_super) {
  82164. __extends(ColorGradingTexture, _super);
  82165. /**
  82166. * Instantiates a ColorGradingTexture from the following parameters.
  82167. *
  82168. * @param url The location of the color gradind data (currently only supporting 3dl)
  82169. * @param scene The scene the texture will be used in
  82170. */
  82171. function ColorGradingTexture(url, scene) {
  82172. var _this = _super.call(this, scene) || this;
  82173. if (!url) {
  82174. return _this;
  82175. }
  82176. _this._engine = scene.getEngine();
  82177. _this._textureMatrix = BABYLON.Matrix.Identity();
  82178. _this.name = url;
  82179. _this.url = url;
  82180. _this.hasAlpha = false;
  82181. _this.isCube = false;
  82182. _this.is3D = _this._engine.webGLVersion > 1;
  82183. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82184. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82185. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82186. _this.anisotropicFilteringLevel = 1;
  82187. _this._texture = _this._getFromCache(url, true);
  82188. if (!_this._texture) {
  82189. if (!scene.useDelayedTextureLoading) {
  82190. _this.loadTexture();
  82191. }
  82192. else {
  82193. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  82194. }
  82195. }
  82196. return _this;
  82197. }
  82198. /**
  82199. * Returns the texture matrix used in most of the material.
  82200. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  82201. */
  82202. ColorGradingTexture.prototype.getTextureMatrix = function () {
  82203. return this._textureMatrix;
  82204. };
  82205. /**
  82206. * Occurs when the file being loaded is a .3dl LUT file.
  82207. */
  82208. ColorGradingTexture.prototype.load3dlTexture = function () {
  82209. var engine = this._engine;
  82210. var texture;
  82211. if (engine.webGLVersion === 1) {
  82212. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  82213. }
  82214. else {
  82215. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  82216. }
  82217. this._texture = texture;
  82218. var callback = function (text) {
  82219. if (typeof text !== "string") {
  82220. return;
  82221. }
  82222. var data = null;
  82223. var tempData = null;
  82224. var line;
  82225. var lines = text.split('\n');
  82226. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  82227. var maxColor = 0;
  82228. for (var i = 0; i < lines.length; i++) {
  82229. line = lines[i];
  82230. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  82231. continue;
  82232. if (line.indexOf('#') === 0)
  82233. continue;
  82234. var words = line.split(" ");
  82235. if (size === 0) {
  82236. // Number of space + one
  82237. size = words.length;
  82238. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  82239. tempData = new Float32Array(size * size * size * 4);
  82240. continue;
  82241. }
  82242. if (size != 0) {
  82243. var r = Math.max(parseInt(words[0]), 0);
  82244. var g = Math.max(parseInt(words[1]), 0);
  82245. var b = Math.max(parseInt(words[2]), 0);
  82246. maxColor = Math.max(r, maxColor);
  82247. maxColor = Math.max(g, maxColor);
  82248. maxColor = Math.max(b, maxColor);
  82249. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  82250. if (tempData) {
  82251. tempData[pixelStorageIndex + 0] = r;
  82252. tempData[pixelStorageIndex + 1] = g;
  82253. tempData[pixelStorageIndex + 2] = b;
  82254. }
  82255. pixelIndexSlice++;
  82256. if (pixelIndexSlice % size == 0) {
  82257. pixelIndexH++;
  82258. pixelIndexSlice = 0;
  82259. if (pixelIndexH % size == 0) {
  82260. pixelIndexW++;
  82261. pixelIndexH = 0;
  82262. }
  82263. }
  82264. }
  82265. }
  82266. if (tempData && data) {
  82267. for (var i = 0; i < tempData.length; i++) {
  82268. if (i > 0 && (i + 1) % 4 === 0) {
  82269. data[i] = 255;
  82270. }
  82271. else {
  82272. var value = tempData[i];
  82273. data[i] = (value / maxColor * 255);
  82274. }
  82275. }
  82276. }
  82277. if (texture.is3D) {
  82278. texture.updateSize(size, size, size);
  82279. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  82280. }
  82281. else {
  82282. texture.updateSize(size * size, size);
  82283. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  82284. }
  82285. };
  82286. var scene = this.getScene();
  82287. if (scene) {
  82288. scene._loadFile(this.url, callback);
  82289. }
  82290. else {
  82291. this._engine._loadFile(this.url, callback);
  82292. }
  82293. return this._texture;
  82294. };
  82295. /**
  82296. * Starts the loading process of the texture.
  82297. */
  82298. ColorGradingTexture.prototype.loadTexture = function () {
  82299. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  82300. this.load3dlTexture();
  82301. }
  82302. };
  82303. /**
  82304. * Clones the color gradind texture.
  82305. */
  82306. ColorGradingTexture.prototype.clone = function () {
  82307. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  82308. // Base texture
  82309. newTexture.level = this.level;
  82310. return newTexture;
  82311. };
  82312. /**
  82313. * Called during delayed load for textures.
  82314. */
  82315. ColorGradingTexture.prototype.delayLoad = function () {
  82316. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  82317. return;
  82318. }
  82319. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  82320. this._texture = this._getFromCache(this.url, true);
  82321. if (!this._texture) {
  82322. this.loadTexture();
  82323. }
  82324. };
  82325. /**
  82326. * Parses a color grading texture serialized by Babylon.
  82327. * @param parsedTexture The texture information being parsedTexture
  82328. * @param scene The scene to load the texture in
  82329. * @param rootUrl The root url of the data assets to load
  82330. * @return A color gradind texture
  82331. */
  82332. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  82333. var texture = null;
  82334. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  82335. texture = new ColorGradingTexture(parsedTexture.name, scene);
  82336. texture.name = parsedTexture.name;
  82337. texture.level = parsedTexture.level;
  82338. }
  82339. return texture;
  82340. };
  82341. /**
  82342. * Serializes the LUT texture to json format.
  82343. */
  82344. ColorGradingTexture.prototype.serialize = function () {
  82345. if (!this.name) {
  82346. return null;
  82347. }
  82348. var serializationObject = {};
  82349. serializationObject.name = this.name;
  82350. serializationObject.level = this.level;
  82351. serializationObject.customType = "BABYLON.ColorGradingTexture";
  82352. return serializationObject;
  82353. };
  82354. /**
  82355. * Empty line regex stored for GC.
  82356. */
  82357. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  82358. return ColorGradingTexture;
  82359. }(BABYLON.BaseTexture));
  82360. BABYLON.ColorGradingTexture = ColorGradingTexture;
  82361. })(BABYLON || (BABYLON = {}));
  82362. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  82363. var BABYLON;
  82364. (function (BABYLON) {
  82365. /**
  82366. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  82367. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  82368. * 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;
  82369. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  82370. */
  82371. var ColorCurves = /** @class */ (function () {
  82372. function ColorCurves() {
  82373. this._dirty = true;
  82374. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  82375. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  82376. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  82377. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  82378. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  82379. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  82380. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  82381. this._globalHue = 30;
  82382. this._globalDensity = 0;
  82383. this._globalSaturation = 0;
  82384. this._globalExposure = 0;
  82385. this._highlightsHue = 30;
  82386. this._highlightsDensity = 0;
  82387. this._highlightsSaturation = 0;
  82388. this._highlightsExposure = 0;
  82389. this._midtonesHue = 30;
  82390. this._midtonesDensity = 0;
  82391. this._midtonesSaturation = 0;
  82392. this._midtonesExposure = 0;
  82393. this._shadowsHue = 30;
  82394. this._shadowsDensity = 0;
  82395. this._shadowsSaturation = 0;
  82396. this._shadowsExposure = 0;
  82397. }
  82398. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  82399. /**
  82400. * Gets the global Hue value.
  82401. * 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).
  82402. */
  82403. get: function () {
  82404. return this._globalHue;
  82405. },
  82406. /**
  82407. * Sets the global Hue value.
  82408. * 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).
  82409. */
  82410. set: function (value) {
  82411. this._globalHue = value;
  82412. this._dirty = true;
  82413. },
  82414. enumerable: true,
  82415. configurable: true
  82416. });
  82417. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  82418. /**
  82419. * Gets the global Density value.
  82420. * 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.
  82421. * Values less than zero provide a filter of opposite hue.
  82422. */
  82423. get: function () {
  82424. return this._globalDensity;
  82425. },
  82426. /**
  82427. * Sets the global Density value.
  82428. * 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.
  82429. * Values less than zero provide a filter of opposite hue.
  82430. */
  82431. set: function (value) {
  82432. this._globalDensity = value;
  82433. this._dirty = true;
  82434. },
  82435. enumerable: true,
  82436. configurable: true
  82437. });
  82438. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  82439. /**
  82440. * Gets the global Saturation value.
  82441. * 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.
  82442. */
  82443. get: function () {
  82444. return this._globalSaturation;
  82445. },
  82446. /**
  82447. * Sets the global Saturation value.
  82448. * 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.
  82449. */
  82450. set: function (value) {
  82451. this._globalSaturation = value;
  82452. this._dirty = true;
  82453. },
  82454. enumerable: true,
  82455. configurable: true
  82456. });
  82457. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  82458. /**
  82459. * Gets the global Exposure value.
  82460. * 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.
  82461. */
  82462. get: function () {
  82463. return this._globalExposure;
  82464. },
  82465. /**
  82466. * Sets the global Exposure value.
  82467. * 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.
  82468. */
  82469. set: function (value) {
  82470. this._globalExposure = value;
  82471. this._dirty = true;
  82472. },
  82473. enumerable: true,
  82474. configurable: true
  82475. });
  82476. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  82477. /**
  82478. * Gets the highlights Hue value.
  82479. * 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).
  82480. */
  82481. get: function () {
  82482. return this._highlightsHue;
  82483. },
  82484. /**
  82485. * Sets the highlights Hue value.
  82486. * 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).
  82487. */
  82488. set: function (value) {
  82489. this._highlightsHue = value;
  82490. this._dirty = true;
  82491. },
  82492. enumerable: true,
  82493. configurable: true
  82494. });
  82495. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  82496. /**
  82497. * Gets the highlights Density value.
  82498. * 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.
  82499. * Values less than zero provide a filter of opposite hue.
  82500. */
  82501. get: function () {
  82502. return this._highlightsDensity;
  82503. },
  82504. /**
  82505. * Sets the highlights Density value.
  82506. * 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.
  82507. * Values less than zero provide a filter of opposite hue.
  82508. */
  82509. set: function (value) {
  82510. this._highlightsDensity = value;
  82511. this._dirty = true;
  82512. },
  82513. enumerable: true,
  82514. configurable: true
  82515. });
  82516. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  82517. /**
  82518. * Gets the highlights Saturation value.
  82519. * 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.
  82520. */
  82521. get: function () {
  82522. return this._highlightsSaturation;
  82523. },
  82524. /**
  82525. * Sets the highlights Saturation value.
  82526. * 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.
  82527. */
  82528. set: function (value) {
  82529. this._highlightsSaturation = value;
  82530. this._dirty = true;
  82531. },
  82532. enumerable: true,
  82533. configurable: true
  82534. });
  82535. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  82536. /**
  82537. * Gets the highlights Exposure value.
  82538. * 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.
  82539. */
  82540. get: function () {
  82541. return this._highlightsExposure;
  82542. },
  82543. /**
  82544. * Sets the highlights Exposure value.
  82545. * 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.
  82546. */
  82547. set: function (value) {
  82548. this._highlightsExposure = value;
  82549. this._dirty = true;
  82550. },
  82551. enumerable: true,
  82552. configurable: true
  82553. });
  82554. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  82555. /**
  82556. * Gets the midtones Hue value.
  82557. * 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).
  82558. */
  82559. get: function () {
  82560. return this._midtonesHue;
  82561. },
  82562. /**
  82563. * Sets the midtones Hue value.
  82564. * 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).
  82565. */
  82566. set: function (value) {
  82567. this._midtonesHue = value;
  82568. this._dirty = true;
  82569. },
  82570. enumerable: true,
  82571. configurable: true
  82572. });
  82573. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  82574. /**
  82575. * Gets the midtones Density value.
  82576. * 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.
  82577. * Values less than zero provide a filter of opposite hue.
  82578. */
  82579. get: function () {
  82580. return this._midtonesDensity;
  82581. },
  82582. /**
  82583. * Sets the midtones Density value.
  82584. * 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.
  82585. * Values less than zero provide a filter of opposite hue.
  82586. */
  82587. set: function (value) {
  82588. this._midtonesDensity = value;
  82589. this._dirty = true;
  82590. },
  82591. enumerable: true,
  82592. configurable: true
  82593. });
  82594. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  82595. /**
  82596. * Gets the midtones Saturation value.
  82597. * 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.
  82598. */
  82599. get: function () {
  82600. return this._midtonesSaturation;
  82601. },
  82602. /**
  82603. * Sets the midtones Saturation value.
  82604. * 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.
  82605. */
  82606. set: function (value) {
  82607. this._midtonesSaturation = value;
  82608. this._dirty = true;
  82609. },
  82610. enumerable: true,
  82611. configurable: true
  82612. });
  82613. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  82614. /**
  82615. * Gets the midtones Exposure value.
  82616. * 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.
  82617. */
  82618. get: function () {
  82619. return this._midtonesExposure;
  82620. },
  82621. /**
  82622. * Sets the midtones Exposure value.
  82623. * 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.
  82624. */
  82625. set: function (value) {
  82626. this._midtonesExposure = value;
  82627. this._dirty = true;
  82628. },
  82629. enumerable: true,
  82630. configurable: true
  82631. });
  82632. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  82633. /**
  82634. * Gets the shadows Hue value.
  82635. * 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).
  82636. */
  82637. get: function () {
  82638. return this._shadowsHue;
  82639. },
  82640. /**
  82641. * Sets the shadows Hue value.
  82642. * 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).
  82643. */
  82644. set: function (value) {
  82645. this._shadowsHue = value;
  82646. this._dirty = true;
  82647. },
  82648. enumerable: true,
  82649. configurable: true
  82650. });
  82651. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  82652. /**
  82653. * Gets the shadows Density value.
  82654. * 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.
  82655. * Values less than zero provide a filter of opposite hue.
  82656. */
  82657. get: function () {
  82658. return this._shadowsDensity;
  82659. },
  82660. /**
  82661. * Sets the shadows Density value.
  82662. * 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.
  82663. * Values less than zero provide a filter of opposite hue.
  82664. */
  82665. set: function (value) {
  82666. this._shadowsDensity = value;
  82667. this._dirty = true;
  82668. },
  82669. enumerable: true,
  82670. configurable: true
  82671. });
  82672. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  82673. /**
  82674. * Gets the shadows Saturation value.
  82675. * 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.
  82676. */
  82677. get: function () {
  82678. return this._shadowsSaturation;
  82679. },
  82680. /**
  82681. * Sets the shadows Saturation value.
  82682. * 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.
  82683. */
  82684. set: function (value) {
  82685. this._shadowsSaturation = value;
  82686. this._dirty = true;
  82687. },
  82688. enumerable: true,
  82689. configurable: true
  82690. });
  82691. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  82692. /**
  82693. * Gets the shadows Exposure value.
  82694. * 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.
  82695. */
  82696. get: function () {
  82697. return this._shadowsExposure;
  82698. },
  82699. /**
  82700. * Sets the shadows Exposure value.
  82701. * 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.
  82702. */
  82703. set: function (value) {
  82704. this._shadowsExposure = value;
  82705. this._dirty = true;
  82706. },
  82707. enumerable: true,
  82708. configurable: true
  82709. });
  82710. ColorCurves.prototype.getClassName = function () {
  82711. return "ColorCurves";
  82712. };
  82713. /**
  82714. * Binds the color curves to the shader.
  82715. * @param colorCurves The color curve to bind
  82716. * @param effect The effect to bind to
  82717. */
  82718. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  82719. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  82720. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  82721. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  82722. if (colorCurves._dirty) {
  82723. colorCurves._dirty = false;
  82724. // Fill in global info.
  82725. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  82726. // Compute highlights info.
  82727. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  82728. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  82729. // Compute midtones info.
  82730. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  82731. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  82732. // Compute shadows info.
  82733. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  82734. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  82735. // Compute deltas (neutral is midtones).
  82736. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  82737. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  82738. }
  82739. if (effect) {
  82740. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  82741. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  82742. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  82743. }
  82744. };
  82745. /**
  82746. * Prepare the list of uniforms associated with the ColorCurves effects.
  82747. * @param uniformsList The list of uniforms used in the effect
  82748. */
  82749. ColorCurves.PrepareUniforms = function (uniformsList) {
  82750. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  82751. };
  82752. /**
  82753. * Returns color grading data based on a hue, density, saturation and exposure value.
  82754. * @param filterHue The hue of the color filter.
  82755. * @param filterDensity The density of the color filter.
  82756. * @param saturation The saturation.
  82757. * @param exposure The exposure.
  82758. * @param result The result data container.
  82759. */
  82760. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  82761. if (hue == null) {
  82762. return;
  82763. }
  82764. hue = ColorCurves.clamp(hue, 0, 360);
  82765. density = ColorCurves.clamp(density, -100, 100);
  82766. saturation = ColorCurves.clamp(saturation, -100, 100);
  82767. exposure = ColorCurves.clamp(exposure, -100, 100);
  82768. // Remap the slider/config filter density with non-linear mapping and also scale by half
  82769. // so that the maximum filter density is only 50% control. This provides fine control
  82770. // for small values and reasonable range.
  82771. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  82772. density *= 0.5;
  82773. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  82774. if (density < 0) {
  82775. density *= -1;
  82776. hue = (hue + 180) % 360;
  82777. }
  82778. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  82779. result.scaleToRef(2, result);
  82780. result.a = 1 + 0.01 * saturation;
  82781. };
  82782. /**
  82783. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  82784. * @param value The input slider value in range [-100,100].
  82785. * @returns Adjusted value.
  82786. */
  82787. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  82788. value /= 100;
  82789. var x = Math.abs(value);
  82790. x = Math.pow(x, 2);
  82791. if (value < 0) {
  82792. x *= -1;
  82793. }
  82794. x *= 100;
  82795. return x;
  82796. };
  82797. /**
  82798. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  82799. * @param hue The hue (H) input.
  82800. * @param saturation The saturation (S) input.
  82801. * @param brightness The brightness (B) input.
  82802. * @result An RGBA color represented as Vector4.
  82803. */
  82804. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  82805. var h = ColorCurves.clamp(hue, 0, 360);
  82806. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  82807. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  82808. if (s === 0) {
  82809. result.r = v;
  82810. result.g = v;
  82811. result.b = v;
  82812. }
  82813. else {
  82814. // sector 0 to 5
  82815. h /= 60;
  82816. var i = Math.floor(h);
  82817. // fractional part of h
  82818. var f = h - i;
  82819. var p = v * (1 - s);
  82820. var q = v * (1 - s * f);
  82821. var t = v * (1 - s * (1 - f));
  82822. switch (i) {
  82823. case 0:
  82824. result.r = v;
  82825. result.g = t;
  82826. result.b = p;
  82827. break;
  82828. case 1:
  82829. result.r = q;
  82830. result.g = v;
  82831. result.b = p;
  82832. break;
  82833. case 2:
  82834. result.r = p;
  82835. result.g = v;
  82836. result.b = t;
  82837. break;
  82838. case 3:
  82839. result.r = p;
  82840. result.g = q;
  82841. result.b = v;
  82842. break;
  82843. case 4:
  82844. result.r = t;
  82845. result.g = p;
  82846. result.b = v;
  82847. break;
  82848. default: // case 5:
  82849. result.r = v;
  82850. result.g = p;
  82851. result.b = q;
  82852. break;
  82853. }
  82854. }
  82855. result.a = 1;
  82856. };
  82857. /**
  82858. * Returns a value clamped between min and max
  82859. * @param value The value to clamp
  82860. * @param min The minimum of value
  82861. * @param max The maximum of value
  82862. * @returns The clamped value.
  82863. */
  82864. ColorCurves.clamp = function (value, min, max) {
  82865. return Math.min(Math.max(value, min), max);
  82866. };
  82867. /**
  82868. * Clones the current color curve instance.
  82869. * @return The cloned curves
  82870. */
  82871. ColorCurves.prototype.clone = function () {
  82872. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  82873. };
  82874. /**
  82875. * Serializes the current color curve instance to a json representation.
  82876. * @return a JSON representation
  82877. */
  82878. ColorCurves.prototype.serialize = function () {
  82879. return BABYLON.SerializationHelper.Serialize(this);
  82880. };
  82881. /**
  82882. * Parses the color curve from a json representation.
  82883. * @param source the JSON source to parse
  82884. * @return The parsed curves
  82885. */
  82886. ColorCurves.Parse = function (source) {
  82887. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  82888. };
  82889. __decorate([
  82890. BABYLON.serialize()
  82891. ], ColorCurves.prototype, "_globalHue", void 0);
  82892. __decorate([
  82893. BABYLON.serialize()
  82894. ], ColorCurves.prototype, "_globalDensity", void 0);
  82895. __decorate([
  82896. BABYLON.serialize()
  82897. ], ColorCurves.prototype, "_globalSaturation", void 0);
  82898. __decorate([
  82899. BABYLON.serialize()
  82900. ], ColorCurves.prototype, "_globalExposure", void 0);
  82901. __decorate([
  82902. BABYLON.serialize()
  82903. ], ColorCurves.prototype, "_highlightsHue", void 0);
  82904. __decorate([
  82905. BABYLON.serialize()
  82906. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  82907. __decorate([
  82908. BABYLON.serialize()
  82909. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  82910. __decorate([
  82911. BABYLON.serialize()
  82912. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  82913. __decorate([
  82914. BABYLON.serialize()
  82915. ], ColorCurves.prototype, "_midtonesHue", void 0);
  82916. __decorate([
  82917. BABYLON.serialize()
  82918. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  82919. __decorate([
  82920. BABYLON.serialize()
  82921. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  82922. __decorate([
  82923. BABYLON.serialize()
  82924. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  82925. return ColorCurves;
  82926. }());
  82927. BABYLON.ColorCurves = ColorCurves;
  82928. })(BABYLON || (BABYLON = {}));
  82929. //# sourceMappingURL=babylon.colorCurves.js.map
  82930. var BABYLON;
  82931. (function (BABYLON) {
  82932. var RefractionPostProcess = /** @class */ (function (_super) {
  82933. __extends(RefractionPostProcess, _super);
  82934. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  82935. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  82936. _this.color = color;
  82937. _this.depth = depth;
  82938. _this.colorLevel = colorLevel;
  82939. _this._ownRefractionTexture = true;
  82940. _this.onActivateObservable.add(function (cam) {
  82941. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  82942. });
  82943. _this.onApplyObservable.add(function (effect) {
  82944. effect.setColor3("baseColor", _this.color);
  82945. effect.setFloat("depth", _this.depth);
  82946. effect.setFloat("colorLevel", _this.colorLevel);
  82947. effect.setTexture("refractionSampler", _this._refTexture);
  82948. });
  82949. return _this;
  82950. }
  82951. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  82952. /**
  82953. * Gets or sets the refraction texture
  82954. * Please note that you are responsible for disposing the texture if you set it manually
  82955. */
  82956. get: function () {
  82957. return this._refTexture;
  82958. },
  82959. set: function (value) {
  82960. if (this._refTexture && this._ownRefractionTexture) {
  82961. this._refTexture.dispose();
  82962. }
  82963. this._refTexture = value;
  82964. this._ownRefractionTexture = false;
  82965. },
  82966. enumerable: true,
  82967. configurable: true
  82968. });
  82969. // Methods
  82970. RefractionPostProcess.prototype.dispose = function (camera) {
  82971. if (this._refTexture && this._ownRefractionTexture) {
  82972. this._refTexture.dispose();
  82973. this._refTexture = null;
  82974. }
  82975. _super.prototype.dispose.call(this, camera);
  82976. };
  82977. return RefractionPostProcess;
  82978. }(BABYLON.PostProcess));
  82979. BABYLON.RefractionPostProcess = RefractionPostProcess;
  82980. })(BABYLON || (BABYLON = {}));
  82981. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  82982. var BABYLON;
  82983. (function (BABYLON) {
  82984. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  82985. __extends(BlackAndWhitePostProcess, _super);
  82986. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  82987. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  82988. _this.degree = 1;
  82989. _this.onApplyObservable.add(function (effect) {
  82990. effect.setFloat("degree", _this.degree);
  82991. });
  82992. return _this;
  82993. }
  82994. return BlackAndWhitePostProcess;
  82995. }(BABYLON.PostProcess));
  82996. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  82997. })(BABYLON || (BABYLON = {}));
  82998. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  82999. var BABYLON;
  83000. (function (BABYLON) {
  83001. /**
  83002. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  83003. * input texture to perform effects such as edge detection or sharpening
  83004. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  83005. */
  83006. var ConvolutionPostProcess = /** @class */ (function (_super) {
  83007. __extends(ConvolutionPostProcess, _super);
  83008. /**
  83009. * Creates a new instance ConvolutionPostProcess
  83010. * @param name The name of the effect.
  83011. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  83012. * @param options The required width/height ratio to downsize to before computing the render pass.
  83013. * @param camera The camera to apply the render pass to.
  83014. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  83015. * @param engine The engine which the post process will be applied. (default: current engine)
  83016. * @param reusable If the post process can be reused on the same frame. (default: false)
  83017. * @param textureType Type of textures used when performing the post process. (default: 0)
  83018. */
  83019. function ConvolutionPostProcess(name,
  83020. /** Array of 9 values corrisponding to the 3x3 kernel to be applied */
  83021. kernel, options, camera, samplingMode, engine, reusable, textureType) {
  83022. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  83023. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  83024. _this.kernel = kernel;
  83025. _this.onApply = function (effect) {
  83026. effect.setFloat2("screenSize", _this.width, _this.height);
  83027. effect.setArray("kernel", _this.kernel);
  83028. };
  83029. return _this;
  83030. }
  83031. // Statics
  83032. /**
  83033. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  83034. */
  83035. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  83036. /**
  83037. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  83038. */
  83039. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  83040. /**
  83041. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  83042. */
  83043. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  83044. /**
  83045. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  83046. */
  83047. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  83048. /**
  83049. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  83050. */
  83051. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  83052. /**
  83053. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  83054. */
  83055. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  83056. return ConvolutionPostProcess;
  83057. }(BABYLON.PostProcess));
  83058. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  83059. })(BABYLON || (BABYLON = {}));
  83060. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  83061. var BABYLON;
  83062. (function (BABYLON) {
  83063. var FilterPostProcess = /** @class */ (function (_super) {
  83064. __extends(FilterPostProcess, _super);
  83065. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  83066. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  83067. _this.kernelMatrix = kernelMatrix;
  83068. _this.onApply = function (effect) {
  83069. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  83070. };
  83071. return _this;
  83072. }
  83073. return FilterPostProcess;
  83074. }(BABYLON.PostProcess));
  83075. BABYLON.FilterPostProcess = FilterPostProcess;
  83076. })(BABYLON || (BABYLON = {}));
  83077. //# sourceMappingURL=babylon.filterPostProcess.js.map
  83078. var BABYLON;
  83079. (function (BABYLON) {
  83080. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  83081. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  83082. __extends(VolumetricLightScatteringPostProcess, _super);
  83083. /**
  83084. * @constructor
  83085. * @param {string} name - The post-process name
  83086. * @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)
  83087. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  83088. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  83089. * @param {number} samples - The post-process quality, default 100
  83090. * @param {number} samplingMode - The post-process filtering mode
  83091. * @param {BABYLON.Engine} engine - The babylon engine
  83092. * @param {boolean} reusable - If the post-process is reusable
  83093. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null a "scene" must be provided
  83094. */
  83095. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  83096. if (samples === void 0) { samples = 100; }
  83097. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  83098. 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;
  83099. _this._screenCoordinates = BABYLON.Vector2.Zero();
  83100. /**
  83101. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  83102. */
  83103. _this.customMeshPosition = BABYLON.Vector3.Zero();
  83104. /**
  83105. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  83106. */
  83107. _this.useCustomMeshPosition = false;
  83108. /**
  83109. * If the post-process should inverse the light scattering direction
  83110. */
  83111. _this.invert = true;
  83112. /**
  83113. * Array containing the excluded meshes not rendered in the internal pass
  83114. */
  83115. _this.excludedMeshes = new Array();
  83116. /**
  83117. * Controls the overall intensity of the post-process
  83118. */
  83119. _this.exposure = 0.3;
  83120. /**
  83121. * Dissipates each sample's contribution in range [0, 1]
  83122. */
  83123. _this.decay = 0.96815;
  83124. /**
  83125. * Controls the overall intensity of each sample
  83126. */
  83127. _this.weight = 0.58767;
  83128. /**
  83129. * Controls the density of each sample
  83130. */
  83131. _this.density = 0.926;
  83132. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  83133. engine = scene.getEngine();
  83134. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  83135. // Configure mesh
  83136. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  83137. // Configure
  83138. _this._createPass(scene, ratio.passRatio || ratio);
  83139. _this.onActivate = function (camera) {
  83140. if (!_this.isSupported) {
  83141. _this.dispose(camera);
  83142. }
  83143. _this.onActivate = null;
  83144. };
  83145. _this.onApplyObservable.add(function (effect) {
  83146. _this._updateMeshScreenCoordinates(scene);
  83147. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  83148. effect.setFloat("exposure", _this.exposure);
  83149. effect.setFloat("decay", _this.decay);
  83150. effect.setFloat("weight", _this.weight);
  83151. effect.setFloat("density", _this.density);
  83152. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  83153. });
  83154. return _this;
  83155. }
  83156. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  83157. get: function () {
  83158. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  83159. return false;
  83160. },
  83161. set: function (useDiffuseColor) {
  83162. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  83163. },
  83164. enumerable: true,
  83165. configurable: true
  83166. });
  83167. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  83168. return "VolumetricLightScatteringPostProcess";
  83169. };
  83170. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  83171. var mesh = subMesh.getMesh();
  83172. // Render this.mesh as default
  83173. if (mesh === this.mesh && mesh.material) {
  83174. return mesh.material.isReady(mesh);
  83175. }
  83176. var defines = [];
  83177. var attribs = [BABYLON.VertexBuffer.PositionKind];
  83178. var material = subMesh.getMaterial();
  83179. // Alpha test
  83180. if (material) {
  83181. if (material.needAlphaTesting()) {
  83182. defines.push("#define ALPHATEST");
  83183. }
  83184. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  83185. attribs.push(BABYLON.VertexBuffer.UVKind);
  83186. defines.push("#define UV1");
  83187. }
  83188. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  83189. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  83190. defines.push("#define UV2");
  83191. }
  83192. }
  83193. // Bones
  83194. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  83195. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  83196. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  83197. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  83198. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  83199. }
  83200. else {
  83201. defines.push("#define NUM_BONE_INFLUENCERS 0");
  83202. }
  83203. // Instances
  83204. if (useInstances) {
  83205. defines.push("#define INSTANCES");
  83206. attribs.push("world0");
  83207. attribs.push("world1");
  83208. attribs.push("world2");
  83209. attribs.push("world3");
  83210. }
  83211. // Get correct effect
  83212. var join = defines.join("\n");
  83213. if (this._cachedDefines !== join) {
  83214. this._cachedDefines = join;
  83215. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  83216. }
  83217. return this._volumetricLightScatteringPass.isReady();
  83218. };
  83219. /**
  83220. * Sets the new light position for light scattering effect
  83221. * @param {BABYLON.Vector3} The new custom light position
  83222. */
  83223. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  83224. this.customMeshPosition = position;
  83225. };
  83226. /**
  83227. * Returns the light position for light scattering effect
  83228. * @return {BABYLON.Vector3} The custom light position
  83229. */
  83230. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  83231. return this.customMeshPosition;
  83232. };
  83233. /**
  83234. * Disposes the internal assets and detaches the post-process from the camera
  83235. */
  83236. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  83237. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  83238. if (rttIndex !== -1) {
  83239. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  83240. }
  83241. this._volumetricLightScatteringRTT.dispose();
  83242. _super.prototype.dispose.call(this, camera);
  83243. };
  83244. /**
  83245. * Returns the render target texture used by the post-process
  83246. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  83247. */
  83248. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  83249. return this._volumetricLightScatteringRTT;
  83250. };
  83251. // Private methods
  83252. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  83253. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  83254. return true;
  83255. }
  83256. return false;
  83257. };
  83258. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  83259. var _this = this;
  83260. var engine = scene.getEngine();
  83261. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  83262. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83263. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83264. this._volumetricLightScatteringRTT.renderList = null;
  83265. this._volumetricLightScatteringRTT.renderParticles = false;
  83266. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  83267. var camera = this.getCamera();
  83268. if (camera) {
  83269. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  83270. }
  83271. else {
  83272. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  83273. }
  83274. // Custom render function for submeshes
  83275. var renderSubMesh = function (subMesh) {
  83276. var mesh = subMesh.getRenderingMesh();
  83277. if (_this._meshExcluded(mesh)) {
  83278. return;
  83279. }
  83280. var material = subMesh.getMaterial();
  83281. if (!material) {
  83282. return;
  83283. }
  83284. var scene = mesh.getScene();
  83285. var engine = scene.getEngine();
  83286. // Culling
  83287. engine.setState(material.backFaceCulling);
  83288. // Managing instances
  83289. var batch = mesh._getInstancesRenderList(subMesh._id);
  83290. if (batch.mustReturn) {
  83291. return;
  83292. }
  83293. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  83294. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  83295. var effect = _this._volumetricLightScatteringPass;
  83296. if (mesh === _this.mesh) {
  83297. if (subMesh.effect) {
  83298. effect = subMesh.effect;
  83299. }
  83300. else {
  83301. effect = material.getEffect();
  83302. }
  83303. }
  83304. engine.enableEffect(effect);
  83305. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  83306. if (mesh === _this.mesh) {
  83307. material.bind(mesh.getWorldMatrix(), mesh);
  83308. }
  83309. else {
  83310. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  83311. // Alpha test
  83312. if (material && material.needAlphaTesting()) {
  83313. var alphaTexture = material.getAlphaTestTexture();
  83314. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  83315. if (alphaTexture) {
  83316. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  83317. }
  83318. }
  83319. // Bones
  83320. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  83321. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  83322. }
  83323. }
  83324. // Draw
  83325. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  83326. }
  83327. };
  83328. // Render target texture callbacks
  83329. var savedSceneClearColor;
  83330. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  83331. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  83332. savedSceneClearColor = scene.clearColor;
  83333. scene.clearColor = sceneClearColor;
  83334. });
  83335. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  83336. scene.clearColor = savedSceneClearColor;
  83337. });
  83338. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  83339. var engine = scene.getEngine();
  83340. var index;
  83341. if (depthOnlySubMeshes.length) {
  83342. engine.setColorWrite(false);
  83343. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  83344. renderSubMesh(depthOnlySubMeshes.data[index]);
  83345. }
  83346. engine.setColorWrite(true);
  83347. }
  83348. for (index = 0; index < opaqueSubMeshes.length; index++) {
  83349. renderSubMesh(opaqueSubMeshes.data[index]);
  83350. }
  83351. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  83352. renderSubMesh(alphaTestSubMeshes.data[index]);
  83353. }
  83354. if (transparentSubMeshes.length) {
  83355. // Sort sub meshes
  83356. for (index = 0; index < transparentSubMeshes.length; index++) {
  83357. var submesh = transparentSubMeshes.data[index];
  83358. var boundingInfo = submesh.getBoundingInfo();
  83359. if (boundingInfo && scene.activeCamera) {
  83360. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  83361. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  83362. }
  83363. }
  83364. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  83365. sortedArray.sort(function (a, b) {
  83366. // Alpha index first
  83367. if (a._alphaIndex > b._alphaIndex) {
  83368. return 1;
  83369. }
  83370. if (a._alphaIndex < b._alphaIndex) {
  83371. return -1;
  83372. }
  83373. // Then distance to camera
  83374. if (a._distanceToCamera < b._distanceToCamera) {
  83375. return 1;
  83376. }
  83377. if (a._distanceToCamera > b._distanceToCamera) {
  83378. return -1;
  83379. }
  83380. return 0;
  83381. });
  83382. // Render sub meshes
  83383. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  83384. for (index = 0; index < sortedArray.length; index++) {
  83385. renderSubMesh(sortedArray[index]);
  83386. }
  83387. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  83388. }
  83389. };
  83390. };
  83391. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  83392. var transform = scene.getTransformMatrix();
  83393. var meshPosition;
  83394. if (this.useCustomMeshPosition) {
  83395. meshPosition = this.customMeshPosition;
  83396. }
  83397. else if (this.attachedNode) {
  83398. meshPosition = this.attachedNode.position;
  83399. }
  83400. else {
  83401. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  83402. }
  83403. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  83404. this._screenCoordinates.x = pos.x / this._viewPort.width;
  83405. this._screenCoordinates.y = pos.y / this._viewPort.height;
  83406. if (this.invert)
  83407. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  83408. };
  83409. // Static methods
  83410. /**
  83411. * Creates a default mesh for the Volumeric Light Scattering post-process
  83412. * @param {string} The mesh name
  83413. * @param {BABYLON.Scene} The scene where to create the mesh
  83414. * @return {BABYLON.Mesh} the default mesh
  83415. */
  83416. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  83417. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  83418. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  83419. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  83420. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  83421. mesh.material = material;
  83422. return mesh;
  83423. };
  83424. __decorate([
  83425. BABYLON.serializeAsVector3()
  83426. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  83427. __decorate([
  83428. BABYLON.serialize()
  83429. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  83430. __decorate([
  83431. BABYLON.serialize()
  83432. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  83433. __decorate([
  83434. BABYLON.serializeAsMeshReference()
  83435. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  83436. __decorate([
  83437. BABYLON.serialize()
  83438. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  83439. __decorate([
  83440. BABYLON.serialize()
  83441. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  83442. __decorate([
  83443. BABYLON.serialize()
  83444. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  83445. __decorate([
  83446. BABYLON.serialize()
  83447. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  83448. __decorate([
  83449. BABYLON.serialize()
  83450. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  83451. return VolumetricLightScatteringPostProcess;
  83452. }(BABYLON.PostProcess));
  83453. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  83454. })(BABYLON || (BABYLON = {}));
  83455. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  83456. //
  83457. // This post-process allows the modification of rendered colors by using
  83458. // a 'look-up table' (LUT). This effect is also called Color Grading.
  83459. //
  83460. // The object needs to be provided an url to a texture containing the color
  83461. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  83462. // Use an image editing software to tweak the LUT to match your needs.
  83463. //
  83464. // For an example of a color LUT, see here:
  83465. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  83466. // For explanations on color grading, see here:
  83467. // http://udn.epicgames.com/Three/ColorGrading.html
  83468. //
  83469. var BABYLON;
  83470. (function (BABYLON) {
  83471. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  83472. __extends(ColorCorrectionPostProcess, _super);
  83473. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  83474. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  83475. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  83476. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  83477. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83478. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83479. _this.onApply = function (effect) {
  83480. effect.setTexture("colorTable", _this._colorTableTexture);
  83481. };
  83482. return _this;
  83483. }
  83484. return ColorCorrectionPostProcess;
  83485. }(BABYLON.PostProcess));
  83486. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  83487. })(BABYLON || (BABYLON = {}));
  83488. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  83489. var BABYLON;
  83490. (function (BABYLON) {
  83491. /** Defines operator used for tonemapping */
  83492. var TonemappingOperator;
  83493. (function (TonemappingOperator) {
  83494. /** Hable */
  83495. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  83496. /** Reinhard */
  83497. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  83498. /** HejiDawson */
  83499. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  83500. /** Photographic */
  83501. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  83502. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  83503. ;
  83504. /**
  83505. * Defines a post process to apply tone mapping
  83506. */
  83507. var TonemapPostProcess = /** @class */ (function (_super) {
  83508. __extends(TonemapPostProcess, _super);
  83509. /**
  83510. * Creates a new TonemapPostProcess
  83511. * @param name defines the name of the postprocess
  83512. * @param _operator defines the operator to use
  83513. * @param exposureAdjustment defines the required exposure adjustement
  83514. * @param camera defines the camera to use (can be null)
  83515. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  83516. * @param engine defines the hosting engine (can be ignore if camera is set)
  83517. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  83518. */
  83519. function TonemapPostProcess(name, _operator,
  83520. /** Defines the required exposure adjustement */
  83521. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  83522. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  83523. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  83524. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  83525. _this._operator = _operator;
  83526. _this.exposureAdjustment = exposureAdjustment;
  83527. var defines = "#define ";
  83528. if (_this._operator === TonemappingOperator.Hable)
  83529. defines += "HABLE_TONEMAPPING";
  83530. else if (_this._operator === TonemappingOperator.Reinhard)
  83531. defines += "REINHARD_TONEMAPPING";
  83532. else if (_this._operator === TonemappingOperator.HejiDawson)
  83533. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  83534. else if (_this._operator === TonemappingOperator.Photographic)
  83535. defines += "PHOTOGRAPHIC_TONEMAPPING";
  83536. //sadly a second call to create the effect.
  83537. _this.updateEffect(defines);
  83538. _this.onApply = function (effect) {
  83539. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  83540. };
  83541. return _this;
  83542. }
  83543. return TonemapPostProcess;
  83544. }(BABYLON.PostProcess));
  83545. BABYLON.TonemapPostProcess = TonemapPostProcess;
  83546. })(BABYLON || (BABYLON = {}));
  83547. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  83548. var BABYLON;
  83549. (function (BABYLON) {
  83550. var DisplayPassPostProcess = /** @class */ (function (_super) {
  83551. __extends(DisplayPassPostProcess, _super);
  83552. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  83553. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  83554. }
  83555. return DisplayPassPostProcess;
  83556. }(BABYLON.PostProcess));
  83557. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  83558. })(BABYLON || (BABYLON = {}));
  83559. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  83560. var BABYLON;
  83561. (function (BABYLON) {
  83562. var HighlightsPostProcess = /** @class */ (function (_super) {
  83563. __extends(HighlightsPostProcess, _super);
  83564. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  83565. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  83566. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  83567. }
  83568. return HighlightsPostProcess;
  83569. }(BABYLON.PostProcess));
  83570. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  83571. })(BABYLON || (BABYLON = {}));
  83572. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  83573. var BABYLON;
  83574. (function (BABYLON) {
  83575. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  83576. __extends(ImageProcessingPostProcess, _super);
  83577. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  83578. if (camera === void 0) { camera = null; }
  83579. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  83580. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  83581. _this._fromLinearSpace = true;
  83582. /**
  83583. * Defines cache preventing GC.
  83584. */
  83585. _this._defines = {
  83586. IMAGEPROCESSING: false,
  83587. VIGNETTE: false,
  83588. VIGNETTEBLENDMODEMULTIPLY: false,
  83589. VIGNETTEBLENDMODEOPAQUE: false,
  83590. TONEMAPPING: false,
  83591. TONEMAPPING_ACES: false,
  83592. CONTRAST: false,
  83593. COLORCURVES: false,
  83594. COLORGRADING: false,
  83595. COLORGRADING3D: false,
  83596. FROMLINEARSPACE: false,
  83597. SAMPLER3DGREENDEPTH: false,
  83598. SAMPLER3DBGRMAP: false,
  83599. IMAGEPROCESSINGPOSTPROCESS: false,
  83600. EXPOSURE: false,
  83601. };
  83602. // Setup the configuration as forced by the constructor. This would then not force the
  83603. // scene materials output in linear space and let untouched the default forward pass.
  83604. if (imageProcessingConfiguration) {
  83605. imageProcessingConfiguration.applyByPostProcess = true;
  83606. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  83607. // This will cause the shader to be compiled
  83608. _this.fromLinearSpace = false;
  83609. }
  83610. // Setup the default processing configuration to the scene.
  83611. else {
  83612. _this._attachImageProcessingConfiguration(null, true);
  83613. _this.imageProcessingConfiguration.applyByPostProcess = true;
  83614. }
  83615. _this.onApply = function (effect) {
  83616. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  83617. };
  83618. return _this;
  83619. }
  83620. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  83621. /**
  83622. * Gets the image processing configuration used either in this material.
  83623. */
  83624. get: function () {
  83625. return this._imageProcessingConfiguration;
  83626. },
  83627. /**
  83628. * Sets the Default image processing configuration used either in the this material.
  83629. *
  83630. * If sets to null, the scene one is in use.
  83631. */
  83632. set: function (value) {
  83633. this._attachImageProcessingConfiguration(value);
  83634. },
  83635. enumerable: true,
  83636. configurable: true
  83637. });
  83638. /**
  83639. * Attaches a new image processing configuration to the PBR Material.
  83640. * @param configuration
  83641. */
  83642. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  83643. var _this = this;
  83644. if (doNotBuild === void 0) { doNotBuild = false; }
  83645. if (configuration === this._imageProcessingConfiguration) {
  83646. return;
  83647. }
  83648. // Detaches observer.
  83649. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  83650. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  83651. }
  83652. // Pick the scene configuration if needed.
  83653. if (!configuration) {
  83654. var scene = null;
  83655. var engine = this.getEngine();
  83656. var camera = this.getCamera();
  83657. if (camera) {
  83658. scene = camera.getScene();
  83659. }
  83660. else if (engine && engine.scenes) {
  83661. var scenes = engine.scenes;
  83662. scene = scenes[scenes.length - 1];
  83663. }
  83664. else {
  83665. scene = BABYLON.Engine.LastCreatedScene;
  83666. }
  83667. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  83668. }
  83669. else {
  83670. this._imageProcessingConfiguration = configuration;
  83671. }
  83672. // Attaches observer.
  83673. if (this._imageProcessingConfiguration) {
  83674. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  83675. _this._updateParameters();
  83676. });
  83677. }
  83678. // Ensure the effect will be rebuilt.
  83679. if (!doNotBuild) {
  83680. this._updateParameters();
  83681. }
  83682. };
  83683. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  83684. /**
  83685. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  83686. */
  83687. get: function () {
  83688. return this.imageProcessingConfiguration.colorCurves;
  83689. },
  83690. /**
  83691. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  83692. */
  83693. set: function (value) {
  83694. this.imageProcessingConfiguration.colorCurves = value;
  83695. },
  83696. enumerable: true,
  83697. configurable: true
  83698. });
  83699. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  83700. /**
  83701. * Gets wether the color curves effect is enabled.
  83702. */
  83703. get: function () {
  83704. return this.imageProcessingConfiguration.colorCurvesEnabled;
  83705. },
  83706. /**
  83707. * Sets wether the color curves effect is enabled.
  83708. */
  83709. set: function (value) {
  83710. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  83711. },
  83712. enumerable: true,
  83713. configurable: true
  83714. });
  83715. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  83716. /**
  83717. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  83718. */
  83719. get: function () {
  83720. return this.imageProcessingConfiguration.colorGradingTexture;
  83721. },
  83722. /**
  83723. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  83724. */
  83725. set: function (value) {
  83726. this.imageProcessingConfiguration.colorGradingTexture = value;
  83727. },
  83728. enumerable: true,
  83729. configurable: true
  83730. });
  83731. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  83732. /**
  83733. * Gets wether the color grading effect is enabled.
  83734. */
  83735. get: function () {
  83736. return this.imageProcessingConfiguration.colorGradingEnabled;
  83737. },
  83738. /**
  83739. * Gets wether the color grading effect is enabled.
  83740. */
  83741. set: function (value) {
  83742. this.imageProcessingConfiguration.colorGradingEnabled = value;
  83743. },
  83744. enumerable: true,
  83745. configurable: true
  83746. });
  83747. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  83748. /**
  83749. * Gets exposure used in the effect.
  83750. */
  83751. get: function () {
  83752. return this.imageProcessingConfiguration.exposure;
  83753. },
  83754. /**
  83755. * Sets exposure used in the effect.
  83756. */
  83757. set: function (value) {
  83758. this.imageProcessingConfiguration.exposure = value;
  83759. },
  83760. enumerable: true,
  83761. configurable: true
  83762. });
  83763. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  83764. /**
  83765. * Gets wether tonemapping is enabled or not.
  83766. */
  83767. get: function () {
  83768. return this._imageProcessingConfiguration.toneMappingEnabled;
  83769. },
  83770. /**
  83771. * Sets wether tonemapping is enabled or not
  83772. */
  83773. set: function (value) {
  83774. this._imageProcessingConfiguration.toneMappingEnabled = value;
  83775. },
  83776. enumerable: true,
  83777. configurable: true
  83778. });
  83779. ;
  83780. ;
  83781. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  83782. /**
  83783. * Gets contrast used in the effect.
  83784. */
  83785. get: function () {
  83786. return this.imageProcessingConfiguration.contrast;
  83787. },
  83788. /**
  83789. * Sets contrast used in the effect.
  83790. */
  83791. set: function (value) {
  83792. this.imageProcessingConfiguration.contrast = value;
  83793. },
  83794. enumerable: true,
  83795. configurable: true
  83796. });
  83797. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  83798. /**
  83799. * Gets Vignette stretch size.
  83800. */
  83801. get: function () {
  83802. return this.imageProcessingConfiguration.vignetteStretch;
  83803. },
  83804. /**
  83805. * Sets Vignette stretch size.
  83806. */
  83807. set: function (value) {
  83808. this.imageProcessingConfiguration.vignetteStretch = value;
  83809. },
  83810. enumerable: true,
  83811. configurable: true
  83812. });
  83813. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  83814. /**
  83815. * Gets Vignette centre X Offset.
  83816. */
  83817. get: function () {
  83818. return this.imageProcessingConfiguration.vignetteCentreX;
  83819. },
  83820. /**
  83821. * Sets Vignette centre X Offset.
  83822. */
  83823. set: function (value) {
  83824. this.imageProcessingConfiguration.vignetteCentreX = value;
  83825. },
  83826. enumerable: true,
  83827. configurable: true
  83828. });
  83829. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  83830. /**
  83831. * Gets Vignette centre Y Offset.
  83832. */
  83833. get: function () {
  83834. return this.imageProcessingConfiguration.vignetteCentreY;
  83835. },
  83836. /**
  83837. * Sets Vignette centre Y Offset.
  83838. */
  83839. set: function (value) {
  83840. this.imageProcessingConfiguration.vignetteCentreY = value;
  83841. },
  83842. enumerable: true,
  83843. configurable: true
  83844. });
  83845. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  83846. /**
  83847. * Gets Vignette weight or intensity of the vignette effect.
  83848. */
  83849. get: function () {
  83850. return this.imageProcessingConfiguration.vignetteWeight;
  83851. },
  83852. /**
  83853. * Sets Vignette weight or intensity of the vignette effect.
  83854. */
  83855. set: function (value) {
  83856. this.imageProcessingConfiguration.vignetteWeight = value;
  83857. },
  83858. enumerable: true,
  83859. configurable: true
  83860. });
  83861. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  83862. /**
  83863. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  83864. * if vignetteEnabled is set to true.
  83865. */
  83866. get: function () {
  83867. return this.imageProcessingConfiguration.vignetteColor;
  83868. },
  83869. /**
  83870. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  83871. * if vignetteEnabled is set to true.
  83872. */
  83873. set: function (value) {
  83874. this.imageProcessingConfiguration.vignetteColor = value;
  83875. },
  83876. enumerable: true,
  83877. configurable: true
  83878. });
  83879. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  83880. /**
  83881. * Gets Camera field of view used by the Vignette effect.
  83882. */
  83883. get: function () {
  83884. return this.imageProcessingConfiguration.vignetteCameraFov;
  83885. },
  83886. /**
  83887. * Sets Camera field of view used by the Vignette effect.
  83888. */
  83889. set: function (value) {
  83890. this.imageProcessingConfiguration.vignetteCameraFov = value;
  83891. },
  83892. enumerable: true,
  83893. configurable: true
  83894. });
  83895. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  83896. /**
  83897. * Gets the vignette blend mode allowing different kind of effect.
  83898. */
  83899. get: function () {
  83900. return this.imageProcessingConfiguration.vignetteBlendMode;
  83901. },
  83902. /**
  83903. * Sets the vignette blend mode allowing different kind of effect.
  83904. */
  83905. set: function (value) {
  83906. this.imageProcessingConfiguration.vignetteBlendMode = value;
  83907. },
  83908. enumerable: true,
  83909. configurable: true
  83910. });
  83911. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  83912. /**
  83913. * Gets wether the vignette effect is enabled.
  83914. */
  83915. get: function () {
  83916. return this.imageProcessingConfiguration.vignetteEnabled;
  83917. },
  83918. /**
  83919. * Sets wether the vignette effect is enabled.
  83920. */
  83921. set: function (value) {
  83922. this.imageProcessingConfiguration.vignetteEnabled = value;
  83923. },
  83924. enumerable: true,
  83925. configurable: true
  83926. });
  83927. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  83928. /**
  83929. * Gets wether the input of the processing is in Gamma or Linear Space.
  83930. */
  83931. get: function () {
  83932. return this._fromLinearSpace;
  83933. },
  83934. /**
  83935. * Sets wether the input of the processing is in Gamma or Linear Space.
  83936. */
  83937. set: function (value) {
  83938. if (this._fromLinearSpace === value) {
  83939. return;
  83940. }
  83941. this._fromLinearSpace = value;
  83942. this._updateParameters();
  83943. },
  83944. enumerable: true,
  83945. configurable: true
  83946. });
  83947. ImageProcessingPostProcess.prototype.getClassName = function () {
  83948. return "ImageProcessingPostProcess";
  83949. };
  83950. ImageProcessingPostProcess.prototype._updateParameters = function () {
  83951. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  83952. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  83953. var defines = "";
  83954. for (var define in this._defines) {
  83955. if (this._defines[define]) {
  83956. defines += "#define " + define + ";\r\n";
  83957. }
  83958. }
  83959. var samplers = ["textureSampler"];
  83960. var uniforms = ["scale"];
  83961. if (BABYLON.ImageProcessingConfiguration) {
  83962. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  83963. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  83964. }
  83965. this.updateEffect(defines, uniforms, samplers);
  83966. };
  83967. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  83968. _super.prototype.dispose.call(this, camera);
  83969. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  83970. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  83971. }
  83972. if (this._imageProcessingConfiguration) {
  83973. this.imageProcessingConfiguration.applyByPostProcess = false;
  83974. }
  83975. };
  83976. __decorate([
  83977. BABYLON.serialize()
  83978. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  83979. return ImageProcessingPostProcess;
  83980. }(BABYLON.PostProcess));
  83981. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  83982. })(BABYLON || (BABYLON = {}));
  83983. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  83984. var BABYLON;
  83985. (function (BABYLON) {
  83986. /**
  83987. * Class used to store bone information
  83988. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  83989. */
  83990. var Bone = /** @class */ (function (_super) {
  83991. __extends(Bone, _super);
  83992. /**
  83993. * Create a new bone
  83994. * @param name defines the bone name
  83995. * @param skeleton defines the parent skeleton
  83996. * @param parentBone defines the parent (can be null if the bone is the root)
  83997. * @param localMatrix defines the local matrix
  83998. * @param restPose defines the rest pose matrix
  83999. * @param baseMatrix defines the base matrix
  84000. * @param index defines index of the bone in the hiearchy
  84001. */
  84002. function Bone(
  84003. /**
  84004. * defines the bone name
  84005. */
  84006. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  84007. if (parentBone === void 0) { parentBone = null; }
  84008. if (localMatrix === void 0) { localMatrix = null; }
  84009. if (restPose === void 0) { restPose = null; }
  84010. if (baseMatrix === void 0) { baseMatrix = null; }
  84011. if (index === void 0) { index = null; }
  84012. var _this = _super.call(this, name, skeleton.getScene()) || this;
  84013. _this.name = name;
  84014. /**
  84015. * Gets the list of child bones
  84016. */
  84017. _this.children = new Array();
  84018. /** Gets the animations associated with this bone */
  84019. _this.animations = new Array();
  84020. /**
  84021. * @hidden Internal only
  84022. * Set this value to map this bone to a different index in the transform matrices
  84023. * Set this value to -1 to exclude the bone from the transform matrices
  84024. */
  84025. _this._index = null;
  84026. _this._absoluteTransform = new BABYLON.Matrix();
  84027. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  84028. _this._scalingDeterminant = 1;
  84029. _this._worldTransform = new BABYLON.Matrix();
  84030. _this._needToDecompose = true;
  84031. _this._needToCompose = false;
  84032. _this._skeleton = skeleton;
  84033. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  84034. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  84035. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  84036. _this._index = index;
  84037. skeleton.bones.push(_this);
  84038. _this.setParent(parentBone, false);
  84039. if (baseMatrix || localMatrix) {
  84040. _this._updateDifferenceMatrix();
  84041. }
  84042. return _this;
  84043. }
  84044. Object.defineProperty(Bone.prototype, "_matrix", {
  84045. /** @hidden */
  84046. get: function () {
  84047. this._compose();
  84048. return this._localMatrix;
  84049. },
  84050. /** @hidden */
  84051. set: function (value) {
  84052. this._localMatrix.copyFrom(value);
  84053. this._needToDecompose = true;
  84054. },
  84055. enumerable: true,
  84056. configurable: true
  84057. });
  84058. // Members
  84059. /**
  84060. * Gets the parent skeleton
  84061. * @returns a skeleton
  84062. */
  84063. Bone.prototype.getSkeleton = function () {
  84064. return this._skeleton;
  84065. };
  84066. /**
  84067. * Gets parent bone
  84068. * @returns a bone or null if the bone is the root of the bone hierarchy
  84069. */
  84070. Bone.prototype.getParent = function () {
  84071. return this._parent;
  84072. };
  84073. /**
  84074. * Sets the parent bone
  84075. * @param parent defines the parent (can be null if the bone is the root)
  84076. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  84077. */
  84078. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  84079. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  84080. if (this._parent === parent) {
  84081. return;
  84082. }
  84083. if (this._parent) {
  84084. var index = this._parent.children.indexOf(this);
  84085. if (index !== -1) {
  84086. this._parent.children.splice(index, 1);
  84087. }
  84088. }
  84089. this._parent = parent;
  84090. if (this._parent) {
  84091. this._parent.children.push(this);
  84092. }
  84093. if (updateDifferenceMatrix) {
  84094. this._updateDifferenceMatrix();
  84095. }
  84096. this.markAsDirty();
  84097. };
  84098. /**
  84099. * Gets the local matrix
  84100. * @returns a matrix
  84101. */
  84102. Bone.prototype.getLocalMatrix = function () {
  84103. this._compose();
  84104. return this._localMatrix;
  84105. };
  84106. /**
  84107. * Gets the base matrix (initial matrix which remains unchanged)
  84108. * @returns a matrix
  84109. */
  84110. Bone.prototype.getBaseMatrix = function () {
  84111. return this._baseMatrix;
  84112. };
  84113. /**
  84114. * Gets the rest pose matrix
  84115. * @returns a matrix
  84116. */
  84117. Bone.prototype.getRestPose = function () {
  84118. return this._restPose;
  84119. };
  84120. /**
  84121. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  84122. */
  84123. Bone.prototype.getWorldMatrix = function () {
  84124. return this._worldTransform;
  84125. };
  84126. /**
  84127. * Sets the local matrix to rest pose matrix
  84128. */
  84129. Bone.prototype.returnToRest = function () {
  84130. this.updateMatrix(this._restPose.clone());
  84131. };
  84132. /**
  84133. * Gets the inverse of the absolute transform matrix.
  84134. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  84135. * @returns a matrix
  84136. */
  84137. Bone.prototype.getInvertedAbsoluteTransform = function () {
  84138. return this._invertedAbsoluteTransform;
  84139. };
  84140. /**
  84141. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  84142. * @returns a matrix
  84143. */
  84144. Bone.prototype.getAbsoluteTransform = function () {
  84145. return this._absoluteTransform;
  84146. };
  84147. Object.defineProperty(Bone.prototype, "position", {
  84148. // Properties (matches AbstractMesh properties)
  84149. /** Gets or sets current position (in local space) */
  84150. get: function () {
  84151. this._decompose();
  84152. return this._localPosition;
  84153. },
  84154. set: function (newPosition) {
  84155. this._decompose();
  84156. this._localPosition.copyFrom(newPosition);
  84157. this._markAsDirtyAndCompose();
  84158. },
  84159. enumerable: true,
  84160. configurable: true
  84161. });
  84162. Object.defineProperty(Bone.prototype, "rotation", {
  84163. /** Gets or sets current rotation (in local space) */
  84164. get: function () {
  84165. return this.getRotation();
  84166. },
  84167. set: function (newRotation) {
  84168. this.setRotation(newRotation);
  84169. },
  84170. enumerable: true,
  84171. configurable: true
  84172. });
  84173. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  84174. /** Gets or sets current rotation quaternion (in local space) */
  84175. get: function () {
  84176. this._decompose();
  84177. return this._localRotation;
  84178. },
  84179. set: function (newRotation) {
  84180. this.setRotationQuaternion(newRotation);
  84181. },
  84182. enumerable: true,
  84183. configurable: true
  84184. });
  84185. Object.defineProperty(Bone.prototype, "scaling", {
  84186. /** Gets or sets current scaling (in local space) */
  84187. get: function () {
  84188. return this.getScale();
  84189. },
  84190. set: function (newScaling) {
  84191. this.setScale(newScaling);
  84192. },
  84193. enumerable: true,
  84194. configurable: true
  84195. });
  84196. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  84197. /**
  84198. * Gets the animation properties override
  84199. */
  84200. get: function () {
  84201. return this._skeleton.animationPropertiesOverride;
  84202. },
  84203. enumerable: true,
  84204. configurable: true
  84205. });
  84206. // Methods
  84207. Bone.prototype._decompose = function () {
  84208. if (!this._needToDecompose) {
  84209. return;
  84210. }
  84211. this._needToDecompose = false;
  84212. if (!this._localScaling) {
  84213. this._localScaling = BABYLON.Vector3.Zero();
  84214. this._localRotation = BABYLON.Quaternion.Zero();
  84215. this._localPosition = BABYLON.Vector3.Zero();
  84216. }
  84217. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  84218. };
  84219. Bone.prototype._compose = function () {
  84220. if (!this._needToCompose) {
  84221. return;
  84222. }
  84223. this._needToCompose = false;
  84224. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  84225. };
  84226. /**
  84227. * Update the base and local matrices
  84228. * @param matrix defines the new base or local matrix
  84229. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  84230. * @param updateLocalMatrix defines if the local matrix should be updated
  84231. */
  84232. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  84233. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  84234. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  84235. this._baseMatrix.copyFrom(matrix);
  84236. if (updateDifferenceMatrix) {
  84237. this._updateDifferenceMatrix();
  84238. }
  84239. if (updateLocalMatrix) {
  84240. this._localMatrix.copyFrom(matrix);
  84241. this._markAsDirtyAndDecompose();
  84242. }
  84243. else {
  84244. this.markAsDirty();
  84245. }
  84246. };
  84247. /** @hidden */
  84248. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  84249. if (updateChildren === void 0) { updateChildren = true; }
  84250. if (!rootMatrix) {
  84251. rootMatrix = this._baseMatrix;
  84252. }
  84253. if (this._parent) {
  84254. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  84255. }
  84256. else {
  84257. this._absoluteTransform.copyFrom(rootMatrix);
  84258. }
  84259. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  84260. if (updateChildren) {
  84261. for (var index = 0; index < this.children.length; index++) {
  84262. this.children[index]._updateDifferenceMatrix();
  84263. }
  84264. }
  84265. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  84266. };
  84267. /**
  84268. * Flag the bone as dirty (Forcing it to update everything)
  84269. */
  84270. Bone.prototype.markAsDirty = function () {
  84271. this._currentRenderId++;
  84272. this._childRenderId++;
  84273. this._skeleton._markAsDirty();
  84274. };
  84275. Bone.prototype._markAsDirtyAndCompose = function () {
  84276. this.markAsDirty();
  84277. this._needToCompose = true;
  84278. };
  84279. Bone.prototype._markAsDirtyAndDecompose = function () {
  84280. this.markAsDirty();
  84281. this._needToDecompose = true;
  84282. };
  84283. /**
  84284. * Copy an animation range from another bone
  84285. * @param source defines the source bone
  84286. * @param rangeName defines the range name to copy
  84287. * @param frameOffset defines the frame offset
  84288. * @param rescaleAsRequired defines if rescaling must be applied if required
  84289. * @param skelDimensionsRatio defines the scaling ratio
  84290. * @returns true if operation was successful
  84291. */
  84292. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  84293. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  84294. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  84295. // all animation may be coming from a library skeleton, so may need to create animation
  84296. if (this.animations.length === 0) {
  84297. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  84298. this.animations[0].setKeys([]);
  84299. }
  84300. // get animation info / verify there is such a range from the source bone
  84301. var sourceRange = source.animations[0].getRange(rangeName);
  84302. if (!sourceRange) {
  84303. return false;
  84304. }
  84305. var from = sourceRange.from;
  84306. var to = sourceRange.to;
  84307. var sourceKeys = source.animations[0].getKeys();
  84308. // rescaling prep
  84309. var sourceBoneLength = source.length;
  84310. var sourceParent = source.getParent();
  84311. var parent = this.getParent();
  84312. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  84313. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  84314. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  84315. var destKeys = this.animations[0].getKeys();
  84316. // loop vars declaration
  84317. var orig;
  84318. var origTranslation;
  84319. var mat;
  84320. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  84321. orig = sourceKeys[key];
  84322. if (orig.frame >= from && orig.frame <= to) {
  84323. if (rescaleAsRequired) {
  84324. mat = orig.value.clone();
  84325. // scale based on parent ratio, when bone has parent
  84326. if (parentScalingReqd) {
  84327. origTranslation = mat.getTranslation();
  84328. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  84329. // scale based on skeleton dimension ratio when root bone, and value is passed
  84330. }
  84331. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  84332. origTranslation = mat.getTranslation();
  84333. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  84334. // use original when root bone, and no data for skelDimensionsRatio
  84335. }
  84336. else {
  84337. mat = orig.value;
  84338. }
  84339. }
  84340. else {
  84341. mat = orig.value;
  84342. }
  84343. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  84344. }
  84345. }
  84346. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  84347. return true;
  84348. };
  84349. /**
  84350. * Translate the bone in local or world space
  84351. * @param vec The amount to translate the bone
  84352. * @param space The space that the translation is in
  84353. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84354. */
  84355. Bone.prototype.translate = function (vec, space, mesh) {
  84356. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84357. var lm = this.getLocalMatrix();
  84358. if (space == BABYLON.Space.LOCAL) {
  84359. lm.m[12] += vec.x;
  84360. lm.m[13] += vec.y;
  84361. lm.m[14] += vec.z;
  84362. }
  84363. else {
  84364. var wm = null;
  84365. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  84366. if (mesh) {
  84367. wm = mesh.getWorldMatrix();
  84368. }
  84369. this._skeleton.computeAbsoluteTransforms();
  84370. var tmat = Bone._tmpMats[0];
  84371. var tvec = Bone._tmpVecs[0];
  84372. if (this._parent) {
  84373. if (mesh && wm) {
  84374. tmat.copyFrom(this._parent.getAbsoluteTransform());
  84375. tmat.multiplyToRef(wm, tmat);
  84376. }
  84377. else {
  84378. tmat.copyFrom(this._parent.getAbsoluteTransform());
  84379. }
  84380. }
  84381. tmat.m[12] = 0;
  84382. tmat.m[13] = 0;
  84383. tmat.m[14] = 0;
  84384. tmat.invert();
  84385. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  84386. lm.m[12] += tvec.x;
  84387. lm.m[13] += tvec.y;
  84388. lm.m[14] += tvec.z;
  84389. }
  84390. this._markAsDirtyAndDecompose();
  84391. };
  84392. /**
  84393. * Set the postion of the bone in local or world space
  84394. * @param position The position to set the bone
  84395. * @param space The space that the position is in
  84396. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84397. */
  84398. Bone.prototype.setPosition = function (position, space, mesh) {
  84399. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84400. var lm = this.getLocalMatrix();
  84401. if (space == BABYLON.Space.LOCAL) {
  84402. lm.m[12] = position.x;
  84403. lm.m[13] = position.y;
  84404. lm.m[14] = position.z;
  84405. }
  84406. else {
  84407. var wm = null;
  84408. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  84409. if (mesh) {
  84410. wm = mesh.getWorldMatrix();
  84411. }
  84412. this._skeleton.computeAbsoluteTransforms();
  84413. var tmat = Bone._tmpMats[0];
  84414. var vec = Bone._tmpVecs[0];
  84415. if (this._parent) {
  84416. if (mesh && wm) {
  84417. tmat.copyFrom(this._parent.getAbsoluteTransform());
  84418. tmat.multiplyToRef(wm, tmat);
  84419. }
  84420. else {
  84421. tmat.copyFrom(this._parent.getAbsoluteTransform());
  84422. }
  84423. }
  84424. tmat.invert();
  84425. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  84426. lm.m[12] = vec.x;
  84427. lm.m[13] = vec.y;
  84428. lm.m[14] = vec.z;
  84429. }
  84430. this._markAsDirtyAndDecompose();
  84431. };
  84432. /**
  84433. * Set the absolute position of the bone (world space)
  84434. * @param position The position to set the bone
  84435. * @param mesh The mesh that this bone is attached to
  84436. */
  84437. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  84438. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  84439. };
  84440. /**
  84441. * Scale the bone on the x, y and z axes (in local space)
  84442. * @param x The amount to scale the bone on the x axis
  84443. * @param y The amount to scale the bone on the y axis
  84444. * @param z The amount to scale the bone on the z axis
  84445. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  84446. */
  84447. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  84448. if (scaleChildren === void 0) { scaleChildren = false; }
  84449. var locMat = this.getLocalMatrix();
  84450. // Apply new scaling on top of current local matrix
  84451. var scaleMat = Bone._tmpMats[0];
  84452. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  84453. scaleMat.multiplyToRef(locMat, locMat);
  84454. // Invert scaling matrix and apply the inverse to all children
  84455. scaleMat.invert();
  84456. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  84457. var child = _a[_i];
  84458. var cm = child.getLocalMatrix();
  84459. cm.multiplyToRef(scaleMat, cm);
  84460. cm.m[12] *= x;
  84461. cm.m[13] *= y;
  84462. cm.m[14] *= z;
  84463. child._markAsDirtyAndDecompose();
  84464. }
  84465. this._markAsDirtyAndDecompose();
  84466. if (scaleChildren) {
  84467. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  84468. var child = _c[_b];
  84469. child.scale(x, y, z, scaleChildren);
  84470. }
  84471. }
  84472. };
  84473. /**
  84474. * Set the bone scaling in local space
  84475. * @param scale defines the scaling vector
  84476. */
  84477. Bone.prototype.setScale = function (scale) {
  84478. this._decompose();
  84479. this._localScaling.copyFrom(scale);
  84480. this._markAsDirtyAndCompose();
  84481. };
  84482. /**
  84483. * Gets the current scaling in local space
  84484. * @returns the current scaling vector
  84485. */
  84486. Bone.prototype.getScale = function () {
  84487. this._decompose();
  84488. return this._localScaling;
  84489. };
  84490. /**
  84491. * Gets the current scaling in local space and stores it in a target vector
  84492. * @param result defines the target vector
  84493. */
  84494. Bone.prototype.getScaleToRef = function (result) {
  84495. this._decompose();
  84496. result.copyFrom(this._localScaling);
  84497. };
  84498. /**
  84499. * Set the yaw, pitch, and roll of the bone in local or world space
  84500. * @param yaw The rotation of the bone on the y axis
  84501. * @param pitch The rotation of the bone on the x axis
  84502. * @param roll The rotation of the bone on the z axis
  84503. * @param space The space that the axes of rotation are in
  84504. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84505. */
  84506. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  84507. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84508. if (space === BABYLON.Space.LOCAL) {
  84509. var quat = Bone._tmpQuat;
  84510. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  84511. this.setRotationQuaternion(quat, space, mesh);
  84512. return;
  84513. }
  84514. var rotMatInv = Bone._tmpMats[0];
  84515. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  84516. return;
  84517. }
  84518. var rotMat = Bone._tmpMats[1];
  84519. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  84520. rotMatInv.multiplyToRef(rotMat, rotMat);
  84521. this._rotateWithMatrix(rotMat, space, mesh);
  84522. };
  84523. /**
  84524. * Add a rotation to the bone on an axis in local or world space
  84525. * @param axis The axis to rotate the bone on
  84526. * @param amount The amount to rotate the bone
  84527. * @param space The space that the axis is in
  84528. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84529. */
  84530. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  84531. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84532. var rmat = Bone._tmpMats[0];
  84533. rmat.m[12] = 0;
  84534. rmat.m[13] = 0;
  84535. rmat.m[14] = 0;
  84536. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  84537. this._rotateWithMatrix(rmat, space, mesh);
  84538. };
  84539. /**
  84540. * Set the rotation of the bone to a particular axis angle in local or world space
  84541. * @param axis The axis to rotate the bone on
  84542. * @param angle The angle that the bone should be rotated to
  84543. * @param space The space that the axis is in
  84544. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84545. */
  84546. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  84547. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84548. if (space === BABYLON.Space.LOCAL) {
  84549. var quat = Bone._tmpQuat;
  84550. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  84551. this.setRotationQuaternion(quat, space, mesh);
  84552. return;
  84553. }
  84554. var rotMatInv = Bone._tmpMats[0];
  84555. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  84556. return;
  84557. }
  84558. var rotMat = Bone._tmpMats[1];
  84559. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  84560. rotMatInv.multiplyToRef(rotMat, rotMat);
  84561. this._rotateWithMatrix(rotMat, space, mesh);
  84562. };
  84563. /**
  84564. * Set the euler rotation of the bone in local of world space
  84565. * @param rotation The euler rotation that the bone should be set to
  84566. * @param space The space that the rotation is in
  84567. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84568. */
  84569. Bone.prototype.setRotation = function (rotation, space, mesh) {
  84570. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84571. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  84572. };
  84573. /**
  84574. * Set the quaternion rotation of the bone in local of world space
  84575. * @param quat The quaternion rotation that the bone should be set to
  84576. * @param space The space that the rotation is in
  84577. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84578. */
  84579. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  84580. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84581. if (space === BABYLON.Space.LOCAL) {
  84582. this._decompose();
  84583. this._localRotation.copyFrom(quat);
  84584. this._markAsDirtyAndCompose();
  84585. return;
  84586. }
  84587. var rotMatInv = Bone._tmpMats[0];
  84588. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  84589. return;
  84590. }
  84591. var rotMat = Bone._tmpMats[1];
  84592. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  84593. rotMatInv.multiplyToRef(rotMat, rotMat);
  84594. this._rotateWithMatrix(rotMat, space, mesh);
  84595. };
  84596. /**
  84597. * Set the rotation matrix of the bone in local of world space
  84598. * @param rotMat The rotation matrix that the bone should be set to
  84599. * @param space The space that the rotation is in
  84600. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84601. */
  84602. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  84603. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84604. if (space === BABYLON.Space.LOCAL) {
  84605. var quat = Bone._tmpQuat;
  84606. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  84607. this.setRotationQuaternion(quat, space, mesh);
  84608. return;
  84609. }
  84610. var rotMatInv = Bone._tmpMats[0];
  84611. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  84612. return;
  84613. }
  84614. var rotMat2 = Bone._tmpMats[1];
  84615. rotMat2.copyFrom(rotMat);
  84616. rotMatInv.multiplyToRef(rotMat, rotMat2);
  84617. this._rotateWithMatrix(rotMat2, space, mesh);
  84618. };
  84619. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  84620. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84621. var lmat = this.getLocalMatrix();
  84622. var lx = lmat.m[12];
  84623. var ly = lmat.m[13];
  84624. var lz = lmat.m[14];
  84625. var parent = this.getParent();
  84626. var parentScale = Bone._tmpMats[3];
  84627. var parentScaleInv = Bone._tmpMats[4];
  84628. if (parent && space == BABYLON.Space.WORLD) {
  84629. if (mesh) {
  84630. parentScale.copyFrom(mesh.getWorldMatrix());
  84631. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  84632. }
  84633. else {
  84634. parentScale.copyFrom(parent.getAbsoluteTransform());
  84635. }
  84636. parentScaleInv.copyFrom(parentScale);
  84637. parentScaleInv.invert();
  84638. lmat.multiplyToRef(parentScale, lmat);
  84639. lmat.multiplyToRef(rmat, lmat);
  84640. lmat.multiplyToRef(parentScaleInv, lmat);
  84641. }
  84642. else {
  84643. if (space == BABYLON.Space.WORLD && mesh) {
  84644. parentScale.copyFrom(mesh.getWorldMatrix());
  84645. parentScaleInv.copyFrom(parentScale);
  84646. parentScaleInv.invert();
  84647. lmat.multiplyToRef(parentScale, lmat);
  84648. lmat.multiplyToRef(rmat, lmat);
  84649. lmat.multiplyToRef(parentScaleInv, lmat);
  84650. }
  84651. else {
  84652. lmat.multiplyToRef(rmat, lmat);
  84653. }
  84654. }
  84655. lmat.m[12] = lx;
  84656. lmat.m[13] = ly;
  84657. lmat.m[14] = lz;
  84658. this.computeAbsoluteTransforms();
  84659. this._markAsDirtyAndDecompose();
  84660. };
  84661. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  84662. var scaleMatrix = Bone._tmpMats[2];
  84663. rotMatInv.copyFrom(this.getAbsoluteTransform());
  84664. if (mesh) {
  84665. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  84666. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  84667. }
  84668. rotMatInv.invert();
  84669. if (isNaN(rotMatInv.m[0])) {
  84670. // Matrix failed to invert.
  84671. // This can happen if scale is zero for example.
  84672. return false;
  84673. }
  84674. scaleMatrix.m[0] *= this._scalingDeterminant;
  84675. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  84676. return true;
  84677. };
  84678. /**
  84679. * Get the position of the bone in local or world space
  84680. * @param space The space that the returned position is in
  84681. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84682. * @returns The position of the bone
  84683. */
  84684. Bone.prototype.getPosition = function (space, mesh) {
  84685. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84686. if (mesh === void 0) { mesh = null; }
  84687. var pos = BABYLON.Vector3.Zero();
  84688. this.getPositionToRef(space, mesh, pos);
  84689. return pos;
  84690. };
  84691. /**
  84692. * Copy the position of the bone to a vector3 in local or world space
  84693. * @param space The space that the returned position is in
  84694. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84695. * @param result The vector3 to copy the position to
  84696. */
  84697. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  84698. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84699. if (space == BABYLON.Space.LOCAL) {
  84700. var lm = this.getLocalMatrix();
  84701. result.x = lm.m[12];
  84702. result.y = lm.m[13];
  84703. result.z = lm.m[14];
  84704. }
  84705. else {
  84706. var wm = null;
  84707. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  84708. if (mesh) {
  84709. wm = mesh.getWorldMatrix();
  84710. }
  84711. this._skeleton.computeAbsoluteTransforms();
  84712. var tmat = Bone._tmpMats[0];
  84713. if (mesh && wm) {
  84714. tmat.copyFrom(this.getAbsoluteTransform());
  84715. tmat.multiplyToRef(wm, tmat);
  84716. }
  84717. else {
  84718. tmat = this.getAbsoluteTransform();
  84719. }
  84720. result.x = tmat.m[12];
  84721. result.y = tmat.m[13];
  84722. result.z = tmat.m[14];
  84723. }
  84724. };
  84725. /**
  84726. * Get the absolute position of the bone (world space)
  84727. * @param mesh The mesh that this bone is attached to
  84728. * @returns The absolute position of the bone
  84729. */
  84730. Bone.prototype.getAbsolutePosition = function (mesh) {
  84731. if (mesh === void 0) { mesh = null; }
  84732. var pos = BABYLON.Vector3.Zero();
  84733. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  84734. return pos;
  84735. };
  84736. /**
  84737. * Copy the absolute position of the bone (world space) to the result param
  84738. * @param mesh The mesh that this bone is attached to
  84739. * @param result The vector3 to copy the absolute position to
  84740. */
  84741. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  84742. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  84743. };
  84744. /**
  84745. * Compute the absolute transforms of this bone and its children
  84746. */
  84747. Bone.prototype.computeAbsoluteTransforms = function () {
  84748. this._compose();
  84749. if (this._parent) {
  84750. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  84751. }
  84752. else {
  84753. this._absoluteTransform.copyFrom(this._localMatrix);
  84754. var poseMatrix = this._skeleton.getPoseMatrix();
  84755. if (poseMatrix) {
  84756. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  84757. }
  84758. }
  84759. var children = this.children;
  84760. var len = children.length;
  84761. for (var i = 0; i < len; i++) {
  84762. children[i].computeAbsoluteTransforms();
  84763. }
  84764. };
  84765. /**
  84766. * Get the world direction from an axis that is in the local space of the bone
  84767. * @param localAxis The local direction that is used to compute the world direction
  84768. * @param mesh The mesh that this bone is attached to
  84769. * @returns The world direction
  84770. */
  84771. Bone.prototype.getDirection = function (localAxis, mesh) {
  84772. if (mesh === void 0) { mesh = null; }
  84773. var result = BABYLON.Vector3.Zero();
  84774. this.getDirectionToRef(localAxis, mesh, result);
  84775. return result;
  84776. };
  84777. /**
  84778. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  84779. * @param localAxis The local direction that is used to compute the world direction
  84780. * @param mesh The mesh that this bone is attached to
  84781. * @param result The vector3 that the world direction will be copied to
  84782. */
  84783. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  84784. if (mesh === void 0) { mesh = null; }
  84785. var wm = null;
  84786. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  84787. if (mesh) {
  84788. wm = mesh.getWorldMatrix();
  84789. }
  84790. this._skeleton.computeAbsoluteTransforms();
  84791. var mat = Bone._tmpMats[0];
  84792. mat.copyFrom(this.getAbsoluteTransform());
  84793. if (mesh && wm) {
  84794. mat.multiplyToRef(wm, mat);
  84795. }
  84796. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  84797. result.normalize();
  84798. };
  84799. /**
  84800. * Get the euler rotation of the bone in local or world space
  84801. * @param space The space that the rotation should be in
  84802. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84803. * @returns The euler rotation
  84804. */
  84805. Bone.prototype.getRotation = function (space, mesh) {
  84806. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84807. if (mesh === void 0) { mesh = null; }
  84808. var result = BABYLON.Vector3.Zero();
  84809. this.getRotationToRef(space, mesh, result);
  84810. return result;
  84811. };
  84812. /**
  84813. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  84814. * @param space The space that the rotation should be in
  84815. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84816. * @param result The vector3 that the rotation should be copied to
  84817. */
  84818. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  84819. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84820. if (mesh === void 0) { mesh = null; }
  84821. var quat = Bone._tmpQuat;
  84822. this.getRotationQuaternionToRef(space, mesh, quat);
  84823. quat.toEulerAnglesToRef(result);
  84824. };
  84825. /**
  84826. * Get the quaternion rotation of the bone in either local or world space
  84827. * @param space The space that the rotation should be in
  84828. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84829. * @returns The quaternion rotation
  84830. */
  84831. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  84832. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84833. if (mesh === void 0) { mesh = null; }
  84834. var result = BABYLON.Quaternion.Identity();
  84835. this.getRotationQuaternionToRef(space, mesh, result);
  84836. return result;
  84837. };
  84838. /**
  84839. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  84840. * @param space The space that the rotation should be in
  84841. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84842. * @param result The quaternion that the rotation should be copied to
  84843. */
  84844. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  84845. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84846. if (mesh === void 0) { mesh = null; }
  84847. if (space == BABYLON.Space.LOCAL) {
  84848. this._decompose();
  84849. result.copyFrom(this._localRotation);
  84850. }
  84851. else {
  84852. var mat = Bone._tmpMats[0];
  84853. var amat = this.getAbsoluteTransform();
  84854. if (mesh) {
  84855. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  84856. }
  84857. else {
  84858. mat.copyFrom(amat);
  84859. }
  84860. mat.m[0] *= this._scalingDeterminant;
  84861. mat.m[1] *= this._scalingDeterminant;
  84862. mat.m[2] *= this._scalingDeterminant;
  84863. mat.decompose(undefined, result, undefined);
  84864. }
  84865. };
  84866. /**
  84867. * Get the rotation matrix of the bone in local or world space
  84868. * @param space The space that the rotation should be in
  84869. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84870. * @returns The rotation matrix
  84871. */
  84872. Bone.prototype.getRotationMatrix = function (space, mesh) {
  84873. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84874. var result = BABYLON.Matrix.Identity();
  84875. this.getRotationMatrixToRef(space, mesh, result);
  84876. return result;
  84877. };
  84878. /**
  84879. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  84880. * @param space The space that the rotation should be in
  84881. * @param mesh The mesh that this bone is attached to. This is only used in world space
  84882. * @param result The quaternion that the rotation should be copied to
  84883. */
  84884. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  84885. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  84886. if (space == BABYLON.Space.LOCAL) {
  84887. this.getLocalMatrix().getRotationMatrixToRef(result);
  84888. }
  84889. else {
  84890. var mat = Bone._tmpMats[0];
  84891. var amat = this.getAbsoluteTransform();
  84892. if (mesh) {
  84893. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  84894. }
  84895. else {
  84896. mat.copyFrom(amat);
  84897. }
  84898. mat.m[0] *= this._scalingDeterminant;
  84899. mat.m[1] *= this._scalingDeterminant;
  84900. mat.m[2] *= this._scalingDeterminant;
  84901. mat.getRotationMatrixToRef(result);
  84902. }
  84903. };
  84904. /**
  84905. * Get the world position of a point that is in the local space of the bone
  84906. * @param position The local position
  84907. * @param mesh The mesh that this bone is attached to
  84908. * @returns The world position
  84909. */
  84910. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  84911. if (mesh === void 0) { mesh = null; }
  84912. var result = BABYLON.Vector3.Zero();
  84913. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  84914. return result;
  84915. };
  84916. /**
  84917. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  84918. * @param position The local position
  84919. * @param mesh The mesh that this bone is attached to
  84920. * @param result The vector3 that the world position should be copied to
  84921. */
  84922. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  84923. if (mesh === void 0) { mesh = null; }
  84924. var wm = null;
  84925. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  84926. if (mesh) {
  84927. wm = mesh.getWorldMatrix();
  84928. }
  84929. this._skeleton.computeAbsoluteTransforms();
  84930. var tmat = Bone._tmpMats[0];
  84931. if (mesh && wm) {
  84932. tmat.copyFrom(this.getAbsoluteTransform());
  84933. tmat.multiplyToRef(wm, tmat);
  84934. }
  84935. else {
  84936. tmat = this.getAbsoluteTransform();
  84937. }
  84938. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  84939. };
  84940. /**
  84941. * Get the local position of a point that is in world space
  84942. * @param position The world position
  84943. * @param mesh The mesh that this bone is attached to
  84944. * @returns The local position
  84945. */
  84946. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  84947. if (mesh === void 0) { mesh = null; }
  84948. var result = BABYLON.Vector3.Zero();
  84949. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  84950. return result;
  84951. };
  84952. /**
  84953. * Get the local position of a point that is in world space and copy it to the result param
  84954. * @param position The world position
  84955. * @param mesh The mesh that this bone is attached to
  84956. * @param result The vector3 that the local position should be copied to
  84957. */
  84958. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  84959. if (mesh === void 0) { mesh = null; }
  84960. var wm = null;
  84961. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  84962. if (mesh) {
  84963. wm = mesh.getWorldMatrix();
  84964. }
  84965. this._skeleton.computeAbsoluteTransforms();
  84966. var tmat = Bone._tmpMats[0];
  84967. tmat.copyFrom(this.getAbsoluteTransform());
  84968. if (mesh && wm) {
  84969. tmat.multiplyToRef(wm, tmat);
  84970. }
  84971. tmat.invert();
  84972. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  84973. };
  84974. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84975. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  84976. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  84977. return Bone;
  84978. }(BABYLON.Node));
  84979. BABYLON.Bone = Bone;
  84980. })(BABYLON || (BABYLON = {}));
  84981. //# sourceMappingURL=babylon.bone.js.map
  84982. var BABYLON;
  84983. (function (BABYLON) {
  84984. /**
  84985. * Class used to apply inverse kinematics to bones
  84986. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  84987. */
  84988. var BoneIKController = /** @class */ (function () {
  84989. /**
  84990. * Creates a new BoneIKController
  84991. * @param mesh defines the mesh to control
  84992. * @param bone defines the bone to control
  84993. * @param options defines options to set up the controller
  84994. */
  84995. function BoneIKController(mesh, bone, options) {
  84996. /**
  84997. * Gets or sets the target position
  84998. */
  84999. this.targetPosition = BABYLON.Vector3.Zero();
  85000. /**
  85001. * Gets or sets the pole target position
  85002. */
  85003. this.poleTargetPosition = BABYLON.Vector3.Zero();
  85004. /**
  85005. * Gets or sets the pole target local offset
  85006. */
  85007. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  85008. /**
  85009. * Gets or sets the pole angle
  85010. */
  85011. this.poleAngle = 0;
  85012. /**
  85013. * 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)
  85014. */
  85015. this.slerpAmount = 1;
  85016. this._bone1Quat = BABYLON.Quaternion.Identity();
  85017. this._bone1Mat = BABYLON.Matrix.Identity();
  85018. this._bone2Ang = Math.PI;
  85019. this._maxAngle = Math.PI;
  85020. this._rightHandedSystem = false;
  85021. this._bendAxis = BABYLON.Vector3.Right();
  85022. this._slerping = false;
  85023. this._adjustRoll = 0;
  85024. this._bone2 = bone;
  85025. this._bone1 = bone.getParent();
  85026. if (!this._bone1) {
  85027. return;
  85028. }
  85029. this.mesh = mesh;
  85030. var bonePos = bone.getPosition();
  85031. if (bone.getAbsoluteTransform().determinant() > 0) {
  85032. this._rightHandedSystem = true;
  85033. this._bendAxis.x = 0;
  85034. this._bendAxis.y = 0;
  85035. this._bendAxis.z = -1;
  85036. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  85037. this._adjustRoll = Math.PI * .5;
  85038. this._bendAxis.z = 1;
  85039. }
  85040. }
  85041. if (this._bone1.length) {
  85042. var boneScale1 = this._bone1.getScale();
  85043. var boneScale2 = this._bone2.getScale();
  85044. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  85045. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  85046. }
  85047. else if (this._bone1.children[0]) {
  85048. mesh.computeWorldMatrix(true);
  85049. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  85050. var pos2 = this._bone2.getAbsolutePosition(mesh);
  85051. var pos3 = this._bone1.getAbsolutePosition(mesh);
  85052. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  85053. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  85054. }
  85055. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  85056. this.maxAngle = Math.PI;
  85057. if (options) {
  85058. if (options.targetMesh) {
  85059. this.targetMesh = options.targetMesh;
  85060. this.targetMesh.computeWorldMatrix(true);
  85061. }
  85062. if (options.poleTargetMesh) {
  85063. this.poleTargetMesh = options.poleTargetMesh;
  85064. this.poleTargetMesh.computeWorldMatrix(true);
  85065. }
  85066. else if (options.poleTargetBone) {
  85067. this.poleTargetBone = options.poleTargetBone;
  85068. }
  85069. else if (this._bone1.getParent()) {
  85070. this.poleTargetBone = this._bone1.getParent();
  85071. }
  85072. if (options.poleTargetLocalOffset) {
  85073. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  85074. }
  85075. if (options.poleAngle) {
  85076. this.poleAngle = options.poleAngle;
  85077. }
  85078. if (options.bendAxis) {
  85079. this._bendAxis.copyFrom(options.bendAxis);
  85080. }
  85081. if (options.maxAngle) {
  85082. this.maxAngle = options.maxAngle;
  85083. }
  85084. if (options.slerpAmount) {
  85085. this.slerpAmount = options.slerpAmount;
  85086. }
  85087. }
  85088. }
  85089. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  85090. /**
  85091. * Gets or sets maximum allowed angle
  85092. */
  85093. get: function () {
  85094. return this._maxAngle;
  85095. },
  85096. set: function (value) {
  85097. this._setMaxAngle(value);
  85098. },
  85099. enumerable: true,
  85100. configurable: true
  85101. });
  85102. BoneIKController.prototype._setMaxAngle = function (ang) {
  85103. if (ang < 0) {
  85104. ang = 0;
  85105. }
  85106. if (ang > Math.PI || ang == undefined) {
  85107. ang = Math.PI;
  85108. }
  85109. this._maxAngle = ang;
  85110. var a = this._bone1Length;
  85111. var b = this._bone2Length;
  85112. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  85113. };
  85114. /**
  85115. * Force the controller to update the bones
  85116. */
  85117. BoneIKController.prototype.update = function () {
  85118. var bone1 = this._bone1;
  85119. if (!bone1) {
  85120. return;
  85121. }
  85122. var target = this.targetPosition;
  85123. var poleTarget = this.poleTargetPosition;
  85124. var mat1 = BoneIKController._tmpMats[0];
  85125. var mat2 = BoneIKController._tmpMats[1];
  85126. if (this.targetMesh) {
  85127. target.copyFrom(this.targetMesh.getAbsolutePosition());
  85128. }
  85129. if (this.poleTargetBone) {
  85130. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  85131. }
  85132. else if (this.poleTargetMesh) {
  85133. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  85134. }
  85135. var bonePos = BoneIKController._tmpVecs[0];
  85136. var zaxis = BoneIKController._tmpVecs[1];
  85137. var xaxis = BoneIKController._tmpVecs[2];
  85138. var yaxis = BoneIKController._tmpVecs[3];
  85139. var upAxis = BoneIKController._tmpVecs[4];
  85140. var _tmpQuat = BoneIKController._tmpQuat;
  85141. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  85142. poleTarget.subtractToRef(bonePos, upAxis);
  85143. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  85144. upAxis.y = 1;
  85145. }
  85146. else {
  85147. upAxis.normalize();
  85148. }
  85149. target.subtractToRef(bonePos, yaxis);
  85150. yaxis.normalize();
  85151. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  85152. zaxis.normalize();
  85153. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  85154. xaxis.normalize();
  85155. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  85156. var a = this._bone1Length;
  85157. var b = this._bone2Length;
  85158. var c = BABYLON.Vector3.Distance(bonePos, target);
  85159. if (this._maxReach > 0) {
  85160. c = Math.min(this._maxReach, c);
  85161. }
  85162. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  85163. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  85164. if (acosa > 1) {
  85165. acosa = 1;
  85166. }
  85167. if (acosb > 1) {
  85168. acosb = 1;
  85169. }
  85170. if (acosa < -1) {
  85171. acosa = -1;
  85172. }
  85173. if (acosb < -1) {
  85174. acosb = -1;
  85175. }
  85176. var angA = Math.acos(acosa);
  85177. var angB = Math.acos(acosb);
  85178. var angC = -angA - angB;
  85179. if (this._rightHandedSystem) {
  85180. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  85181. mat2.multiplyToRef(mat1, mat1);
  85182. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  85183. mat2.multiplyToRef(mat1, mat1);
  85184. }
  85185. else {
  85186. var _tmpVec = BoneIKController._tmpVecs[5];
  85187. _tmpVec.copyFrom(this._bendAxis);
  85188. _tmpVec.x *= -1;
  85189. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  85190. mat2.multiplyToRef(mat1, mat1);
  85191. }
  85192. if (this.poleAngle) {
  85193. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  85194. mat1.multiplyToRef(mat2, mat1);
  85195. }
  85196. if (this._bone1) {
  85197. if (this.slerpAmount < 1) {
  85198. if (!this._slerping) {
  85199. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  85200. }
  85201. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  85202. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  85203. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  85204. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  85205. this._slerping = true;
  85206. }
  85207. else {
  85208. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  85209. this._bone1Mat.copyFrom(mat1);
  85210. this._slerping = false;
  85211. }
  85212. }
  85213. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  85214. this._bone2Ang = angC;
  85215. };
  85216. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85217. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  85218. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  85219. return BoneIKController;
  85220. }());
  85221. BABYLON.BoneIKController = BoneIKController;
  85222. })(BABYLON || (BABYLON = {}));
  85223. //# sourceMappingURL=babylon.boneIKController.js.map
  85224. var BABYLON;
  85225. (function (BABYLON) {
  85226. /**
  85227. * Class used to make a bone look toward a point in space
  85228. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  85229. */
  85230. var BoneLookController = /** @class */ (function () {
  85231. /**
  85232. * Create a BoneLookController
  85233. * @param mesh the mesh that the bone belongs to
  85234. * @param bone the bone that will be looking to the target
  85235. * @param target the target Vector3 to look at
  85236. * @param settings optional settings:
  85237. * * maxYaw: the maximum angle the bone will yaw to
  85238. * * minYaw: the minimum angle the bone will yaw to
  85239. * * maxPitch: the maximum angle the bone will pitch to
  85240. * * minPitch: the minimum angle the bone will yaw to
  85241. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  85242. * * upAxis: the up axis of the coordinate system
  85243. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  85244. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  85245. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  85246. * * adjustYaw: used to make an adjustment to the yaw of the bone
  85247. * * adjustPitch: used to make an adjustment to the pitch of the bone
  85248. * * adjustRoll: used to make an adjustment to the roll of the bone
  85249. **/
  85250. function BoneLookController(mesh, bone, target, options) {
  85251. /**
  85252. * The up axis of the coordinate system that is used when the bone is rotated
  85253. */
  85254. this.upAxis = BABYLON.Vector3.Up();
  85255. /**
  85256. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  85257. */
  85258. this.upAxisSpace = BABYLON.Space.LOCAL;
  85259. /**
  85260. * Used to make an adjustment to the yaw of the bone
  85261. */
  85262. this.adjustYaw = 0;
  85263. /**
  85264. * Used to make an adjustment to the pitch of the bone
  85265. */
  85266. this.adjustPitch = 0;
  85267. /**
  85268. * Used to make an adjustment to the roll of the bone
  85269. */
  85270. this.adjustRoll = 0;
  85271. /**
  85272. * 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)
  85273. */
  85274. this.slerpAmount = 1;
  85275. this._boneQuat = BABYLON.Quaternion.Identity();
  85276. this._slerping = false;
  85277. this._firstFrameSkipped = false;
  85278. this._fowardAxis = BABYLON.Vector3.Forward();
  85279. this.mesh = mesh;
  85280. this.bone = bone;
  85281. this.target = target;
  85282. if (options) {
  85283. if (options.adjustYaw) {
  85284. this.adjustYaw = options.adjustYaw;
  85285. }
  85286. if (options.adjustPitch) {
  85287. this.adjustPitch = options.adjustPitch;
  85288. }
  85289. if (options.adjustRoll) {
  85290. this.adjustRoll = options.adjustRoll;
  85291. }
  85292. if (options.maxYaw != null) {
  85293. this.maxYaw = options.maxYaw;
  85294. }
  85295. else {
  85296. this.maxYaw = Math.PI;
  85297. }
  85298. if (options.minYaw != null) {
  85299. this.minYaw = options.minYaw;
  85300. }
  85301. else {
  85302. this.minYaw = -Math.PI;
  85303. }
  85304. if (options.maxPitch != null) {
  85305. this.maxPitch = options.maxPitch;
  85306. }
  85307. else {
  85308. this.maxPitch = Math.PI;
  85309. }
  85310. if (options.minPitch != null) {
  85311. this.minPitch = options.minPitch;
  85312. }
  85313. else {
  85314. this.minPitch = -Math.PI;
  85315. }
  85316. if (options.slerpAmount != null) {
  85317. this.slerpAmount = options.slerpAmount;
  85318. }
  85319. if (options.upAxis != null) {
  85320. this.upAxis = options.upAxis;
  85321. }
  85322. if (options.upAxisSpace != null) {
  85323. this.upAxisSpace = options.upAxisSpace;
  85324. }
  85325. if (options.yawAxis != null || options.pitchAxis != null) {
  85326. var newYawAxis = BABYLON.Axis.Y;
  85327. var newPitchAxis = BABYLON.Axis.X;
  85328. if (options.yawAxis != null) {
  85329. newYawAxis = options.yawAxis.clone();
  85330. newYawAxis.normalize();
  85331. }
  85332. if (options.pitchAxis != null) {
  85333. newPitchAxis = options.pitchAxis.clone();
  85334. newPitchAxis.normalize();
  85335. }
  85336. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  85337. this._transformYawPitch = BABYLON.Matrix.Identity();
  85338. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  85339. this._transformYawPitchInv = this._transformYawPitch.clone();
  85340. this._transformYawPitch.invert();
  85341. }
  85342. }
  85343. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  85344. this.upAxisSpace = BABYLON.Space.LOCAL;
  85345. }
  85346. }
  85347. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  85348. /**
  85349. * Gets or sets the minimum yaw angle that the bone can look to
  85350. */
  85351. get: function () {
  85352. return this._minYaw;
  85353. },
  85354. set: function (value) {
  85355. this._minYaw = value;
  85356. this._minYawSin = Math.sin(value);
  85357. this._minYawCos = Math.cos(value);
  85358. if (this._maxYaw != null) {
  85359. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  85360. this._yawRange = this._maxYaw - this._minYaw;
  85361. }
  85362. },
  85363. enumerable: true,
  85364. configurable: true
  85365. });
  85366. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  85367. /**
  85368. * Gets or sets the maximum yaw angle that the bone can look to
  85369. */
  85370. get: function () {
  85371. return this._maxYaw;
  85372. },
  85373. set: function (value) {
  85374. this._maxYaw = value;
  85375. this._maxYawSin = Math.sin(value);
  85376. this._maxYawCos = Math.cos(value);
  85377. if (this._minYaw != null) {
  85378. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  85379. this._yawRange = this._maxYaw - this._minYaw;
  85380. }
  85381. },
  85382. enumerable: true,
  85383. configurable: true
  85384. });
  85385. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  85386. /**
  85387. * Gets or sets the minimum pitch angle that the bone can look to
  85388. */
  85389. get: function () {
  85390. return this._minPitch;
  85391. },
  85392. set: function (value) {
  85393. this._minPitch = value;
  85394. this._minPitchTan = Math.tan(value);
  85395. },
  85396. enumerable: true,
  85397. configurable: true
  85398. });
  85399. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  85400. /**
  85401. * Gets or sets the maximum pitch angle that the bone can look to
  85402. */
  85403. get: function () {
  85404. return this._maxPitch;
  85405. },
  85406. set: function (value) {
  85407. this._maxPitch = value;
  85408. this._maxPitchTan = Math.tan(value);
  85409. },
  85410. enumerable: true,
  85411. configurable: true
  85412. });
  85413. /**
  85414. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  85415. */
  85416. BoneLookController.prototype.update = function () {
  85417. //skip the first frame when slerping so that the mesh rotation is correct
  85418. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  85419. this._firstFrameSkipped = true;
  85420. return;
  85421. }
  85422. var bone = this.bone;
  85423. var bonePos = BoneLookController._tmpVecs[0];
  85424. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  85425. var target = this.target;
  85426. var _tmpMat1 = BoneLookController._tmpMats[0];
  85427. var _tmpMat2 = BoneLookController._tmpMats[1];
  85428. var mesh = this.mesh;
  85429. var parentBone = bone.getParent();
  85430. var upAxis = BoneLookController._tmpVecs[1];
  85431. upAxis.copyFrom(this.upAxis);
  85432. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  85433. if (this._transformYawPitch) {
  85434. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  85435. }
  85436. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  85437. }
  85438. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  85439. mesh.getDirectionToRef(upAxis, upAxis);
  85440. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  85441. upAxis.normalize();
  85442. }
  85443. }
  85444. var checkYaw = false;
  85445. var checkPitch = false;
  85446. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  85447. checkYaw = true;
  85448. }
  85449. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  85450. checkPitch = true;
  85451. }
  85452. if (checkYaw || checkPitch) {
  85453. var spaceMat = BoneLookController._tmpMats[2];
  85454. var spaceMatInv = BoneLookController._tmpMats[3];
  85455. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  85456. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  85457. }
  85458. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  85459. spaceMat.copyFrom(mesh.getWorldMatrix());
  85460. }
  85461. else {
  85462. var forwardAxis = BoneLookController._tmpVecs[2];
  85463. forwardAxis.copyFrom(this._fowardAxis);
  85464. if (this._transformYawPitch) {
  85465. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  85466. }
  85467. if (parentBone) {
  85468. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  85469. }
  85470. else {
  85471. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  85472. }
  85473. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  85474. rightAxis.normalize();
  85475. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  85476. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  85477. }
  85478. spaceMat.invertToRef(spaceMatInv);
  85479. var xzlen = null;
  85480. if (checkPitch) {
  85481. var localTarget = BoneLookController._tmpVecs[3];
  85482. target.subtractToRef(bonePos, localTarget);
  85483. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  85484. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  85485. var pitch = Math.atan2(localTarget.y, xzlen);
  85486. var newPitch = pitch;
  85487. if (pitch > this._maxPitch) {
  85488. localTarget.y = this._maxPitchTan * xzlen;
  85489. newPitch = this._maxPitch;
  85490. }
  85491. else if (pitch < this._minPitch) {
  85492. localTarget.y = this._minPitchTan * xzlen;
  85493. newPitch = this._minPitch;
  85494. }
  85495. if (pitch != newPitch) {
  85496. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  85497. localTarget.addInPlace(bonePos);
  85498. target = localTarget;
  85499. }
  85500. }
  85501. if (checkYaw) {
  85502. var localTarget = BoneLookController._tmpVecs[4];
  85503. target.subtractToRef(bonePos, localTarget);
  85504. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  85505. var yaw = Math.atan2(localTarget.x, localTarget.z);
  85506. var newYaw = yaw;
  85507. if (yaw > this._maxYaw || yaw < this._minYaw) {
  85508. if (xzlen == null) {
  85509. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  85510. }
  85511. if (this._yawRange > Math.PI) {
  85512. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  85513. localTarget.z = this._maxYawCos * xzlen;
  85514. localTarget.x = this._maxYawSin * xzlen;
  85515. newYaw = this._maxYaw;
  85516. }
  85517. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  85518. localTarget.z = this._minYawCos * xzlen;
  85519. localTarget.x = this._minYawSin * xzlen;
  85520. newYaw = this._minYaw;
  85521. }
  85522. }
  85523. else {
  85524. if (yaw > this._maxYaw) {
  85525. localTarget.z = this._maxYawCos * xzlen;
  85526. localTarget.x = this._maxYawSin * xzlen;
  85527. newYaw = this._maxYaw;
  85528. }
  85529. else if (yaw < this._minYaw) {
  85530. localTarget.z = this._minYawCos * xzlen;
  85531. localTarget.x = this._minYawSin * xzlen;
  85532. newYaw = this._minYaw;
  85533. }
  85534. }
  85535. }
  85536. if (this._slerping && this._yawRange > Math.PI) {
  85537. //are we going to be crossing into the min/max region?
  85538. var boneFwd = BoneLookController._tmpVecs[8];
  85539. boneFwd.copyFrom(BABYLON.Axis.Z);
  85540. if (this._transformYawPitch) {
  85541. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  85542. }
  85543. var boneRotMat = BoneLookController._tmpMats[4];
  85544. this._boneQuat.toRotationMatrix(boneRotMat);
  85545. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  85546. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  85547. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  85548. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  85549. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  85550. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  85551. if (angBtwTar > angBtwMidYaw) {
  85552. if (xzlen == null) {
  85553. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  85554. }
  85555. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  85556. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  85557. if (angBtwMin < angBtwMax) {
  85558. newYaw = boneYaw + Math.PI * .75;
  85559. localTarget.z = Math.cos(newYaw) * xzlen;
  85560. localTarget.x = Math.sin(newYaw) * xzlen;
  85561. }
  85562. else {
  85563. newYaw = boneYaw - Math.PI * .75;
  85564. localTarget.z = Math.cos(newYaw) * xzlen;
  85565. localTarget.x = Math.sin(newYaw) * xzlen;
  85566. }
  85567. }
  85568. }
  85569. if (yaw != newYaw) {
  85570. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  85571. localTarget.addInPlace(bonePos);
  85572. target = localTarget;
  85573. }
  85574. }
  85575. }
  85576. var zaxis = BoneLookController._tmpVecs[5];
  85577. var xaxis = BoneLookController._tmpVecs[6];
  85578. var yaxis = BoneLookController._tmpVecs[7];
  85579. var _tmpQuat = BoneLookController._tmpQuat;
  85580. target.subtractToRef(bonePos, zaxis);
  85581. zaxis.normalize();
  85582. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  85583. xaxis.normalize();
  85584. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  85585. yaxis.normalize();
  85586. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  85587. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  85588. return;
  85589. }
  85590. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  85591. return;
  85592. }
  85593. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  85594. return;
  85595. }
  85596. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  85597. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  85598. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  85599. }
  85600. if (this.slerpAmount < 1) {
  85601. if (!this._slerping) {
  85602. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  85603. }
  85604. if (this._transformYawPitch) {
  85605. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  85606. }
  85607. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  85608. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  85609. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  85610. this._slerping = true;
  85611. }
  85612. else {
  85613. if (this._transformYawPitch) {
  85614. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  85615. }
  85616. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  85617. this._slerping = false;
  85618. }
  85619. };
  85620. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  85621. var angDiff = ang2 - ang1;
  85622. angDiff %= Math.PI * 2;
  85623. if (angDiff > Math.PI) {
  85624. angDiff -= Math.PI * 2;
  85625. }
  85626. else if (angDiff < -Math.PI) {
  85627. angDiff += Math.PI * 2;
  85628. }
  85629. return angDiff;
  85630. };
  85631. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  85632. ang1 %= (2 * Math.PI);
  85633. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  85634. ang2 %= (2 * Math.PI);
  85635. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  85636. var ab = 0;
  85637. if (ang1 < ang2) {
  85638. ab = ang2 - ang1;
  85639. }
  85640. else {
  85641. ab = ang1 - ang2;
  85642. }
  85643. if (ab > Math.PI) {
  85644. ab = Math.PI * 2 - ab;
  85645. }
  85646. return ab;
  85647. };
  85648. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  85649. ang %= (2 * Math.PI);
  85650. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  85651. ang1 %= (2 * Math.PI);
  85652. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  85653. ang2 %= (2 * Math.PI);
  85654. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  85655. if (ang1 < ang2) {
  85656. if (ang > ang1 && ang < ang2) {
  85657. return true;
  85658. }
  85659. }
  85660. else {
  85661. if (ang > ang2 && ang < ang1) {
  85662. return true;
  85663. }
  85664. }
  85665. return false;
  85666. };
  85667. 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()];
  85668. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  85669. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  85670. return BoneLookController;
  85671. }());
  85672. BABYLON.BoneLookController = BoneLookController;
  85673. })(BABYLON || (BABYLON = {}));
  85674. //# sourceMappingURL=babylon.boneLookController.js.map
  85675. var BABYLON;
  85676. (function (BABYLON) {
  85677. /**
  85678. * Class used to handle skinning animations
  85679. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  85680. */
  85681. var Skeleton = /** @class */ (function () {
  85682. /**
  85683. * Creates a new skeleton
  85684. * @param name defines the skeleton name
  85685. * @param id defines the skeleton Id
  85686. * @param scene defines the hosting scene
  85687. */
  85688. function Skeleton(
  85689. /** defines the skeleton name */
  85690. name,
  85691. /** defines the skeleton Id */
  85692. id, scene) {
  85693. this.name = name;
  85694. this.id = id;
  85695. /**
  85696. * Gets the list of child bones
  85697. */
  85698. this.bones = new Array();
  85699. /**
  85700. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  85701. */
  85702. this.needInitialSkinMatrix = false;
  85703. this._isDirty = true;
  85704. this._meshesWithPoseMatrix = new Array();
  85705. this._identity = BABYLON.Matrix.Identity();
  85706. this._ranges = {};
  85707. this._lastAbsoluteTransformsUpdateId = -1;
  85708. /**
  85709. * Specifies if the skeleton should be serialized
  85710. */
  85711. this.doNotSerialize = false;
  85712. this._animationPropertiesOverride = null;
  85713. // Events
  85714. /**
  85715. * An observable triggered before computing the skeleton's matrices
  85716. */
  85717. this.onBeforeComputeObservable = new BABYLON.Observable();
  85718. this.bones = [];
  85719. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  85720. scene.skeletons.push(this);
  85721. //make sure it will recalculate the matrix next time prepare is called.
  85722. this._isDirty = true;
  85723. }
  85724. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  85725. /**
  85726. * Gets or sets the animation properties override
  85727. */
  85728. get: function () {
  85729. if (!this._animationPropertiesOverride) {
  85730. return this._scene.animationPropertiesOverride;
  85731. }
  85732. return this._animationPropertiesOverride;
  85733. },
  85734. set: function (value) {
  85735. this._animationPropertiesOverride = value;
  85736. },
  85737. enumerable: true,
  85738. configurable: true
  85739. });
  85740. // Members
  85741. /**
  85742. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  85743. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  85744. * @returns a Float32Array containing matrices data
  85745. */
  85746. Skeleton.prototype.getTransformMatrices = function (mesh) {
  85747. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  85748. return mesh._bonesTransformMatrices;
  85749. }
  85750. if (!this._transformMatrices) {
  85751. this.prepare();
  85752. }
  85753. return this._transformMatrices;
  85754. };
  85755. /**
  85756. * Gets the current hosting scene
  85757. * @returns a scene object
  85758. */
  85759. Skeleton.prototype.getScene = function () {
  85760. return this._scene;
  85761. };
  85762. // Methods
  85763. /**
  85764. * Gets a string representing the current skeleton data
  85765. * @param fullDetails defines a boolean indicating if we want a verbose version
  85766. * @returns a string representing the current skeleton data
  85767. */
  85768. Skeleton.prototype.toString = function (fullDetails) {
  85769. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  85770. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  85771. if (fullDetails) {
  85772. ret += ", Ranges: {";
  85773. var first = true;
  85774. for (var name_1 in this._ranges) {
  85775. if (first) {
  85776. ret += ", ";
  85777. first = false;
  85778. }
  85779. ret += name_1;
  85780. }
  85781. ret += "}";
  85782. }
  85783. return ret;
  85784. };
  85785. /**
  85786. * Get bone's index searching by name
  85787. * @param name defines bone's name to search for
  85788. * @return the indice of the bone. Returns -1 if not found
  85789. */
  85790. Skeleton.prototype.getBoneIndexByName = function (name) {
  85791. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  85792. if (this.bones[boneIndex].name === name) {
  85793. return boneIndex;
  85794. }
  85795. }
  85796. return -1;
  85797. };
  85798. /**
  85799. * Creater a new animation range
  85800. * @param name defines the name of the range
  85801. * @param from defines the start key
  85802. * @param to defines the end key
  85803. */
  85804. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  85805. // check name not already in use
  85806. if (!this._ranges[name]) {
  85807. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  85808. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  85809. if (this.bones[i].animations[0]) {
  85810. this.bones[i].animations[0].createRange(name, from, to);
  85811. }
  85812. }
  85813. }
  85814. };
  85815. /**
  85816. * Delete a specific animation range
  85817. * @param name defines the name of the range
  85818. * @param deleteFrames defines if frames must be removed as well
  85819. */
  85820. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  85821. if (deleteFrames === void 0) { deleteFrames = true; }
  85822. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  85823. if (this.bones[i].animations[0]) {
  85824. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  85825. }
  85826. }
  85827. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  85828. };
  85829. /**
  85830. * Gets a specific animation range
  85831. * @param name defines the name of the range to look for
  85832. * @returns the requested animation range or null if not found
  85833. */
  85834. Skeleton.prototype.getAnimationRange = function (name) {
  85835. return this._ranges[name];
  85836. };
  85837. /**
  85838. * Gets the list of all animation ranges defined on this skeleton
  85839. * @returns an array
  85840. */
  85841. Skeleton.prototype.getAnimationRanges = function () {
  85842. var animationRanges = [];
  85843. var name;
  85844. var i = 0;
  85845. for (name in this._ranges) {
  85846. animationRanges[i] = this._ranges[name];
  85847. i++;
  85848. }
  85849. return animationRanges;
  85850. };
  85851. /**
  85852. * Copy animation range from a source skeleton.
  85853. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  85854. * @param source defines the source skeleton
  85855. * @param name defines the name of the range to copy
  85856. * @param rescaleAsRequired defines if rescaling must be applied if required
  85857. * @returns true if operation was successful
  85858. */
  85859. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  85860. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  85861. if (this._ranges[name] || !source.getAnimationRange(name)) {
  85862. return false;
  85863. }
  85864. var ret = true;
  85865. var frameOffset = this._getHighestAnimationFrame() + 1;
  85866. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  85867. var boneDict = {};
  85868. var sourceBones = source.bones;
  85869. var nBones;
  85870. var i;
  85871. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  85872. boneDict[sourceBones[i].name] = sourceBones[i];
  85873. }
  85874. if (this.bones.length !== sourceBones.length) {
  85875. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  85876. ret = false;
  85877. }
  85878. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  85879. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  85880. var boneName = this.bones[i].name;
  85881. var sourceBone = boneDict[boneName];
  85882. if (sourceBone) {
  85883. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  85884. }
  85885. else {
  85886. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  85887. ret = false;
  85888. }
  85889. }
  85890. // do not call createAnimationRange(), since it also is done to bones, which was already done
  85891. var range = source.getAnimationRange(name);
  85892. if (range) {
  85893. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  85894. }
  85895. return ret;
  85896. };
  85897. /**
  85898. * Forces the skeleton to go to rest pose
  85899. */
  85900. Skeleton.prototype.returnToRest = function () {
  85901. for (var index = 0; index < this.bones.length; index++) {
  85902. this.bones[index].returnToRest();
  85903. }
  85904. };
  85905. Skeleton.prototype._getHighestAnimationFrame = function () {
  85906. var ret = 0;
  85907. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  85908. if (this.bones[i].animations[0]) {
  85909. var highest = this.bones[i].animations[0].getHighestFrame();
  85910. if (ret < highest) {
  85911. ret = highest;
  85912. }
  85913. }
  85914. }
  85915. return ret;
  85916. };
  85917. /**
  85918. * Begin a specific animation range
  85919. * @param name defines the name of the range to start
  85920. * @param loop defines if looping must be turned on (false by default)
  85921. * @param speedRatio defines the speed ratio to apply (1 by default)
  85922. * @param onAnimationEnd defines a callback which will be called when animation will end
  85923. * @returns a new animatable
  85924. */
  85925. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  85926. var range = this.getAnimationRange(name);
  85927. if (!range) {
  85928. return null;
  85929. }
  85930. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  85931. };
  85932. /** @hidden */
  85933. Skeleton.prototype._markAsDirty = function () {
  85934. this._isDirty = true;
  85935. };
  85936. /** @hidden */
  85937. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  85938. this._meshesWithPoseMatrix.push(mesh);
  85939. };
  85940. /** @hidden */
  85941. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  85942. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  85943. if (index > -1) {
  85944. this._meshesWithPoseMatrix.splice(index, 1);
  85945. }
  85946. };
  85947. /** @hidden */
  85948. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  85949. this.onBeforeComputeObservable.notifyObservers(this);
  85950. for (var index = 0; index < this.bones.length; index++) {
  85951. var bone = this.bones[index];
  85952. var parentBone = bone.getParent();
  85953. if (parentBone) {
  85954. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  85955. }
  85956. else {
  85957. if (initialSkinMatrix) {
  85958. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  85959. }
  85960. else {
  85961. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  85962. }
  85963. }
  85964. if (bone._index !== -1) {
  85965. var mappedIndex = bone._index === null ? index : bone._index;
  85966. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  85967. }
  85968. }
  85969. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  85970. };
  85971. /**
  85972. * Build all resources required to render a skeleton
  85973. */
  85974. Skeleton.prototype.prepare = function () {
  85975. if (!this._isDirty) {
  85976. return;
  85977. }
  85978. if (this.needInitialSkinMatrix) {
  85979. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  85980. var mesh = this._meshesWithPoseMatrix[index];
  85981. var poseMatrix = mesh.getPoseMatrix();
  85982. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  85983. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  85984. }
  85985. if (this._synchronizedWithMesh !== mesh) {
  85986. this._synchronizedWithMesh = mesh;
  85987. // Prepare bones
  85988. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  85989. var bone = this.bones[boneIndex];
  85990. if (!bone.getParent()) {
  85991. var matrix = bone.getBaseMatrix();
  85992. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  85993. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  85994. }
  85995. }
  85996. }
  85997. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  85998. }
  85999. }
  86000. else {
  86001. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  86002. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  86003. }
  86004. this._computeTransformMatrices(this._transformMatrices, null);
  86005. }
  86006. this._isDirty = false;
  86007. this._scene._activeBones.addCount(this.bones.length, false);
  86008. };
  86009. /**
  86010. * Gets the list of animatables currently running for this skeleton
  86011. * @returns an array of animatables
  86012. */
  86013. Skeleton.prototype.getAnimatables = function () {
  86014. if (!this._animatables || this._animatables.length !== this.bones.length) {
  86015. this._animatables = [];
  86016. for (var index = 0; index < this.bones.length; index++) {
  86017. this._animatables.push(this.bones[index]);
  86018. }
  86019. }
  86020. return this._animatables;
  86021. };
  86022. /**
  86023. * Clone the current skeleton
  86024. * @param name defines the name of the new skeleton
  86025. * @param id defines the id of the enw skeleton
  86026. * @returns the new skeleton
  86027. */
  86028. Skeleton.prototype.clone = function (name, id) {
  86029. var result = new Skeleton(name, id || name, this._scene);
  86030. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  86031. for (var index = 0; index < this.bones.length; index++) {
  86032. var source = this.bones[index];
  86033. var parentBone = null;
  86034. var parent_1 = source.getParent();
  86035. if (parent_1) {
  86036. var parentIndex = this.bones.indexOf(parent_1);
  86037. parentBone = result.bones[parentIndex];
  86038. }
  86039. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  86040. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  86041. }
  86042. if (this._ranges) {
  86043. result._ranges = {};
  86044. for (var rangeName in this._ranges) {
  86045. var range = this._ranges[rangeName];
  86046. if (range) {
  86047. result._ranges[rangeName] = range.clone();
  86048. }
  86049. }
  86050. }
  86051. this._isDirty = true;
  86052. return result;
  86053. };
  86054. /**
  86055. * Enable animation blending for this skeleton
  86056. * @param blendingSpeed defines the blending speed to apply
  86057. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  86058. */
  86059. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  86060. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  86061. this.bones.forEach(function (bone) {
  86062. bone.animations.forEach(function (animation) {
  86063. animation.enableBlending = true;
  86064. animation.blendingSpeed = blendingSpeed;
  86065. });
  86066. });
  86067. };
  86068. /**
  86069. * Releases all resources associated with the current skeleton
  86070. */
  86071. Skeleton.prototype.dispose = function () {
  86072. this._meshesWithPoseMatrix = [];
  86073. // Animations
  86074. this.getScene().stopAnimation(this);
  86075. // Remove from scene
  86076. this.getScene().removeSkeleton(this);
  86077. };
  86078. /**
  86079. * Serialize the skeleton in a JSON object
  86080. * @returns a JSON object
  86081. */
  86082. Skeleton.prototype.serialize = function () {
  86083. var serializationObject = {};
  86084. serializationObject.name = this.name;
  86085. serializationObject.id = this.id;
  86086. if (this.dimensionsAtRest) {
  86087. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  86088. }
  86089. serializationObject.bones = [];
  86090. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  86091. for (var index = 0; index < this.bones.length; index++) {
  86092. var bone = this.bones[index];
  86093. var parent_2 = bone.getParent();
  86094. var serializedBone = {
  86095. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  86096. name: bone.name,
  86097. matrix: bone.getBaseMatrix().toArray(),
  86098. rest: bone.getRestPose().toArray()
  86099. };
  86100. serializationObject.bones.push(serializedBone);
  86101. if (bone.length) {
  86102. serializedBone.length = bone.length;
  86103. }
  86104. if (bone.metadata) {
  86105. serializedBone.metadata = bone.metadata;
  86106. }
  86107. if (bone.animations && bone.animations.length > 0) {
  86108. serializedBone.animation = bone.animations[0].serialize();
  86109. }
  86110. serializationObject.ranges = [];
  86111. for (var name in this._ranges) {
  86112. var source = this._ranges[name];
  86113. if (!source) {
  86114. continue;
  86115. }
  86116. var range = {};
  86117. range.name = name;
  86118. range.from = source.from;
  86119. range.to = source.to;
  86120. serializationObject.ranges.push(range);
  86121. }
  86122. }
  86123. return serializationObject;
  86124. };
  86125. /**
  86126. * Creates a new skeleton from serialized data
  86127. * @param parsedSkeleton defines the serialized data
  86128. * @param scene defines the hosting scene
  86129. * @returns a new skeleton
  86130. */
  86131. Skeleton.Parse = function (parsedSkeleton, scene) {
  86132. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  86133. if (parsedSkeleton.dimensionsAtRest) {
  86134. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  86135. }
  86136. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  86137. var index;
  86138. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  86139. var parsedBone = parsedSkeleton.bones[index];
  86140. var parentBone = null;
  86141. if (parsedBone.parentBoneIndex > -1) {
  86142. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  86143. }
  86144. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  86145. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  86146. if (parsedBone.length) {
  86147. bone.length = parsedBone.length;
  86148. }
  86149. if (parsedBone.metadata) {
  86150. bone.metadata = parsedBone.metadata;
  86151. }
  86152. if (parsedBone.animation) {
  86153. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  86154. }
  86155. }
  86156. // placed after bones, so createAnimationRange can cascade down
  86157. if (parsedSkeleton.ranges) {
  86158. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  86159. var data = parsedSkeleton.ranges[index];
  86160. skeleton.createAnimationRange(data.name, data.from, data.to);
  86161. }
  86162. }
  86163. return skeleton;
  86164. };
  86165. /**
  86166. * Compute all node absolute transforms
  86167. * @param forceUpdate defines if computation must be done even if cache is up to date
  86168. */
  86169. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  86170. if (forceUpdate === void 0) { forceUpdate = false; }
  86171. var renderId = this._scene.getRenderId();
  86172. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  86173. this.bones[0].computeAbsoluteTransforms();
  86174. this._lastAbsoluteTransformsUpdateId = renderId;
  86175. }
  86176. };
  86177. /**
  86178. * Gets the root pose matrix
  86179. * @returns a matrix
  86180. */
  86181. Skeleton.prototype.getPoseMatrix = function () {
  86182. var poseMatrix = null;
  86183. if (this._meshesWithPoseMatrix.length > 0) {
  86184. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  86185. }
  86186. return poseMatrix;
  86187. };
  86188. /**
  86189. * Sorts bones per internal index
  86190. */
  86191. Skeleton.prototype.sortBones = function () {
  86192. var bones = new Array();
  86193. var visited = new Array(this.bones.length);
  86194. for (var index = 0; index < this.bones.length; index++) {
  86195. this._sortBones(index, bones, visited);
  86196. }
  86197. this.bones = bones;
  86198. };
  86199. Skeleton.prototype._sortBones = function (index, bones, visited) {
  86200. if (visited[index]) {
  86201. return;
  86202. }
  86203. visited[index] = true;
  86204. var bone = this.bones[index];
  86205. if (bone._index === undefined) {
  86206. bone._index = index;
  86207. }
  86208. var parentBone = bone.getParent();
  86209. if (parentBone) {
  86210. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  86211. }
  86212. bones.push(bone);
  86213. };
  86214. return Skeleton;
  86215. }());
  86216. BABYLON.Skeleton = Skeleton;
  86217. })(BABYLON || (BABYLON = {}));
  86218. //# sourceMappingURL=babylon.skeleton.js.map
  86219. var BABYLON;
  86220. (function (BABYLON) {
  86221. ;
  86222. /**
  86223. * This groups tools to convert HDR texture to native colors array.
  86224. */
  86225. var HDRTools = /** @class */ (function () {
  86226. function HDRTools() {
  86227. }
  86228. HDRTools.Ldexp = function (mantissa, exponent) {
  86229. if (exponent > 1023) {
  86230. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  86231. }
  86232. if (exponent < -1074) {
  86233. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  86234. }
  86235. return mantissa * Math.pow(2, exponent);
  86236. };
  86237. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  86238. if (exponent > 0) { /*nonzero pixel*/
  86239. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  86240. float32array[index + 0] = red * exponent;
  86241. float32array[index + 1] = green * exponent;
  86242. float32array[index + 2] = blue * exponent;
  86243. }
  86244. else {
  86245. float32array[index + 0] = 0;
  86246. float32array[index + 1] = 0;
  86247. float32array[index + 2] = 0;
  86248. }
  86249. };
  86250. HDRTools.readStringLine = function (uint8array, startIndex) {
  86251. var line = "";
  86252. var character = "";
  86253. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  86254. character = String.fromCharCode(uint8array[i]);
  86255. if (character == "\n") {
  86256. break;
  86257. }
  86258. line += character;
  86259. }
  86260. return line;
  86261. };
  86262. /**
  86263. * Reads header information from an RGBE texture stored in a native array.
  86264. * More information on this format are available here:
  86265. * https://en.wikipedia.org/wiki/RGBE_image_format
  86266. *
  86267. * @param uint8array The binary file stored in native array.
  86268. * @return The header information.
  86269. */
  86270. HDRTools.RGBE_ReadHeader = function (uint8array) {
  86271. var height = 0;
  86272. var width = 0;
  86273. var line = this.readStringLine(uint8array, 0);
  86274. if (line[0] != '#' || line[1] != '?') {
  86275. throw "Bad HDR Format.";
  86276. }
  86277. var endOfHeader = false;
  86278. var findFormat = false;
  86279. var lineIndex = 0;
  86280. do {
  86281. lineIndex += (line.length + 1);
  86282. line = this.readStringLine(uint8array, lineIndex);
  86283. if (line == "FORMAT=32-bit_rle_rgbe") {
  86284. findFormat = true;
  86285. }
  86286. else if (line.length == 0) {
  86287. endOfHeader = true;
  86288. }
  86289. } while (!endOfHeader);
  86290. if (!findFormat) {
  86291. throw "HDR Bad header format, unsupported FORMAT";
  86292. }
  86293. lineIndex += (line.length + 1);
  86294. line = this.readStringLine(uint8array, lineIndex);
  86295. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  86296. var match = sizeRegexp.exec(line);
  86297. // TODO. Support +Y and -X if needed.
  86298. if (!match || match.length < 3) {
  86299. throw "HDR Bad header format, no size";
  86300. }
  86301. width = parseInt(match[2]);
  86302. height = parseInt(match[1]);
  86303. if (width < 8 || width > 0x7fff) {
  86304. throw "HDR Bad header format, unsupported size";
  86305. }
  86306. lineIndex += (line.length + 1);
  86307. return {
  86308. height: height,
  86309. width: width,
  86310. dataPosition: lineIndex
  86311. };
  86312. };
  86313. /**
  86314. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  86315. * This RGBE texture needs to store the information as a panorama.
  86316. *
  86317. * More information on this format are available here:
  86318. * https://en.wikipedia.org/wiki/RGBE_image_format
  86319. *
  86320. * @param buffer The binary file stored in an array buffer.
  86321. * @param size The expected size of the extracted cubemap.
  86322. * @return The Cube Map information.
  86323. */
  86324. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  86325. var uint8array = new Uint8Array(buffer);
  86326. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  86327. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  86328. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  86329. return cubeMapData;
  86330. };
  86331. /**
  86332. * Returns the pixels data extracted from an RGBE texture.
  86333. * This pixels will be stored left to right up to down in the R G B order in one array.
  86334. *
  86335. * More information on this format are available here:
  86336. * https://en.wikipedia.org/wiki/RGBE_image_format
  86337. *
  86338. * @param uint8array The binary file stored in an array buffer.
  86339. * @param hdrInfo The header information of the file.
  86340. * @return The pixels data in RGB right to left up to down order.
  86341. */
  86342. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  86343. // Keep for multi format supports.
  86344. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  86345. };
  86346. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  86347. var num_scanlines = hdrInfo.height;
  86348. var scanline_width = hdrInfo.width;
  86349. var a, b, c, d, count;
  86350. var dataIndex = hdrInfo.dataPosition;
  86351. var index = 0, endIndex = 0, i = 0;
  86352. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  86353. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  86354. // 3 channels of 4 bytes per pixel in float.
  86355. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  86356. var resultArray = new Float32Array(resultBuffer);
  86357. // read in each successive scanline
  86358. while (num_scanlines > 0) {
  86359. a = uint8array[dataIndex++];
  86360. b = uint8array[dataIndex++];
  86361. c = uint8array[dataIndex++];
  86362. d = uint8array[dataIndex++];
  86363. if (a != 2 || b != 2 || (c & 0x80)) {
  86364. // this file is not run length encoded
  86365. throw "HDR Bad header format, not RLE";
  86366. }
  86367. if (((c << 8) | d) != scanline_width) {
  86368. throw "HDR Bad header format, wrong scan line width";
  86369. }
  86370. index = 0;
  86371. // read each of the four channels for the scanline into the buffer
  86372. for (i = 0; i < 4; i++) {
  86373. endIndex = (i + 1) * scanline_width;
  86374. while (index < endIndex) {
  86375. a = uint8array[dataIndex++];
  86376. b = uint8array[dataIndex++];
  86377. if (a > 128) {
  86378. // a run of the same value
  86379. count = a - 128;
  86380. if ((count == 0) || (count > endIndex - index)) {
  86381. throw "HDR Bad Format, bad scanline data (run)";
  86382. }
  86383. while (count-- > 0) {
  86384. scanLineArray[index++] = b;
  86385. }
  86386. }
  86387. else {
  86388. // a non-run
  86389. count = a;
  86390. if ((count == 0) || (count > endIndex - index)) {
  86391. throw "HDR Bad Format, bad scanline data (non-run)";
  86392. }
  86393. scanLineArray[index++] = b;
  86394. if (--count > 0) {
  86395. for (var j = 0; j < count; j++) {
  86396. scanLineArray[index++] = uint8array[dataIndex++];
  86397. }
  86398. }
  86399. }
  86400. }
  86401. }
  86402. // now convert data from buffer into floats
  86403. for (i = 0; i < scanline_width; i++) {
  86404. a = scanLineArray[i];
  86405. b = scanLineArray[i + scanline_width];
  86406. c = scanLineArray[i + 2 * scanline_width];
  86407. d = scanLineArray[i + 3 * scanline_width];
  86408. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  86409. }
  86410. num_scanlines--;
  86411. }
  86412. return resultArray;
  86413. };
  86414. return HDRTools;
  86415. }());
  86416. BABYLON.HDRTools = HDRTools;
  86417. })(BABYLON || (BABYLON = {}));
  86418. //# sourceMappingURL=babylon.hdr.js.map
  86419. var BABYLON;
  86420. (function (BABYLON) {
  86421. /**
  86422. * This represents a texture coming from an HDR input.
  86423. *
  86424. * The only supported format is currently panorama picture stored in RGBE format.
  86425. * Example of such files can be found on HDRLib: http://hdrlib.com/
  86426. */
  86427. var HDRCubeTexture = /** @class */ (function (_super) {
  86428. __extends(HDRCubeTexture, _super);
  86429. /**
  86430. * Instantiates an HDRTexture from the following parameters.
  86431. *
  86432. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  86433. * @param scene The scene the texture will be used in
  86434. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  86435. * @param noMipmap Forces to not generate the mipmap if true
  86436. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  86437. * @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)
  86438. * @param reserved Reserved flag for internal use.
  86439. */
  86440. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  86441. if (noMipmap === void 0) { noMipmap = false; }
  86442. if (generateHarmonics === void 0) { generateHarmonics = true; }
  86443. if (gammaSpace === void 0) { gammaSpace = false; }
  86444. if (reserved === void 0) { reserved = false; }
  86445. if (onLoad === void 0) { onLoad = null; }
  86446. if (onError === void 0) { onError = null; }
  86447. var _this = _super.call(this, scene) || this;
  86448. _this._generateHarmonics = true;
  86449. _this._onLoad = null;
  86450. _this._onError = null;
  86451. /**
  86452. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  86453. */
  86454. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  86455. _this._isBlocking = true;
  86456. _this._rotationY = 0;
  86457. /**
  86458. * Gets or sets the center of the bounding box associated with the cube texture
  86459. * It must define where the camera used to render the texture was set
  86460. */
  86461. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  86462. if (!url) {
  86463. return _this;
  86464. }
  86465. _this.name = url;
  86466. _this.url = url;
  86467. _this.hasAlpha = false;
  86468. _this.isCube = true;
  86469. _this._textureMatrix = BABYLON.Matrix.Identity();
  86470. _this._onLoad = onLoad;
  86471. _this._onError = onError;
  86472. _this.gammaSpace = gammaSpace;
  86473. _this._noMipmap = noMipmap;
  86474. _this._size = size;
  86475. _this._texture = _this._getFromCache(url, _this._noMipmap);
  86476. if (!_this._texture) {
  86477. if (!scene.useDelayedTextureLoading) {
  86478. _this.loadTexture();
  86479. }
  86480. else {
  86481. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  86482. }
  86483. }
  86484. return _this;
  86485. }
  86486. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  86487. /**
  86488. * Gets wether or not the texture is blocking during loading.
  86489. */
  86490. get: function () {
  86491. return this._isBlocking;
  86492. },
  86493. /**
  86494. * Sets wether or not the texture is blocking during loading.
  86495. */
  86496. set: function (value) {
  86497. this._isBlocking = value;
  86498. },
  86499. enumerable: true,
  86500. configurable: true
  86501. });
  86502. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  86503. /**
  86504. * Gets texture matrix rotation angle around Y axis radians.
  86505. */
  86506. get: function () {
  86507. return this._rotationY;
  86508. },
  86509. /**
  86510. * Sets texture matrix rotation angle around Y axis in radians.
  86511. */
  86512. set: function (value) {
  86513. this._rotationY = value;
  86514. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  86515. },
  86516. enumerable: true,
  86517. configurable: true
  86518. });
  86519. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  86520. get: function () {
  86521. return this._boundingBoxSize;
  86522. },
  86523. /**
  86524. * Gets or sets the size of the bounding box associated with the cube texture
  86525. * When defined, the cubemap will switch to local mode
  86526. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  86527. * @example https://www.babylonjs-playground.com/#RNASML
  86528. */
  86529. set: function (value) {
  86530. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  86531. return;
  86532. }
  86533. this._boundingBoxSize = value;
  86534. var scene = this.getScene();
  86535. if (scene) {
  86536. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  86537. }
  86538. },
  86539. enumerable: true,
  86540. configurable: true
  86541. });
  86542. /**
  86543. * Occurs when the file is raw .hdr file.
  86544. */
  86545. HDRCubeTexture.prototype.loadTexture = function () {
  86546. var _this = this;
  86547. var callback = function (buffer) {
  86548. _this.lodGenerationOffset = 0.0;
  86549. _this.lodGenerationScale = 0.8;
  86550. var scene = _this.getScene();
  86551. if (!scene) {
  86552. return null;
  86553. }
  86554. // Extract the raw linear data.
  86555. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  86556. // Generate harmonics if needed.
  86557. if (_this._generateHarmonics) {
  86558. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  86559. _this.sphericalPolynomial = sphericalPolynomial;
  86560. }
  86561. var results = [];
  86562. var byteArray = null;
  86563. // Push each faces.
  86564. for (var j = 0; j < 6; j++) {
  86565. // Create uintarray fallback.
  86566. if (!scene.getEngine().getCaps().textureFloat) {
  86567. // 3 channels of 1 bytes per pixel in bytes.
  86568. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  86569. byteArray = new Uint8Array(byteBuffer);
  86570. }
  86571. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  86572. // If special cases.
  86573. if (_this.gammaSpace || byteArray) {
  86574. for (var i = 0; i < _this._size * _this._size; i++) {
  86575. // Put in gamma space if requested.
  86576. if (_this.gammaSpace) {
  86577. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  86578. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  86579. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  86580. }
  86581. // Convert to int texture for fallback.
  86582. if (byteArray) {
  86583. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  86584. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  86585. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  86586. // May use luminance instead if the result is not accurate.
  86587. var max = Math.max(Math.max(r, g), b);
  86588. if (max > 255) {
  86589. var scale = 255 / max;
  86590. r *= scale;
  86591. g *= scale;
  86592. b *= scale;
  86593. }
  86594. byteArray[(i * 3) + 0] = r;
  86595. byteArray[(i * 3) + 1] = g;
  86596. byteArray[(i * 3) + 2] = b;
  86597. }
  86598. }
  86599. }
  86600. if (byteArray) {
  86601. results.push(byteArray);
  86602. }
  86603. else {
  86604. results.push(dataFace);
  86605. }
  86606. }
  86607. return results;
  86608. };
  86609. var scene = this.getScene();
  86610. if (scene) {
  86611. 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);
  86612. }
  86613. };
  86614. HDRCubeTexture.prototype.clone = function () {
  86615. var scene = this.getScene();
  86616. if (!scene) {
  86617. return this;
  86618. }
  86619. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  86620. // Base texture
  86621. newTexture.level = this.level;
  86622. newTexture.wrapU = this.wrapU;
  86623. newTexture.wrapV = this.wrapV;
  86624. newTexture.coordinatesIndex = this.coordinatesIndex;
  86625. newTexture.coordinatesMode = this.coordinatesMode;
  86626. return newTexture;
  86627. };
  86628. // Methods
  86629. HDRCubeTexture.prototype.delayLoad = function () {
  86630. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  86631. return;
  86632. }
  86633. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  86634. this._texture = this._getFromCache(this.url, this._noMipmap);
  86635. if (!this._texture) {
  86636. this.loadTexture();
  86637. }
  86638. };
  86639. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  86640. return this._textureMatrix;
  86641. };
  86642. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  86643. this._textureMatrix = value;
  86644. };
  86645. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  86646. var texture = null;
  86647. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  86648. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  86649. texture.name = parsedTexture.name;
  86650. texture.hasAlpha = parsedTexture.hasAlpha;
  86651. texture.level = parsedTexture.level;
  86652. texture.coordinatesMode = parsedTexture.coordinatesMode;
  86653. texture.isBlocking = parsedTexture.isBlocking;
  86654. }
  86655. if (texture) {
  86656. if (parsedTexture.boundingBoxPosition) {
  86657. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  86658. }
  86659. if (parsedTexture.boundingBoxSize) {
  86660. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  86661. }
  86662. if (parsedTexture.rotationY) {
  86663. texture.rotationY = parsedTexture.rotationY;
  86664. }
  86665. }
  86666. return texture;
  86667. };
  86668. HDRCubeTexture.prototype.serialize = function () {
  86669. if (!this.name) {
  86670. return null;
  86671. }
  86672. var serializationObject = {};
  86673. serializationObject.name = this.name;
  86674. serializationObject.hasAlpha = this.hasAlpha;
  86675. serializationObject.isCube = true;
  86676. serializationObject.level = this.level;
  86677. serializationObject.size = this._size;
  86678. serializationObject.coordinatesMode = this.coordinatesMode;
  86679. serializationObject.useInGammaSpace = this.gammaSpace;
  86680. serializationObject.generateHarmonics = this._generateHarmonics;
  86681. serializationObject.customType = "BABYLON.HDRCubeTexture";
  86682. serializationObject.noMipmap = this._noMipmap;
  86683. serializationObject.isBlocking = this._isBlocking;
  86684. serializationObject.rotationY = this._rotationY;
  86685. return serializationObject;
  86686. };
  86687. HDRCubeTexture._facesMapping = [
  86688. "right",
  86689. "left",
  86690. "up",
  86691. "down",
  86692. "front",
  86693. "back"
  86694. ];
  86695. return HDRCubeTexture;
  86696. }(BABYLON.BaseTexture));
  86697. BABYLON.HDRCubeTexture = HDRCubeTexture;
  86698. })(BABYLON || (BABYLON = {}));
  86699. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  86700. var BABYLON;
  86701. (function (BABYLON) {
  86702. /**
  86703. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  86704. */
  86705. var PanoramaToCubeMapTools = /** @class */ (function () {
  86706. function PanoramaToCubeMapTools() {
  86707. }
  86708. /**
  86709. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  86710. *
  86711. * @param float32Array The source data.
  86712. * @param inputWidth The width of the input panorama.
  86713. * @param inputhHeight The height of the input panorama.
  86714. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  86715. * @return The cubemap data
  86716. */
  86717. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  86718. if (!float32Array) {
  86719. throw "ConvertPanoramaToCubemap: input cannot be null";
  86720. }
  86721. if (float32Array.length != inputWidth * inputHeight * 3) {
  86722. throw "ConvertPanoramaToCubemap: input size is wrong";
  86723. }
  86724. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  86725. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  86726. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  86727. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  86728. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  86729. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  86730. return {
  86731. front: textureFront,
  86732. back: textureBack,
  86733. left: textureLeft,
  86734. right: textureRight,
  86735. up: textureUp,
  86736. down: textureDown,
  86737. size: size,
  86738. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  86739. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  86740. gammaSpace: false,
  86741. };
  86742. };
  86743. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  86744. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  86745. var textureArray = new Float32Array(buffer);
  86746. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  86747. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  86748. var dy = 1 / texSize;
  86749. var fy = 0;
  86750. for (var y = 0; y < texSize; y++) {
  86751. var xv1 = faceData[0];
  86752. var xv2 = faceData[2];
  86753. for (var x = 0; x < texSize; x++) {
  86754. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  86755. v.normalize();
  86756. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  86757. // 3 channels per pixels
  86758. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  86759. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  86760. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  86761. xv1 = xv1.add(rotDX1);
  86762. xv2 = xv2.add(rotDX2);
  86763. }
  86764. fy += dy;
  86765. }
  86766. return textureArray;
  86767. };
  86768. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  86769. var theta = Math.atan2(vDir.z, vDir.x);
  86770. var phi = Math.acos(vDir.y);
  86771. while (theta < -Math.PI)
  86772. theta += 2 * Math.PI;
  86773. while (theta > Math.PI)
  86774. theta -= 2 * Math.PI;
  86775. var dx = theta / Math.PI;
  86776. var dy = phi / Math.PI;
  86777. // recenter.
  86778. dx = dx * 0.5 + 0.5;
  86779. var px = Math.round(dx * inputWidth);
  86780. if (px < 0)
  86781. px = 0;
  86782. else if (px >= inputWidth)
  86783. px = inputWidth - 1;
  86784. var py = Math.round(dy * inputHeight);
  86785. if (py < 0)
  86786. py = 0;
  86787. else if (py >= inputHeight)
  86788. py = inputHeight - 1;
  86789. var inputY = (inputHeight - py - 1);
  86790. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  86791. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  86792. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  86793. return {
  86794. r: r,
  86795. g: g,
  86796. b: b
  86797. };
  86798. };
  86799. PanoramaToCubeMapTools.FACE_FRONT = [
  86800. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  86801. new BABYLON.Vector3(1.0, -1.0, -1.0),
  86802. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  86803. new BABYLON.Vector3(1.0, 1.0, -1.0)
  86804. ];
  86805. PanoramaToCubeMapTools.FACE_BACK = [
  86806. new BABYLON.Vector3(1.0, -1.0, 1.0),
  86807. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  86808. new BABYLON.Vector3(1.0, 1.0, 1.0),
  86809. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  86810. ];
  86811. PanoramaToCubeMapTools.FACE_RIGHT = [
  86812. new BABYLON.Vector3(1.0, -1.0, -1.0),
  86813. new BABYLON.Vector3(1.0, -1.0, 1.0),
  86814. new BABYLON.Vector3(1.0, 1.0, -1.0),
  86815. new BABYLON.Vector3(1.0, 1.0, 1.0)
  86816. ];
  86817. PanoramaToCubeMapTools.FACE_LEFT = [
  86818. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  86819. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  86820. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  86821. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  86822. ];
  86823. PanoramaToCubeMapTools.FACE_DOWN = [
  86824. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  86825. new BABYLON.Vector3(1.0, 1.0, -1.0),
  86826. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  86827. new BABYLON.Vector3(1.0, 1.0, 1.0)
  86828. ];
  86829. PanoramaToCubeMapTools.FACE_UP = [
  86830. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  86831. new BABYLON.Vector3(1.0, -1.0, 1.0),
  86832. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  86833. new BABYLON.Vector3(1.0, -1.0, -1.0)
  86834. ];
  86835. return PanoramaToCubeMapTools;
  86836. }());
  86837. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  86838. })(BABYLON || (BABYLON = {}));
  86839. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  86840. var BABYLON;
  86841. (function (BABYLON) {
  86842. var IndexedVector2 = /** @class */ (function (_super) {
  86843. __extends(IndexedVector2, _super);
  86844. function IndexedVector2(original, index) {
  86845. var _this = _super.call(this, original.x, original.y) || this;
  86846. _this.index = index;
  86847. return _this;
  86848. }
  86849. return IndexedVector2;
  86850. }(BABYLON.Vector2));
  86851. var PolygonPoints = /** @class */ (function () {
  86852. function PolygonPoints() {
  86853. this.elements = new Array();
  86854. }
  86855. PolygonPoints.prototype.add = function (originalPoints) {
  86856. var _this = this;
  86857. var result = new Array();
  86858. originalPoints.forEach(function (point) {
  86859. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  86860. var newPoint = new IndexedVector2(point, _this.elements.length);
  86861. result.push(newPoint);
  86862. _this.elements.push(newPoint);
  86863. }
  86864. });
  86865. return result;
  86866. };
  86867. PolygonPoints.prototype.computeBounds = function () {
  86868. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  86869. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  86870. this.elements.forEach(function (point) {
  86871. // x
  86872. if (point.x < lmin.x) {
  86873. lmin.x = point.x;
  86874. }
  86875. else if (point.x > lmax.x) {
  86876. lmax.x = point.x;
  86877. }
  86878. // y
  86879. if (point.y < lmin.y) {
  86880. lmin.y = point.y;
  86881. }
  86882. else if (point.y > lmax.y) {
  86883. lmax.y = point.y;
  86884. }
  86885. });
  86886. return {
  86887. min: lmin,
  86888. max: lmax,
  86889. width: lmax.x - lmin.x,
  86890. height: lmax.y - lmin.y
  86891. };
  86892. };
  86893. return PolygonPoints;
  86894. }());
  86895. var Polygon = /** @class */ (function () {
  86896. function Polygon() {
  86897. }
  86898. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  86899. return [
  86900. new BABYLON.Vector2(xmin, ymin),
  86901. new BABYLON.Vector2(xmax, ymin),
  86902. new BABYLON.Vector2(xmax, ymax),
  86903. new BABYLON.Vector2(xmin, ymax)
  86904. ];
  86905. };
  86906. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  86907. if (cx === void 0) { cx = 0; }
  86908. if (cy === void 0) { cy = 0; }
  86909. if (numberOfSides === void 0) { numberOfSides = 32; }
  86910. var result = new Array();
  86911. var angle = 0;
  86912. var increment = (Math.PI * 2) / numberOfSides;
  86913. for (var i = 0; i < numberOfSides; i++) {
  86914. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  86915. angle -= increment;
  86916. }
  86917. return result;
  86918. };
  86919. Polygon.Parse = function (input) {
  86920. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  86921. var i, result = [];
  86922. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  86923. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  86924. }
  86925. return result;
  86926. };
  86927. Polygon.StartingAt = function (x, y) {
  86928. return BABYLON.Path2.StartingAt(x, y);
  86929. };
  86930. return Polygon;
  86931. }());
  86932. BABYLON.Polygon = Polygon;
  86933. var PolygonMeshBuilder = /** @class */ (function () {
  86934. function PolygonMeshBuilder(name, contours, scene) {
  86935. this._points = new PolygonPoints();
  86936. this._outlinepoints = new PolygonPoints();
  86937. this._holes = new Array();
  86938. this._epoints = new Array();
  86939. this._eholes = new Array();
  86940. this._name = name;
  86941. this._scene = scene;
  86942. var points;
  86943. if (contours instanceof BABYLON.Path2) {
  86944. points = contours.getPoints();
  86945. }
  86946. else {
  86947. points = contours;
  86948. }
  86949. this._addToepoint(points);
  86950. this._points.add(points);
  86951. this._outlinepoints.add(points);
  86952. if (typeof earcut === 'undefined') {
  86953. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  86954. }
  86955. }
  86956. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  86957. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  86958. var p = points_1[_i];
  86959. this._epoints.push(p.x, p.y);
  86960. }
  86961. };
  86962. PolygonMeshBuilder.prototype.addHole = function (hole) {
  86963. this._points.add(hole);
  86964. var holepoints = new PolygonPoints();
  86965. holepoints.add(hole);
  86966. this._holes.push(holepoints);
  86967. this._eholes.push(this._epoints.length / 2);
  86968. this._addToepoint(hole);
  86969. return this;
  86970. };
  86971. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  86972. var _this = this;
  86973. if (updatable === void 0) { updatable = false; }
  86974. if (depth === void 0) { depth = 0; }
  86975. var result = new BABYLON.Mesh(this._name, this._scene);
  86976. var normals = new Array();
  86977. var positions = new Array();
  86978. var uvs = new Array();
  86979. var bounds = this._points.computeBounds();
  86980. this._points.elements.forEach(function (p) {
  86981. normals.push(0, 1.0, 0);
  86982. positions.push(p.x, 0, p.y);
  86983. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  86984. });
  86985. var indices = new Array();
  86986. var res = earcut(this._epoints, this._eholes, 2);
  86987. for (var i = 0; i < res.length; i++) {
  86988. indices.push(res[i]);
  86989. }
  86990. if (depth > 0) {
  86991. var positionscount = (positions.length / 3); //get the current pointcount
  86992. this._points.elements.forEach(function (p) {
  86993. normals.push(0, -1.0, 0);
  86994. positions.push(p.x, -depth, p.y);
  86995. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  86996. });
  86997. var totalCount = indices.length;
  86998. for (var i = 0; i < totalCount; i += 3) {
  86999. var i0 = indices[i + 0];
  87000. var i1 = indices[i + 1];
  87001. var i2 = indices[i + 2];
  87002. indices.push(i2 + positionscount);
  87003. indices.push(i1 + positionscount);
  87004. indices.push(i0 + positionscount);
  87005. }
  87006. //Add the sides
  87007. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  87008. this._holes.forEach(function (hole) {
  87009. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  87010. });
  87011. }
  87012. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  87013. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  87014. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  87015. result.setIndices(indices);
  87016. return result;
  87017. };
  87018. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  87019. var StartIndex = positions.length / 3;
  87020. var ulength = 0;
  87021. for (var i = 0; i < points.elements.length; i++) {
  87022. var p = points.elements[i];
  87023. var p1;
  87024. if ((i + 1) > points.elements.length - 1) {
  87025. p1 = points.elements[0];
  87026. }
  87027. else {
  87028. p1 = points.elements[i + 1];
  87029. }
  87030. positions.push(p.x, 0, p.y);
  87031. positions.push(p.x, -depth, p.y);
  87032. positions.push(p1.x, 0, p1.y);
  87033. positions.push(p1.x, -depth, p1.y);
  87034. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  87035. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  87036. var v3 = v2.subtract(v1);
  87037. var v4 = new BABYLON.Vector3(0, 1, 0);
  87038. var vn = BABYLON.Vector3.Cross(v3, v4);
  87039. vn = vn.normalize();
  87040. uvs.push(ulength / bounds.width, 0);
  87041. uvs.push(ulength / bounds.width, 1);
  87042. ulength += v3.length();
  87043. uvs.push((ulength / bounds.width), 0);
  87044. uvs.push((ulength / bounds.width), 1);
  87045. if (!flip) {
  87046. normals.push(-vn.x, -vn.y, -vn.z);
  87047. normals.push(-vn.x, -vn.y, -vn.z);
  87048. normals.push(-vn.x, -vn.y, -vn.z);
  87049. normals.push(-vn.x, -vn.y, -vn.z);
  87050. indices.push(StartIndex);
  87051. indices.push(StartIndex + 1);
  87052. indices.push(StartIndex + 2);
  87053. indices.push(StartIndex + 1);
  87054. indices.push(StartIndex + 3);
  87055. indices.push(StartIndex + 2);
  87056. }
  87057. else {
  87058. normals.push(vn.x, vn.y, vn.z);
  87059. normals.push(vn.x, vn.y, vn.z);
  87060. normals.push(vn.x, vn.y, vn.z);
  87061. normals.push(vn.x, vn.y, vn.z);
  87062. indices.push(StartIndex);
  87063. indices.push(StartIndex + 2);
  87064. indices.push(StartIndex + 1);
  87065. indices.push(StartIndex + 1);
  87066. indices.push(StartIndex + 2);
  87067. indices.push(StartIndex + 3);
  87068. }
  87069. StartIndex += 4;
  87070. }
  87071. ;
  87072. };
  87073. return PolygonMeshBuilder;
  87074. }());
  87075. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  87076. })(BABYLON || (BABYLON = {}));
  87077. //# sourceMappingURL=babylon.polygonMesh.js.map
  87078. var BABYLON;
  87079. (function (BABYLON) {
  87080. // Unique ID when we import meshes from Babylon to CSG
  87081. var currentCSGMeshId = 0;
  87082. // # class Vertex
  87083. // Represents a vertex of a polygon. Use your own vertex class instead of this
  87084. // one to provide additional features like texture coordinates and vertex
  87085. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  87086. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  87087. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  87088. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  87089. // is not used anywhere else.
  87090. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  87091. var Vertex = /** @class */ (function () {
  87092. function Vertex(pos, normal, uv) {
  87093. this.pos = pos;
  87094. this.normal = normal;
  87095. this.uv = uv;
  87096. }
  87097. Vertex.prototype.clone = function () {
  87098. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  87099. };
  87100. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  87101. // orientation of a polygon is flipped.
  87102. Vertex.prototype.flip = function () {
  87103. this.normal = this.normal.scale(-1);
  87104. };
  87105. // Create a new vertex between this vertex and `other` by linearly
  87106. // interpolating all properties using a parameter of `t`. Subclasses should
  87107. // override this to interpolate additional properties.
  87108. Vertex.prototype.interpolate = function (other, t) {
  87109. 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));
  87110. };
  87111. return Vertex;
  87112. }());
  87113. // # class Plane
  87114. // Represents a plane in 3D space.
  87115. var Plane = /** @class */ (function () {
  87116. function Plane(normal, w) {
  87117. this.normal = normal;
  87118. this.w = w;
  87119. }
  87120. Plane.FromPoints = function (a, b, c) {
  87121. var v0 = c.subtract(a);
  87122. var v1 = b.subtract(a);
  87123. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  87124. return null;
  87125. }
  87126. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  87127. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  87128. };
  87129. Plane.prototype.clone = function () {
  87130. return new Plane(this.normal.clone(), this.w);
  87131. };
  87132. Plane.prototype.flip = function () {
  87133. this.normal.scaleInPlace(-1);
  87134. this.w = -this.w;
  87135. };
  87136. // Split `polygon` by this plane if needed, then put the polygon or polygon
  87137. // fragments in the appropriate lists. Coplanar polygons go into either
  87138. // `coplanarFront` or `coplanarBack` depending on their orientation with
  87139. // respect to this plane. Polygons in front or in back of this plane go into
  87140. // either `front` or `back`.
  87141. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  87142. var COPLANAR = 0;
  87143. var FRONT = 1;
  87144. var BACK = 2;
  87145. var SPANNING = 3;
  87146. // Classify each point as well as the entire polygon into one of the above
  87147. // four classes.
  87148. var polygonType = 0;
  87149. var types = [];
  87150. var i;
  87151. var t;
  87152. for (i = 0; i < polygon.vertices.length; i++) {
  87153. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  87154. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  87155. polygonType |= type;
  87156. types.push(type);
  87157. }
  87158. // Put the polygon in the correct list, splitting it when necessary.
  87159. switch (polygonType) {
  87160. case COPLANAR:
  87161. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  87162. break;
  87163. case FRONT:
  87164. front.push(polygon);
  87165. break;
  87166. case BACK:
  87167. back.push(polygon);
  87168. break;
  87169. case SPANNING:
  87170. var f = [], b = [];
  87171. for (i = 0; i < polygon.vertices.length; i++) {
  87172. var j = (i + 1) % polygon.vertices.length;
  87173. var ti = types[i], tj = types[j];
  87174. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  87175. if (ti !== BACK)
  87176. f.push(vi);
  87177. if (ti !== FRONT)
  87178. b.push(ti !== BACK ? vi.clone() : vi);
  87179. if ((ti | tj) === SPANNING) {
  87180. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  87181. var v = vi.interpolate(vj, t);
  87182. f.push(v);
  87183. b.push(v.clone());
  87184. }
  87185. }
  87186. var poly;
  87187. if (f.length >= 3) {
  87188. poly = new Polygon(f, polygon.shared);
  87189. if (poly.plane)
  87190. front.push(poly);
  87191. }
  87192. if (b.length >= 3) {
  87193. poly = new Polygon(b, polygon.shared);
  87194. if (poly.plane)
  87195. back.push(poly);
  87196. }
  87197. break;
  87198. }
  87199. };
  87200. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  87201. // point is on the plane.
  87202. Plane.EPSILON = 1e-5;
  87203. return Plane;
  87204. }());
  87205. // # class Polygon
  87206. // Represents a convex polygon. The vertices used to initialize a polygon must
  87207. // be coplanar and form a convex loop.
  87208. //
  87209. // Each convex polygon has a `shared` property, which is shared between all
  87210. // polygons that are clones of each other or were split from the same polygon.
  87211. // This can be used to define per-polygon properties (such as surface color).
  87212. var Polygon = /** @class */ (function () {
  87213. function Polygon(vertices, shared) {
  87214. this.vertices = vertices;
  87215. this.shared = shared;
  87216. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  87217. }
  87218. Polygon.prototype.clone = function () {
  87219. var vertices = this.vertices.map(function (v) { return v.clone(); });
  87220. return new Polygon(vertices, this.shared);
  87221. };
  87222. Polygon.prototype.flip = function () {
  87223. this.vertices.reverse().map(function (v) { v.flip(); });
  87224. this.plane.flip();
  87225. };
  87226. return Polygon;
  87227. }());
  87228. // # class Node
  87229. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  87230. // by picking a polygon to split along. That polygon (and all other coplanar
  87231. // polygons) are added directly to that node and the other polygons are added to
  87232. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  87233. // no distinction between internal and leaf nodes.
  87234. var Node = /** @class */ (function () {
  87235. function Node(polygons) {
  87236. this.plane = null;
  87237. this.front = null;
  87238. this.back = null;
  87239. this.polygons = new Array();
  87240. if (polygons) {
  87241. this.build(polygons);
  87242. }
  87243. }
  87244. Node.prototype.clone = function () {
  87245. var node = new Node();
  87246. node.plane = this.plane && this.plane.clone();
  87247. node.front = this.front && this.front.clone();
  87248. node.back = this.back && this.back.clone();
  87249. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  87250. return node;
  87251. };
  87252. // Convert solid space to empty space and empty space to solid space.
  87253. Node.prototype.invert = function () {
  87254. for (var i = 0; i < this.polygons.length; i++) {
  87255. this.polygons[i].flip();
  87256. }
  87257. if (this.plane) {
  87258. this.plane.flip();
  87259. }
  87260. if (this.front) {
  87261. this.front.invert();
  87262. }
  87263. if (this.back) {
  87264. this.back.invert();
  87265. }
  87266. var temp = this.front;
  87267. this.front = this.back;
  87268. this.back = temp;
  87269. };
  87270. // Recursively remove all polygons in `polygons` that are inside this BSP
  87271. // tree.
  87272. Node.prototype.clipPolygons = function (polygons) {
  87273. if (!this.plane)
  87274. return polygons.slice();
  87275. var front = new Array(), back = new Array();
  87276. for (var i = 0; i < polygons.length; i++) {
  87277. this.plane.splitPolygon(polygons[i], front, back, front, back);
  87278. }
  87279. if (this.front) {
  87280. front = this.front.clipPolygons(front);
  87281. }
  87282. if (this.back) {
  87283. back = this.back.clipPolygons(back);
  87284. }
  87285. else {
  87286. back = [];
  87287. }
  87288. return front.concat(back);
  87289. };
  87290. // Remove all polygons in this BSP tree that are inside the other BSP tree
  87291. // `bsp`.
  87292. Node.prototype.clipTo = function (bsp) {
  87293. this.polygons = bsp.clipPolygons(this.polygons);
  87294. if (this.front)
  87295. this.front.clipTo(bsp);
  87296. if (this.back)
  87297. this.back.clipTo(bsp);
  87298. };
  87299. // Return a list of all polygons in this BSP tree.
  87300. Node.prototype.allPolygons = function () {
  87301. var polygons = this.polygons.slice();
  87302. if (this.front)
  87303. polygons = polygons.concat(this.front.allPolygons());
  87304. if (this.back)
  87305. polygons = polygons.concat(this.back.allPolygons());
  87306. return polygons;
  87307. };
  87308. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  87309. // new polygons are filtered down to the bottom of the tree and become new
  87310. // nodes there. Each set of polygons is partitioned using the first polygon
  87311. // (no heuristic is used to pick a good split).
  87312. Node.prototype.build = function (polygons) {
  87313. if (!polygons.length)
  87314. return;
  87315. if (!this.plane)
  87316. this.plane = polygons[0].plane.clone();
  87317. var front = new Array(), back = new Array();
  87318. for (var i = 0; i < polygons.length; i++) {
  87319. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  87320. }
  87321. if (front.length) {
  87322. if (!this.front)
  87323. this.front = new Node();
  87324. this.front.build(front);
  87325. }
  87326. if (back.length) {
  87327. if (!this.back)
  87328. this.back = new Node();
  87329. this.back.build(back);
  87330. }
  87331. };
  87332. return Node;
  87333. }());
  87334. var CSG = /** @class */ (function () {
  87335. function CSG() {
  87336. this.polygons = new Array();
  87337. }
  87338. // Convert BABYLON.Mesh to BABYLON.CSG
  87339. CSG.FromMesh = function (mesh) {
  87340. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  87341. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  87342. if (mesh instanceof BABYLON.Mesh) {
  87343. mesh.computeWorldMatrix(true);
  87344. matrix = mesh.getWorldMatrix();
  87345. meshPosition = mesh.position.clone();
  87346. meshRotation = mesh.rotation.clone();
  87347. if (mesh.rotationQuaternion) {
  87348. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  87349. }
  87350. meshScaling = mesh.scaling.clone();
  87351. }
  87352. else {
  87353. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  87354. }
  87355. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  87356. var subMeshes = mesh.subMeshes;
  87357. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  87358. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  87359. vertices = [];
  87360. for (var j = 0; j < 3; j++) {
  87361. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  87362. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  87363. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  87364. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  87365. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  87366. vertex = new Vertex(position, normal, uv);
  87367. vertices.push(vertex);
  87368. }
  87369. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  87370. // To handle the case of degenerated triangle
  87371. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  87372. if (polygon.plane)
  87373. polygons.push(polygon);
  87374. }
  87375. }
  87376. var csg = CSG.FromPolygons(polygons);
  87377. csg.matrix = matrix;
  87378. csg.position = meshPosition;
  87379. csg.rotation = meshRotation;
  87380. csg.scaling = meshScaling;
  87381. csg.rotationQuaternion = meshRotationQuaternion;
  87382. currentCSGMeshId++;
  87383. return csg;
  87384. };
  87385. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  87386. CSG.FromPolygons = function (polygons) {
  87387. var csg = new CSG();
  87388. csg.polygons = polygons;
  87389. return csg;
  87390. };
  87391. CSG.prototype.clone = function () {
  87392. var csg = new CSG();
  87393. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  87394. csg.copyTransformAttributes(this);
  87395. return csg;
  87396. };
  87397. CSG.prototype.union = function (csg) {
  87398. var a = new Node(this.clone().polygons);
  87399. var b = new Node(csg.clone().polygons);
  87400. a.clipTo(b);
  87401. b.clipTo(a);
  87402. b.invert();
  87403. b.clipTo(a);
  87404. b.invert();
  87405. a.build(b.allPolygons());
  87406. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  87407. };
  87408. CSG.prototype.unionInPlace = function (csg) {
  87409. var a = new Node(this.polygons);
  87410. var b = new Node(csg.polygons);
  87411. a.clipTo(b);
  87412. b.clipTo(a);
  87413. b.invert();
  87414. b.clipTo(a);
  87415. b.invert();
  87416. a.build(b.allPolygons());
  87417. this.polygons = a.allPolygons();
  87418. };
  87419. CSG.prototype.subtract = function (csg) {
  87420. var a = new Node(this.clone().polygons);
  87421. var b = new Node(csg.clone().polygons);
  87422. a.invert();
  87423. a.clipTo(b);
  87424. b.clipTo(a);
  87425. b.invert();
  87426. b.clipTo(a);
  87427. b.invert();
  87428. a.build(b.allPolygons());
  87429. a.invert();
  87430. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  87431. };
  87432. CSG.prototype.subtractInPlace = function (csg) {
  87433. var a = new Node(this.polygons);
  87434. var b = new Node(csg.polygons);
  87435. a.invert();
  87436. a.clipTo(b);
  87437. b.clipTo(a);
  87438. b.invert();
  87439. b.clipTo(a);
  87440. b.invert();
  87441. a.build(b.allPolygons());
  87442. a.invert();
  87443. this.polygons = a.allPolygons();
  87444. };
  87445. CSG.prototype.intersect = function (csg) {
  87446. var a = new Node(this.clone().polygons);
  87447. var b = new Node(csg.clone().polygons);
  87448. a.invert();
  87449. b.clipTo(a);
  87450. b.invert();
  87451. a.clipTo(b);
  87452. b.clipTo(a);
  87453. a.build(b.allPolygons());
  87454. a.invert();
  87455. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  87456. };
  87457. CSG.prototype.intersectInPlace = function (csg) {
  87458. var a = new Node(this.polygons);
  87459. var b = new Node(csg.polygons);
  87460. a.invert();
  87461. b.clipTo(a);
  87462. b.invert();
  87463. a.clipTo(b);
  87464. b.clipTo(a);
  87465. a.build(b.allPolygons());
  87466. a.invert();
  87467. this.polygons = a.allPolygons();
  87468. };
  87469. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  87470. // not modified.
  87471. CSG.prototype.inverse = function () {
  87472. var csg = this.clone();
  87473. csg.inverseInPlace();
  87474. return csg;
  87475. };
  87476. CSG.prototype.inverseInPlace = function () {
  87477. this.polygons.map(function (p) { p.flip(); });
  87478. };
  87479. // This is used to keep meshes transformations so they can be restored
  87480. // when we build back a Babylon Mesh
  87481. // NB : All CSG operations are performed in world coordinates
  87482. CSG.prototype.copyTransformAttributes = function (csg) {
  87483. this.matrix = csg.matrix;
  87484. this.position = csg.position;
  87485. this.rotation = csg.rotation;
  87486. this.scaling = csg.scaling;
  87487. this.rotationQuaternion = csg.rotationQuaternion;
  87488. return this;
  87489. };
  87490. // Build Raw mesh from CSG
  87491. // Coordinates here are in world space
  87492. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  87493. var matrix = this.matrix.clone();
  87494. matrix.invert();
  87495. 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;
  87496. if (keepSubMeshes) {
  87497. // Sort Polygons, since subMeshes are indices range
  87498. polygons.sort(function (a, b) {
  87499. if (a.shared.meshId === b.shared.meshId) {
  87500. return a.shared.subMeshId - b.shared.subMeshId;
  87501. }
  87502. else {
  87503. return a.shared.meshId - b.shared.meshId;
  87504. }
  87505. });
  87506. }
  87507. for (var i = 0, il = polygons.length; i < il; i++) {
  87508. polygon = polygons[i];
  87509. // Building SubMeshes
  87510. if (!subMesh_dict[polygon.shared.meshId]) {
  87511. subMesh_dict[polygon.shared.meshId] = {};
  87512. }
  87513. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  87514. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  87515. indexStart: +Infinity,
  87516. indexEnd: -Infinity,
  87517. materialIndex: polygon.shared.materialIndex
  87518. };
  87519. }
  87520. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  87521. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  87522. polygonIndices[0] = 0;
  87523. polygonIndices[1] = j - 1;
  87524. polygonIndices[2] = j;
  87525. for (var k = 0; k < 3; k++) {
  87526. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  87527. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  87528. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  87529. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  87530. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  87531. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  87532. // Check if 2 points can be merged
  87533. if (!(typeof vertex_idx !== 'undefined' &&
  87534. normals[vertex_idx * 3] === localNormal.x &&
  87535. normals[vertex_idx * 3 + 1] === localNormal.y &&
  87536. normals[vertex_idx * 3 + 2] === localNormal.z &&
  87537. uvs[vertex_idx * 2] === uv.x &&
  87538. uvs[vertex_idx * 2 + 1] === uv.y)) {
  87539. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  87540. uvs.push(uv.x, uv.y);
  87541. normals.push(normal.x, normal.y, normal.z);
  87542. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  87543. }
  87544. indices.push(vertex_idx);
  87545. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  87546. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  87547. currentIndex++;
  87548. }
  87549. }
  87550. }
  87551. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  87552. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  87553. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  87554. mesh.setIndices(indices, null);
  87555. if (keepSubMeshes) {
  87556. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  87557. var materialIndexOffset = 0, materialMaxIndex;
  87558. mesh.subMeshes = new Array();
  87559. for (var m in subMesh_dict) {
  87560. materialMaxIndex = -1;
  87561. for (var sm in subMesh_dict[m]) {
  87562. subMesh_obj = subMesh_dict[m][sm];
  87563. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  87564. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  87565. }
  87566. materialIndexOffset += ++materialMaxIndex;
  87567. }
  87568. }
  87569. return mesh;
  87570. };
  87571. // Build Mesh from CSG taking material and transforms into account
  87572. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  87573. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  87574. mesh.material = material;
  87575. mesh.position.copyFrom(this.position);
  87576. mesh.rotation.copyFrom(this.rotation);
  87577. if (this.rotationQuaternion) {
  87578. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  87579. }
  87580. mesh.scaling.copyFrom(this.scaling);
  87581. mesh.computeWorldMatrix(true);
  87582. return mesh;
  87583. };
  87584. return CSG;
  87585. }());
  87586. BABYLON.CSG = CSG;
  87587. })(BABYLON || (BABYLON = {}));
  87588. //# sourceMappingURL=babylon.csg.js.map
  87589. var BABYLON;
  87590. (function (BABYLON) {
  87591. var LensFlare = /** @class */ (function () {
  87592. function LensFlare(size, position, color, imgUrl, system) {
  87593. this.size = size;
  87594. this.position = position;
  87595. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  87596. this.color = color || new BABYLON.Color3(1, 1, 1);
  87597. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  87598. this._system = system;
  87599. system.lensFlares.push(this);
  87600. }
  87601. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  87602. return new LensFlare(size, position, color, imgUrl, system);
  87603. };
  87604. LensFlare.prototype.dispose = function () {
  87605. if (this.texture) {
  87606. this.texture.dispose();
  87607. }
  87608. // Remove from scene
  87609. var index = this._system.lensFlares.indexOf(this);
  87610. this._system.lensFlares.splice(index, 1);
  87611. };
  87612. ;
  87613. return LensFlare;
  87614. }());
  87615. BABYLON.LensFlare = LensFlare;
  87616. })(BABYLON || (BABYLON = {}));
  87617. //# sourceMappingURL=babylon.lensFlare.js.map
  87618. var BABYLON;
  87619. (function (BABYLON) {
  87620. // Adds the parser to the scene parsers.
  87621. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM, function (parsedData, scene, container, rootUrl) {
  87622. // Lens flares
  87623. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  87624. if (!container.lensFlareSystems) {
  87625. container.lensFlareSystems = new Array();
  87626. }
  87627. for (var index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  87628. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  87629. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  87630. container.lensFlareSystems.push(lf);
  87631. }
  87632. }
  87633. });
  87634. BABYLON.AbstractScene.prototype.getLensFlareSystemByName = function (name) {
  87635. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  87636. if (this.lensFlareSystems[index].name === name) {
  87637. return this.lensFlareSystems[index];
  87638. }
  87639. }
  87640. return null;
  87641. };
  87642. BABYLON.AbstractScene.prototype.getLensFlareSystemByID = function (id) {
  87643. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  87644. if (this.lensFlareSystems[index].id === id) {
  87645. return this.lensFlareSystems[index];
  87646. }
  87647. }
  87648. return null;
  87649. };
  87650. BABYLON.AbstractScene.prototype.removeLensFlareSystem = function (toRemove) {
  87651. var index = this.lensFlareSystems.indexOf(toRemove);
  87652. if (index !== -1) {
  87653. this.lensFlareSystems.splice(index, 1);
  87654. }
  87655. return index;
  87656. };
  87657. BABYLON.AbstractScene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  87658. this.lensFlareSystems.push(newLensFlareSystem);
  87659. };
  87660. /**
  87661. * Defines the lens flare scene component responsible to manage any lens flares
  87662. * in a given scene.
  87663. */
  87664. var LensFlareSystemSceneComponent = /** @class */ (function () {
  87665. /**
  87666. * Creates a new instance of the component for the given scene
  87667. * @param scene Defines the scene to register the component in
  87668. */
  87669. function LensFlareSystemSceneComponent(scene) {
  87670. /**
  87671. * The component name helpfull to identify the component in the list of scene components.
  87672. */
  87673. this.name = BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM;
  87674. this.scene = scene;
  87675. scene.lensFlareSystems = new Array();
  87676. }
  87677. /**
  87678. * Registers the component in a given scene
  87679. */
  87680. LensFlareSystemSceneComponent.prototype.register = function () {
  87681. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM, this, this._draw);
  87682. };
  87683. /**
  87684. * Rebuilds the elements related to this component in case of
  87685. * context lost for instance.
  87686. */
  87687. LensFlareSystemSceneComponent.prototype.rebuild = function () {
  87688. // Nothing to do for lens flare
  87689. };
  87690. /**
  87691. * Adds all the element from the container to the scene
  87692. * @param container the container holding the elements
  87693. */
  87694. LensFlareSystemSceneComponent.prototype.addFromContainer = function (container) {
  87695. var _this = this;
  87696. if (!container.lensFlareSystems) {
  87697. return;
  87698. }
  87699. container.lensFlareSystems.forEach(function (o) {
  87700. _this.scene.addLensFlareSystem(o);
  87701. });
  87702. };
  87703. /**
  87704. * Removes all the elements in the container from the scene
  87705. * @param container contains the elements to remove
  87706. */
  87707. LensFlareSystemSceneComponent.prototype.removeFromContainer = function (container) {
  87708. var _this = this;
  87709. if (!container.lensFlareSystems) {
  87710. return;
  87711. }
  87712. container.lensFlareSystems.forEach(function (o) {
  87713. _this.scene.removeLensFlareSystem(o);
  87714. });
  87715. };
  87716. /**
  87717. * Serializes the component data to the specified json object
  87718. * @param serializationObject The object to serialize to
  87719. */
  87720. LensFlareSystemSceneComponent.prototype.serialize = function (serializationObject) {
  87721. // Lens flares
  87722. serializationObject.lensFlareSystems = [];
  87723. var lensFlareSystems = this.scene.lensFlareSystems;
  87724. for (var _i = 0, lensFlareSystems_1 = lensFlareSystems; _i < lensFlareSystems_1.length; _i++) {
  87725. var lensFlareSystem = lensFlareSystems_1[_i];
  87726. serializationObject.lensFlareSystems.push(lensFlareSystem.serialize());
  87727. }
  87728. };
  87729. /**
  87730. * Disposes the component and the associated ressources.
  87731. */
  87732. LensFlareSystemSceneComponent.prototype.dispose = function () {
  87733. var lensFlareSystems = this.scene.lensFlareSystems;
  87734. while (lensFlareSystems.length) {
  87735. lensFlareSystems[0].dispose();
  87736. }
  87737. };
  87738. LensFlareSystemSceneComponent.prototype._draw = function (camera) {
  87739. // Lens flares
  87740. if (this.scene.lensFlaresEnabled) {
  87741. var lensFlareSystems = this.scene.lensFlareSystems;
  87742. BABYLON.Tools.StartPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  87743. for (var _i = 0, lensFlareSystems_2 = lensFlareSystems; _i < lensFlareSystems_2.length; _i++) {
  87744. var lensFlareSystem = lensFlareSystems_2[_i];
  87745. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  87746. lensFlareSystem.render();
  87747. }
  87748. }
  87749. BABYLON.Tools.EndPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  87750. }
  87751. };
  87752. return LensFlareSystemSceneComponent;
  87753. }());
  87754. BABYLON.LensFlareSystemSceneComponent = LensFlareSystemSceneComponent;
  87755. })(BABYLON || (BABYLON = {}));
  87756. //# sourceMappingURL=babylon.lensFlareSystemSceneComponent.js.map
  87757. var BABYLON;
  87758. (function (BABYLON) {
  87759. var LensFlareSystem = /** @class */ (function () {
  87760. function LensFlareSystem(name, emitter, scene) {
  87761. this.name = name;
  87762. this.lensFlares = new Array();
  87763. this.borderLimit = 300;
  87764. this.viewportBorder = 0;
  87765. this.layerMask = 0x0FFFFFFF;
  87766. this._vertexBuffers = {};
  87767. this._isEnabled = true;
  87768. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  87769. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM);
  87770. if (!component) {
  87771. component = new BABYLON.LensFlareSystemSceneComponent(this._scene);
  87772. scene._addComponent(component);
  87773. }
  87774. this._emitter = emitter;
  87775. this.id = name;
  87776. scene.lensFlareSystems.push(this);
  87777. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  87778. var engine = scene.getEngine();
  87779. // VBO
  87780. var vertices = [];
  87781. vertices.push(1, 1);
  87782. vertices.push(-1, 1);
  87783. vertices.push(-1, -1);
  87784. vertices.push(1, -1);
  87785. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  87786. // Indices
  87787. var indices = [];
  87788. indices.push(0);
  87789. indices.push(1);
  87790. indices.push(2);
  87791. indices.push(0);
  87792. indices.push(2);
  87793. indices.push(3);
  87794. this._indexBuffer = engine.createIndexBuffer(indices);
  87795. // Effects
  87796. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  87797. }
  87798. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  87799. get: function () {
  87800. return this._isEnabled;
  87801. },
  87802. set: function (value) {
  87803. this._isEnabled = value;
  87804. },
  87805. enumerable: true,
  87806. configurable: true
  87807. });
  87808. LensFlareSystem.prototype.getScene = function () {
  87809. return this._scene;
  87810. };
  87811. LensFlareSystem.prototype.getEmitter = function () {
  87812. return this._emitter;
  87813. };
  87814. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  87815. this._emitter = newEmitter;
  87816. };
  87817. LensFlareSystem.prototype.getEmitterPosition = function () {
  87818. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  87819. };
  87820. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  87821. var position = this.getEmitterPosition();
  87822. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  87823. this._positionX = position.x;
  87824. this._positionY = position.y;
  87825. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  87826. if (this.viewportBorder > 0) {
  87827. globalViewport.x -= this.viewportBorder;
  87828. globalViewport.y -= this.viewportBorder;
  87829. globalViewport.width += this.viewportBorder * 2;
  87830. globalViewport.height += this.viewportBorder * 2;
  87831. position.x += this.viewportBorder;
  87832. position.y += this.viewportBorder;
  87833. this._positionX += this.viewportBorder;
  87834. this._positionY += this.viewportBorder;
  87835. }
  87836. if (position.z > 0) {
  87837. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  87838. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  87839. return true;
  87840. }
  87841. return true;
  87842. }
  87843. return false;
  87844. };
  87845. /** @hidden */
  87846. LensFlareSystem.prototype._isVisible = function () {
  87847. if (!this._isEnabled || !this._scene.activeCamera) {
  87848. return false;
  87849. }
  87850. var emitterPosition = this.getEmitterPosition();
  87851. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  87852. var distance = direction.length();
  87853. direction.normalize();
  87854. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  87855. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  87856. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  87857. };
  87858. LensFlareSystem.prototype.render = function () {
  87859. if (!this._effect.isReady() || !this._scene.activeCamera)
  87860. return false;
  87861. var engine = this._scene.getEngine();
  87862. var viewport = this._scene.activeCamera.viewport;
  87863. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  87864. // Position
  87865. if (!this.computeEffectivePosition(globalViewport)) {
  87866. return false;
  87867. }
  87868. // Visibility
  87869. if (!this._isVisible()) {
  87870. return false;
  87871. }
  87872. // Intensity
  87873. var awayX;
  87874. var awayY;
  87875. if (this._positionX < this.borderLimit + globalViewport.x) {
  87876. awayX = this.borderLimit + globalViewport.x - this._positionX;
  87877. }
  87878. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  87879. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  87880. }
  87881. else {
  87882. awayX = 0;
  87883. }
  87884. if (this._positionY < this.borderLimit + globalViewport.y) {
  87885. awayY = this.borderLimit + globalViewport.y - this._positionY;
  87886. }
  87887. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  87888. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  87889. }
  87890. else {
  87891. awayY = 0;
  87892. }
  87893. var away = (awayX > awayY) ? awayX : awayY;
  87894. away -= this.viewportBorder;
  87895. if (away > this.borderLimit) {
  87896. away = this.borderLimit;
  87897. }
  87898. var intensity = 1.0 - (away / this.borderLimit);
  87899. if (intensity < 0) {
  87900. return false;
  87901. }
  87902. if (intensity > 1.0) {
  87903. intensity = 1.0;
  87904. }
  87905. if (this.viewportBorder > 0) {
  87906. globalViewport.x += this.viewportBorder;
  87907. globalViewport.y += this.viewportBorder;
  87908. globalViewport.width -= this.viewportBorder * 2;
  87909. globalViewport.height -= this.viewportBorder * 2;
  87910. this._positionX -= this.viewportBorder;
  87911. this._positionY -= this.viewportBorder;
  87912. }
  87913. // Position
  87914. var centerX = globalViewport.x + globalViewport.width / 2;
  87915. var centerY = globalViewport.y + globalViewport.height / 2;
  87916. var distX = centerX - this._positionX;
  87917. var distY = centerY - this._positionY;
  87918. // Effects
  87919. engine.enableEffect(this._effect);
  87920. engine.setState(false);
  87921. engine.setDepthBuffer(false);
  87922. // VBOs
  87923. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  87924. // Flares
  87925. for (var index = 0; index < this.lensFlares.length; index++) {
  87926. var flare = this.lensFlares[index];
  87927. engine.setAlphaMode(flare.alphaMode);
  87928. var x = centerX - (distX * flare.position);
  87929. var y = centerY - (distY * flare.position);
  87930. var cw = flare.size;
  87931. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  87932. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  87933. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  87934. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  87935. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  87936. // Texture
  87937. this._effect.setTexture("textureSampler", flare.texture);
  87938. // Color
  87939. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  87940. // Draw order
  87941. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  87942. }
  87943. engine.setDepthBuffer(true);
  87944. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  87945. return true;
  87946. };
  87947. LensFlareSystem.prototype.dispose = function () {
  87948. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  87949. if (vertexBuffer) {
  87950. vertexBuffer.dispose();
  87951. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  87952. }
  87953. if (this._indexBuffer) {
  87954. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  87955. this._indexBuffer = null;
  87956. }
  87957. while (this.lensFlares.length) {
  87958. this.lensFlares[0].dispose();
  87959. }
  87960. // Remove from scene
  87961. var index = this._scene.lensFlareSystems.indexOf(this);
  87962. this._scene.lensFlareSystems.splice(index, 1);
  87963. };
  87964. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  87965. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  87966. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  87967. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  87968. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  87969. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  87970. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  87971. var parsedFlare = parsedLensFlareSystem.flares[index];
  87972. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  87973. }
  87974. return lensFlareSystem;
  87975. };
  87976. LensFlareSystem.prototype.serialize = function () {
  87977. var serializationObject = {};
  87978. serializationObject.id = this.id;
  87979. serializationObject.name = this.name;
  87980. serializationObject.emitterId = this.getEmitter().id;
  87981. serializationObject.borderLimit = this.borderLimit;
  87982. serializationObject.flares = [];
  87983. for (var index = 0; index < this.lensFlares.length; index++) {
  87984. var flare = this.lensFlares[index];
  87985. serializationObject.flares.push({
  87986. size: flare.size,
  87987. position: flare.position,
  87988. color: flare.color.asArray(),
  87989. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  87990. });
  87991. }
  87992. return serializationObject;
  87993. };
  87994. return LensFlareSystem;
  87995. }());
  87996. BABYLON.LensFlareSystem = LensFlareSystem;
  87997. })(BABYLON || (BABYLON = {}));
  87998. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  87999. var BABYLON;
  88000. (function (BABYLON) {
  88001. /**
  88002. * This is a holder class for the physics joint created by the physics plugin.
  88003. * It holds a set of functions to control the underlying joint.
  88004. */
  88005. var PhysicsJoint = /** @class */ (function () {
  88006. function PhysicsJoint(type, jointData) {
  88007. this.type = type;
  88008. this.jointData = jointData;
  88009. jointData.nativeParams = jointData.nativeParams || {};
  88010. }
  88011. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  88012. get: function () {
  88013. return this._physicsJoint;
  88014. },
  88015. set: function (newJoint) {
  88016. if (this._physicsJoint) {
  88017. //remove from the wolrd
  88018. }
  88019. this._physicsJoint = newJoint;
  88020. },
  88021. enumerable: true,
  88022. configurable: true
  88023. });
  88024. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  88025. set: function (physicsPlugin) {
  88026. this._physicsPlugin = physicsPlugin;
  88027. },
  88028. enumerable: true,
  88029. configurable: true
  88030. });
  88031. /**
  88032. * Execute a function that is physics-plugin specific.
  88033. * @param {Function} func the function that will be executed.
  88034. * It accepts two parameters: the physics world and the physics joint.
  88035. */
  88036. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  88037. func(this._physicsPlugin.world, this._physicsJoint);
  88038. };
  88039. //TODO check if the native joints are the same
  88040. //Joint Types
  88041. PhysicsJoint.DistanceJoint = 0;
  88042. PhysicsJoint.HingeJoint = 1;
  88043. PhysicsJoint.BallAndSocketJoint = 2;
  88044. PhysicsJoint.WheelJoint = 3;
  88045. PhysicsJoint.SliderJoint = 4;
  88046. //OIMO
  88047. PhysicsJoint.PrismaticJoint = 5;
  88048. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  88049. PhysicsJoint.UniversalJoint = 6;
  88050. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  88051. //Cannon
  88052. //Similar to a Ball-Joint. Different in params
  88053. PhysicsJoint.PointToPointJoint = 8;
  88054. //Cannon only at the moment
  88055. PhysicsJoint.SpringJoint = 9;
  88056. PhysicsJoint.LockJoint = 10;
  88057. return PhysicsJoint;
  88058. }());
  88059. BABYLON.PhysicsJoint = PhysicsJoint;
  88060. /**
  88061. * A class representing a physics distance joint.
  88062. */
  88063. var DistanceJoint = /** @class */ (function (_super) {
  88064. __extends(DistanceJoint, _super);
  88065. function DistanceJoint(jointData) {
  88066. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  88067. }
  88068. /**
  88069. * Update the predefined distance.
  88070. */
  88071. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  88072. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  88073. };
  88074. return DistanceJoint;
  88075. }(PhysicsJoint));
  88076. BABYLON.DistanceJoint = DistanceJoint;
  88077. var MotorEnabledJoint = /** @class */ (function (_super) {
  88078. __extends(MotorEnabledJoint, _super);
  88079. function MotorEnabledJoint(type, jointData) {
  88080. return _super.call(this, type, jointData) || this;
  88081. }
  88082. /**
  88083. * Set the motor values.
  88084. * Attention, this function is plugin specific. Engines won't react 100% the same.
  88085. * @param {number} force the force to apply
  88086. * @param {number} maxForce max force for this motor.
  88087. */
  88088. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  88089. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  88090. };
  88091. /**
  88092. * Set the motor's limits.
  88093. * Attention, this function is plugin specific. Engines won't react 100% the same.
  88094. */
  88095. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  88096. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  88097. };
  88098. return MotorEnabledJoint;
  88099. }(PhysicsJoint));
  88100. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  88101. /**
  88102. * This class represents a single hinge physics joint
  88103. */
  88104. var HingeJoint = /** @class */ (function (_super) {
  88105. __extends(HingeJoint, _super);
  88106. function HingeJoint(jointData) {
  88107. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  88108. }
  88109. /**
  88110. * Set the motor values.
  88111. * Attention, this function is plugin specific. Engines won't react 100% the same.
  88112. * @param {number} force the force to apply
  88113. * @param {number} maxForce max force for this motor.
  88114. */
  88115. HingeJoint.prototype.setMotor = function (force, maxForce) {
  88116. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  88117. };
  88118. /**
  88119. * Set the motor's limits.
  88120. * Attention, this function is plugin specific. Engines won't react 100% the same.
  88121. */
  88122. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  88123. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  88124. };
  88125. return HingeJoint;
  88126. }(MotorEnabledJoint));
  88127. BABYLON.HingeJoint = HingeJoint;
  88128. /**
  88129. * This class represents a dual hinge physics joint (same as wheel joint)
  88130. */
  88131. var Hinge2Joint = /** @class */ (function (_super) {
  88132. __extends(Hinge2Joint, _super);
  88133. function Hinge2Joint(jointData) {
  88134. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  88135. }
  88136. /**
  88137. * Set the motor values.
  88138. * Attention, this function is plugin specific. Engines won't react 100% the same.
  88139. * @param {number} force the force to apply
  88140. * @param {number} maxForce max force for this motor.
  88141. * @param {motorIndex} the motor's index, 0 or 1.
  88142. */
  88143. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  88144. if (motorIndex === void 0) { motorIndex = 0; }
  88145. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  88146. };
  88147. /**
  88148. * Set the motor limits.
  88149. * Attention, this function is plugin specific. Engines won't react 100% the same.
  88150. * @param {number} upperLimit the upper limit
  88151. * @param {number} lowerLimit lower limit
  88152. * @param {motorIndex} the motor's index, 0 or 1.
  88153. */
  88154. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  88155. if (motorIndex === void 0) { motorIndex = 0; }
  88156. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  88157. };
  88158. return Hinge2Joint;
  88159. }(MotorEnabledJoint));
  88160. BABYLON.Hinge2Joint = Hinge2Joint;
  88161. })(BABYLON || (BABYLON = {}));
  88162. //# sourceMappingURL=babylon.physicsJoint.js.map
  88163. var BABYLON;
  88164. (function (BABYLON) {
  88165. var PhysicsImpostor = /** @class */ (function () {
  88166. function PhysicsImpostor(object, type, _options, _scene) {
  88167. if (_options === void 0) { _options = { mass: 0 }; }
  88168. var _this = this;
  88169. this.object = object;
  88170. this.type = type;
  88171. this._options = _options;
  88172. this._scene = _scene;
  88173. this._bodyUpdateRequired = false;
  88174. this._onBeforePhysicsStepCallbacks = new Array();
  88175. this._onAfterPhysicsStepCallbacks = new Array();
  88176. this._onPhysicsCollideCallbacks = [];
  88177. this._deltaPosition = BABYLON.Vector3.Zero();
  88178. this._isDisposed = false;
  88179. //temp variables for parent rotation calculations
  88180. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  88181. this._tmpQuat = new BABYLON.Quaternion();
  88182. this._tmpQuat2 = new BABYLON.Quaternion();
  88183. /**
  88184. * this function is executed by the physics engine.
  88185. */
  88186. this.beforeStep = function () {
  88187. if (!_this._physicsEngine) {
  88188. return;
  88189. }
  88190. _this.object.translate(_this._deltaPosition, -1);
  88191. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  88192. _this.object.computeWorldMatrix(false);
  88193. if (_this.object.parent && _this.object.rotationQuaternion) {
  88194. _this.getParentsRotation();
  88195. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  88196. }
  88197. else {
  88198. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  88199. }
  88200. if (!_this._options.disableBidirectionalTransformation) {
  88201. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  88202. }
  88203. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  88204. func(_this);
  88205. });
  88206. };
  88207. /**
  88208. * this function is executed by the physics engine.
  88209. */
  88210. this.afterStep = function () {
  88211. if (!_this._physicsEngine) {
  88212. return;
  88213. }
  88214. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  88215. func(_this);
  88216. });
  88217. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  88218. // object has now its world rotation. needs to be converted to local.
  88219. if (_this.object.parent && _this.object.rotationQuaternion) {
  88220. _this.getParentsRotation();
  88221. _this._tmpQuat.conjugateInPlace();
  88222. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  88223. }
  88224. // take the position set and make it the absolute position of this object.
  88225. _this.object.setAbsolutePosition(_this.object.position);
  88226. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  88227. _this.object.translate(_this._deltaPosition, 1);
  88228. };
  88229. /**
  88230. * Legacy collision detection event support
  88231. */
  88232. this.onCollideEvent = null;
  88233. //event and body object due to cannon's event-based architecture.
  88234. this.onCollide = function (e) {
  88235. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  88236. return;
  88237. }
  88238. if (!_this._physicsEngine) {
  88239. return;
  88240. }
  88241. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  88242. if (otherImpostor) {
  88243. // Legacy collision detection event support
  88244. if (_this.onCollideEvent) {
  88245. _this.onCollideEvent(_this, otherImpostor);
  88246. }
  88247. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  88248. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  88249. }).forEach(function (obj) {
  88250. obj.callback(_this, otherImpostor);
  88251. });
  88252. }
  88253. };
  88254. //sanity check!
  88255. if (!this.object) {
  88256. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  88257. return;
  88258. }
  88259. //legacy support for old syntax.
  88260. if (!this._scene && object.getScene) {
  88261. this._scene = object.getScene();
  88262. }
  88263. if (!this._scene) {
  88264. return;
  88265. }
  88266. this._physicsEngine = this._scene.getPhysicsEngine();
  88267. if (!this._physicsEngine) {
  88268. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  88269. }
  88270. else {
  88271. //set the object's quaternion, if not set
  88272. if (!this.object.rotationQuaternion) {
  88273. if (this.object.rotation) {
  88274. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  88275. }
  88276. else {
  88277. this.object.rotationQuaternion = new BABYLON.Quaternion();
  88278. }
  88279. }
  88280. //default options params
  88281. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  88282. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  88283. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  88284. this._joints = [];
  88285. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  88286. if (!this.object.parent || this._options.ignoreParent) {
  88287. this._init();
  88288. }
  88289. else if (this.object.parent.physicsImpostor) {
  88290. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  88291. }
  88292. }
  88293. }
  88294. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  88295. get: function () {
  88296. return this._isDisposed;
  88297. },
  88298. enumerable: true,
  88299. configurable: true
  88300. });
  88301. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  88302. get: function () {
  88303. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  88304. },
  88305. set: function (value) {
  88306. this.setMass(value);
  88307. },
  88308. enumerable: true,
  88309. configurable: true
  88310. });
  88311. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  88312. get: function () {
  88313. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  88314. },
  88315. set: function (value) {
  88316. if (!this._physicsEngine) {
  88317. return;
  88318. }
  88319. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  88320. },
  88321. enumerable: true,
  88322. configurable: true
  88323. });
  88324. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  88325. get: function () {
  88326. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  88327. },
  88328. set: function (value) {
  88329. if (!this._physicsEngine) {
  88330. return;
  88331. }
  88332. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  88333. },
  88334. enumerable: true,
  88335. configurable: true
  88336. });
  88337. /**
  88338. * This function will completly initialize this impostor.
  88339. * It will create a new body - but only if this mesh has no parent.
  88340. * If it has, this impostor will not be used other than to define the impostor
  88341. * of the child mesh.
  88342. * @hidden
  88343. */
  88344. PhysicsImpostor.prototype._init = function () {
  88345. if (!this._physicsEngine) {
  88346. return;
  88347. }
  88348. this._physicsEngine.removeImpostor(this);
  88349. this.physicsBody = null;
  88350. this._parent = this._parent || this._getPhysicsParent();
  88351. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  88352. this._physicsEngine.addImpostor(this);
  88353. }
  88354. };
  88355. PhysicsImpostor.prototype._getPhysicsParent = function () {
  88356. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  88357. var parentMesh = this.object.parent;
  88358. return parentMesh.physicsImpostor;
  88359. }
  88360. return null;
  88361. };
  88362. /**
  88363. * Should a new body be generated.
  88364. */
  88365. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  88366. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  88367. };
  88368. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  88369. this.forceUpdate();
  88370. };
  88371. /**
  88372. * Force a regeneration of this or the parent's impostor's body.
  88373. * Use under cautious - This will remove all joints already implemented.
  88374. */
  88375. PhysicsImpostor.prototype.forceUpdate = function () {
  88376. this._init();
  88377. if (this.parent && !this._options.ignoreParent) {
  88378. this.parent.forceUpdate();
  88379. }
  88380. };
  88381. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  88382. /*public get mesh(): AbstractMesh {
  88383. return this._mesh;
  88384. }*/
  88385. /**
  88386. * Gets the body that holds this impostor. Either its own, or its parent.
  88387. */
  88388. get: function () {
  88389. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  88390. },
  88391. /**
  88392. * Set the physics body. Used mainly by the physics engine/plugin
  88393. */
  88394. set: function (physicsBody) {
  88395. if (this._physicsBody && this._physicsEngine) {
  88396. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  88397. }
  88398. this._physicsBody = physicsBody;
  88399. this.resetUpdateFlags();
  88400. },
  88401. enumerable: true,
  88402. configurable: true
  88403. });
  88404. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  88405. get: function () {
  88406. return !this._options.ignoreParent && this._parent ? this._parent : null;
  88407. },
  88408. set: function (value) {
  88409. this._parent = value;
  88410. },
  88411. enumerable: true,
  88412. configurable: true
  88413. });
  88414. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  88415. this._bodyUpdateRequired = false;
  88416. };
  88417. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  88418. if (this.object.getBoundingInfo) {
  88419. var q = this.object.rotationQuaternion;
  88420. //reset rotation
  88421. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  88422. //calculate the world matrix with no rotation
  88423. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  88424. var boundingInfo = this.object.getBoundingInfo();
  88425. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  88426. //bring back the rotation
  88427. this.object.rotationQuaternion = q;
  88428. //calculate the world matrix with the new rotation
  88429. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  88430. return size;
  88431. }
  88432. else {
  88433. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  88434. }
  88435. };
  88436. PhysicsImpostor.prototype.getObjectCenter = function () {
  88437. if (this.object.getBoundingInfo) {
  88438. var boundingInfo = this.object.getBoundingInfo();
  88439. return boundingInfo.boundingBox.centerWorld;
  88440. }
  88441. else {
  88442. return this.object.position;
  88443. }
  88444. };
  88445. /**
  88446. * Get a specific parametes from the options parameter.
  88447. */
  88448. PhysicsImpostor.prototype.getParam = function (paramName) {
  88449. return this._options[paramName];
  88450. };
  88451. /**
  88452. * Sets a specific parameter in the options given to the physics plugin
  88453. */
  88454. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  88455. this._options[paramName] = value;
  88456. this._bodyUpdateRequired = true;
  88457. };
  88458. /**
  88459. * Specifically change the body's mass option. Won't recreate the physics body object
  88460. */
  88461. PhysicsImpostor.prototype.setMass = function (mass) {
  88462. if (this.getParam("mass") !== mass) {
  88463. this.setParam("mass", mass);
  88464. }
  88465. if (this._physicsEngine) {
  88466. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  88467. }
  88468. };
  88469. PhysicsImpostor.prototype.getLinearVelocity = function () {
  88470. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  88471. };
  88472. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  88473. if (this._physicsEngine) {
  88474. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  88475. }
  88476. };
  88477. PhysicsImpostor.prototype.getAngularVelocity = function () {
  88478. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  88479. };
  88480. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  88481. if (this._physicsEngine) {
  88482. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  88483. }
  88484. };
  88485. /**
  88486. * Execute a function with the physics plugin native code.
  88487. * Provide a function the will have two variables - the world object and the physics body object.
  88488. */
  88489. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  88490. if (this._physicsEngine) {
  88491. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  88492. }
  88493. };
  88494. /**
  88495. * Register a function that will be executed before the physics world is stepping forward.
  88496. */
  88497. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  88498. this._onBeforePhysicsStepCallbacks.push(func);
  88499. };
  88500. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  88501. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  88502. if (index > -1) {
  88503. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  88504. }
  88505. else {
  88506. BABYLON.Tools.Warn("Function to remove was not found");
  88507. }
  88508. };
  88509. /**
  88510. * Register a function that will be executed after the physics step
  88511. */
  88512. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  88513. this._onAfterPhysicsStepCallbacks.push(func);
  88514. };
  88515. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  88516. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  88517. if (index > -1) {
  88518. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  88519. }
  88520. else {
  88521. BABYLON.Tools.Warn("Function to remove was not found");
  88522. }
  88523. };
  88524. /**
  88525. * register a function that will be executed when this impostor collides against a different body.
  88526. */
  88527. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  88528. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  88529. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  88530. };
  88531. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  88532. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  88533. var index = -1;
  88534. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  88535. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  88536. // chcek the arrays match
  88537. var sameList = cbDef.otherImpostors.every(function (impostor) {
  88538. return collidedAgainstList.indexOf(impostor) > -1;
  88539. });
  88540. if (sameList) {
  88541. index = idx;
  88542. }
  88543. return sameList;
  88544. }
  88545. return false;
  88546. });
  88547. if (found) {
  88548. this._onPhysicsCollideCallbacks.splice(index, 1);
  88549. }
  88550. else {
  88551. BABYLON.Tools.Warn("Function to remove was not found");
  88552. }
  88553. };
  88554. PhysicsImpostor.prototype.getParentsRotation = function () {
  88555. var parent = this.object.parent;
  88556. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  88557. while (parent) {
  88558. if (parent.rotationQuaternion) {
  88559. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  88560. }
  88561. else {
  88562. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  88563. }
  88564. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  88565. parent = parent.parent;
  88566. }
  88567. return this._tmpQuat;
  88568. };
  88569. /**
  88570. * Apply a force
  88571. */
  88572. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  88573. if (this._physicsEngine) {
  88574. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  88575. }
  88576. return this;
  88577. };
  88578. /**
  88579. * Apply an impulse
  88580. */
  88581. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  88582. if (this._physicsEngine) {
  88583. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  88584. }
  88585. return this;
  88586. };
  88587. /**
  88588. * A help function to create a joint.
  88589. */
  88590. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  88591. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  88592. this.addJoint(otherImpostor, joint);
  88593. return this;
  88594. };
  88595. /**
  88596. * Add a joint to this impostor with a different impostor.
  88597. */
  88598. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  88599. this._joints.push({
  88600. otherImpostor: otherImpostor,
  88601. joint: joint
  88602. });
  88603. if (this._physicsEngine) {
  88604. this._physicsEngine.addJoint(this, otherImpostor, joint);
  88605. }
  88606. return this;
  88607. };
  88608. /**
  88609. * Will keep this body still, in a sleep mode.
  88610. */
  88611. PhysicsImpostor.prototype.sleep = function () {
  88612. if (this._physicsEngine) {
  88613. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  88614. }
  88615. return this;
  88616. };
  88617. /**
  88618. * Wake the body up.
  88619. */
  88620. PhysicsImpostor.prototype.wakeUp = function () {
  88621. if (this._physicsEngine) {
  88622. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  88623. }
  88624. return this;
  88625. };
  88626. PhysicsImpostor.prototype.clone = function (newObject) {
  88627. if (!newObject)
  88628. return null;
  88629. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  88630. };
  88631. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  88632. var _this = this;
  88633. //no dispose if no physics engine is available.
  88634. if (!this._physicsEngine) {
  88635. return;
  88636. }
  88637. this._joints.forEach(function (j) {
  88638. if (_this._physicsEngine) {
  88639. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  88640. }
  88641. });
  88642. //dispose the physics body
  88643. this._physicsEngine.removeImpostor(this);
  88644. if (this.parent) {
  88645. this.parent.forceUpdate();
  88646. }
  88647. else {
  88648. /*this._object.getChildMeshes().forEach(function(mesh) {
  88649. if (mesh.physicsImpostor) {
  88650. if (disposeChildren) {
  88651. mesh.physicsImpostor.dispose();
  88652. mesh.physicsImpostor = null;
  88653. }
  88654. }
  88655. })*/
  88656. }
  88657. this._isDisposed = true;
  88658. };
  88659. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  88660. this._deltaPosition.copyFrom(position);
  88661. };
  88662. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  88663. if (!this._deltaRotation) {
  88664. this._deltaRotation = new BABYLON.Quaternion();
  88665. }
  88666. this._deltaRotation.copyFrom(rotation);
  88667. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  88668. };
  88669. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  88670. if (this._physicsEngine) {
  88671. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  88672. }
  88673. return this;
  88674. };
  88675. PhysicsImpostor.prototype.getRadius = function () {
  88676. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  88677. };
  88678. /**
  88679. * Sync a bone with this impostor
  88680. * @param bone The bone to sync to the impostor.
  88681. * @param boneMesh The mesh that the bone is influencing.
  88682. * @param jointPivot The pivot of the joint / bone in local space.
  88683. * @param distToJoint Optional distance from the impostor to the joint.
  88684. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  88685. */
  88686. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  88687. var tempVec = PhysicsImpostor._tmpVecs[0];
  88688. var mesh = this.object;
  88689. if (mesh.rotationQuaternion) {
  88690. if (adjustRotation) {
  88691. var tempQuat = PhysicsImpostor._tmpQuat;
  88692. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  88693. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  88694. }
  88695. else {
  88696. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  88697. }
  88698. }
  88699. tempVec.x = 0;
  88700. tempVec.y = 0;
  88701. tempVec.z = 0;
  88702. if (jointPivot) {
  88703. tempVec.x = jointPivot.x;
  88704. tempVec.y = jointPivot.y;
  88705. tempVec.z = jointPivot.z;
  88706. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  88707. if (distToJoint === undefined || distToJoint === null) {
  88708. distToJoint = jointPivot.length();
  88709. }
  88710. tempVec.x *= distToJoint;
  88711. tempVec.y *= distToJoint;
  88712. tempVec.z *= distToJoint;
  88713. }
  88714. if (bone.getParent()) {
  88715. tempVec.addInPlace(mesh.getAbsolutePosition());
  88716. bone.setAbsolutePosition(tempVec, boneMesh);
  88717. }
  88718. else {
  88719. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  88720. boneMesh.position.x -= tempVec.x;
  88721. boneMesh.position.y -= tempVec.y;
  88722. boneMesh.position.z -= tempVec.z;
  88723. }
  88724. };
  88725. /**
  88726. * Sync impostor to a bone
  88727. * @param bone The bone that the impostor will be synced to.
  88728. * @param boneMesh The mesh that the bone is influencing.
  88729. * @param jointPivot The pivot of the joint / bone in local space.
  88730. * @param distToJoint Optional distance from the impostor to the joint.
  88731. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  88732. * @param boneAxis Optional vector3 axis the bone is aligned with
  88733. */
  88734. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  88735. var mesh = this.object;
  88736. if (mesh.rotationQuaternion) {
  88737. if (adjustRotation) {
  88738. var tempQuat = PhysicsImpostor._tmpQuat;
  88739. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  88740. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  88741. }
  88742. else {
  88743. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  88744. }
  88745. }
  88746. var pos = PhysicsImpostor._tmpVecs[0];
  88747. var boneDir = PhysicsImpostor._tmpVecs[1];
  88748. if (!boneAxis) {
  88749. boneAxis = PhysicsImpostor._tmpVecs[2];
  88750. boneAxis.x = 0;
  88751. boneAxis.y = 1;
  88752. boneAxis.z = 0;
  88753. }
  88754. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  88755. bone.getAbsolutePositionToRef(boneMesh, pos);
  88756. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  88757. distToJoint = jointPivot.length();
  88758. }
  88759. if (distToJoint !== undefined && distToJoint !== null) {
  88760. pos.x += boneDir.x * distToJoint;
  88761. pos.y += boneDir.y * distToJoint;
  88762. pos.z += boneDir.z * distToJoint;
  88763. }
  88764. mesh.setAbsolutePosition(pos);
  88765. };
  88766. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  88767. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  88768. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  88769. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  88770. //Impostor types
  88771. PhysicsImpostor.NoImpostor = 0;
  88772. PhysicsImpostor.SphereImpostor = 1;
  88773. PhysicsImpostor.BoxImpostor = 2;
  88774. PhysicsImpostor.PlaneImpostor = 3;
  88775. PhysicsImpostor.MeshImpostor = 4;
  88776. PhysicsImpostor.CylinderImpostor = 7;
  88777. PhysicsImpostor.ParticleImpostor = 8;
  88778. PhysicsImpostor.HeightmapImpostor = 9;
  88779. return PhysicsImpostor;
  88780. }());
  88781. BABYLON.PhysicsImpostor = PhysicsImpostor;
  88782. })(BABYLON || (BABYLON = {}));
  88783. //# sourceMappingURL=babylon.physicsImpostor.js.map
  88784. var BABYLON;
  88785. (function (BABYLON) {
  88786. var PhysicsEngine = /** @class */ (function () {
  88787. function PhysicsEngine(gravity, _physicsPlugin) {
  88788. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  88789. this._physicsPlugin = _physicsPlugin;
  88790. //new methods and parameters
  88791. this._impostors = [];
  88792. this._joints = [];
  88793. if (!this._physicsPlugin.isSupported()) {
  88794. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  88795. + "Please make sure it is included.");
  88796. }
  88797. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  88798. this.setGravity(gravity);
  88799. this.setTimeStep();
  88800. }
  88801. PhysicsEngine.prototype.setGravity = function (gravity) {
  88802. this.gravity = gravity;
  88803. this._physicsPlugin.setGravity(this.gravity);
  88804. };
  88805. /**
  88806. * Set the time step of the physics engine.
  88807. * default is 1/60.
  88808. * To slow it down, enter 1/600 for example.
  88809. * To speed it up, 1/30
  88810. * @param {number} newTimeStep the new timestep to apply to this world.
  88811. */
  88812. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  88813. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  88814. this._physicsPlugin.setTimeStep(newTimeStep);
  88815. };
  88816. /**
  88817. * Get the time step of the physics engine.
  88818. */
  88819. PhysicsEngine.prototype.getTimeStep = function () {
  88820. return this._physicsPlugin.getTimeStep();
  88821. };
  88822. PhysicsEngine.prototype.dispose = function () {
  88823. this._impostors.forEach(function (impostor) {
  88824. impostor.dispose();
  88825. });
  88826. this._physicsPlugin.dispose();
  88827. };
  88828. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  88829. return this._physicsPlugin.name;
  88830. };
  88831. /**
  88832. * Adding a new impostor for the impostor tracking.
  88833. * This will be done by the impostor itself.
  88834. * @param {PhysicsImpostor} impostor the impostor to add
  88835. */
  88836. PhysicsEngine.prototype.addImpostor = function (impostor) {
  88837. impostor.uniqueId = this._impostors.push(impostor);
  88838. //if no parent, generate the body
  88839. if (!impostor.parent) {
  88840. this._physicsPlugin.generatePhysicsBody(impostor);
  88841. }
  88842. };
  88843. /**
  88844. * Remove an impostor from the engine.
  88845. * This impostor and its mesh will not longer be updated by the physics engine.
  88846. * @param {PhysicsImpostor} impostor the impostor to remove
  88847. */
  88848. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  88849. var index = this._impostors.indexOf(impostor);
  88850. if (index > -1) {
  88851. var removed = this._impostors.splice(index, 1);
  88852. //Is it needed?
  88853. if (removed.length) {
  88854. //this will also remove it from the world.
  88855. removed[0].physicsBody = null;
  88856. }
  88857. }
  88858. };
  88859. /**
  88860. * Add a joint to the physics engine
  88861. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  88862. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  88863. * @param {PhysicsJoint} the joint that will connect both impostors.
  88864. */
  88865. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  88866. var impostorJoint = {
  88867. mainImpostor: mainImpostor,
  88868. connectedImpostor: connectedImpostor,
  88869. joint: joint
  88870. };
  88871. joint.physicsPlugin = this._physicsPlugin;
  88872. this._joints.push(impostorJoint);
  88873. this._physicsPlugin.generateJoint(impostorJoint);
  88874. };
  88875. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  88876. var matchingJoints = this._joints.filter(function (impostorJoint) {
  88877. return (impostorJoint.connectedImpostor === connectedImpostor
  88878. && impostorJoint.joint === joint
  88879. && impostorJoint.mainImpostor === mainImpostor);
  88880. });
  88881. if (matchingJoints.length) {
  88882. this._physicsPlugin.removeJoint(matchingJoints[0]);
  88883. //TODO remove it from the list as well
  88884. }
  88885. };
  88886. /**
  88887. * Called by the scene. no need to call it.
  88888. * @hidden
  88889. */
  88890. PhysicsEngine.prototype._step = function (delta) {
  88891. var _this = this;
  88892. //check if any mesh has no body / requires an update
  88893. this._impostors.forEach(function (impostor) {
  88894. if (impostor.isBodyInitRequired()) {
  88895. _this._physicsPlugin.generatePhysicsBody(impostor);
  88896. }
  88897. });
  88898. if (delta > 0.1) {
  88899. delta = 0.1;
  88900. }
  88901. else if (delta <= 0) {
  88902. delta = 1.0 / 60.0;
  88903. }
  88904. this._physicsPlugin.executeStep(delta, this._impostors);
  88905. };
  88906. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  88907. return this._physicsPlugin;
  88908. };
  88909. PhysicsEngine.prototype.getImpostors = function () {
  88910. return this._impostors;
  88911. };
  88912. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  88913. for (var i = 0; i < this._impostors.length; ++i) {
  88914. if (this._impostors[i].object === object) {
  88915. return this._impostors[i];
  88916. }
  88917. }
  88918. return null;
  88919. };
  88920. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  88921. for (var i = 0; i < this._impostors.length; ++i) {
  88922. if (this._impostors[i].physicsBody === body) {
  88923. return this._impostors[i];
  88924. }
  88925. }
  88926. return null;
  88927. };
  88928. // Statics
  88929. PhysicsEngine.Epsilon = 0.001;
  88930. return PhysicsEngine;
  88931. }());
  88932. BABYLON.PhysicsEngine = PhysicsEngine;
  88933. })(BABYLON || (BABYLON = {}));
  88934. //# sourceMappingURL=babylon.physicsEngine.js.map
  88935. var BABYLON;
  88936. (function (BABYLON) {
  88937. var PhysicsHelper = /** @class */ (function () {
  88938. function PhysicsHelper(scene) {
  88939. this._scene = scene;
  88940. this._physicsEngine = this._scene.getPhysicsEngine();
  88941. if (!this._physicsEngine) {
  88942. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  88943. }
  88944. }
  88945. /**
  88946. * @param {Vector3} origin the origin of the explosion
  88947. * @param {number} radius the explosion radius
  88948. * @param {number} strength the explosion strength
  88949. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  88950. */
  88951. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  88952. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  88953. if (!this._physicsEngine) {
  88954. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  88955. return null;
  88956. }
  88957. var impostors = this._physicsEngine.getImpostors();
  88958. if (impostors.length === 0) {
  88959. return null;
  88960. }
  88961. var event = new PhysicsRadialExplosionEvent(this._scene);
  88962. impostors.forEach(function (impostor) {
  88963. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  88964. if (!impostorForceAndContactPoint) {
  88965. return;
  88966. }
  88967. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  88968. });
  88969. event.dispose(false);
  88970. return event;
  88971. };
  88972. /**
  88973. * @param {Vector3} origin the origin of the explosion
  88974. * @param {number} radius the explosion radius
  88975. * @param {number} strength the explosion strength
  88976. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  88977. */
  88978. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  88979. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  88980. if (!this._physicsEngine) {
  88981. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  88982. return null;
  88983. }
  88984. var impostors = this._physicsEngine.getImpostors();
  88985. if (impostors.length === 0) {
  88986. return null;
  88987. }
  88988. var event = new PhysicsRadialExplosionEvent(this._scene);
  88989. impostors.forEach(function (impostor) {
  88990. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  88991. if (!impostorForceAndContactPoint) {
  88992. return;
  88993. }
  88994. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  88995. });
  88996. event.dispose(false);
  88997. return event;
  88998. };
  88999. /**
  89000. * @param {Vector3} origin the origin of the explosion
  89001. * @param {number} radius the explosion radius
  89002. * @param {number} strength the explosion strength
  89003. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  89004. */
  89005. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  89006. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  89007. if (!this._physicsEngine) {
  89008. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  89009. return null;
  89010. }
  89011. var impostors = this._physicsEngine.getImpostors();
  89012. if (impostors.length === 0) {
  89013. return null;
  89014. }
  89015. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  89016. event.dispose(false);
  89017. return event;
  89018. };
  89019. /**
  89020. * @param {Vector3} origin the origin of the updraft
  89021. * @param {number} radius the radius of the updraft
  89022. * @param {number} strength the strength of the updraft
  89023. * @param {number} height the height of the updraft
  89024. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  89025. */
  89026. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  89027. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  89028. if (!this._physicsEngine) {
  89029. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  89030. return null;
  89031. }
  89032. if (this._physicsEngine.getImpostors().length === 0) {
  89033. return null;
  89034. }
  89035. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  89036. event.dispose(false);
  89037. return event;
  89038. };
  89039. /**
  89040. * @param {Vector3} origin the of the vortex
  89041. * @param {number} radius the radius of the vortex
  89042. * @param {number} strength the strength of the vortex
  89043. * @param {number} height the height of the vortex
  89044. */
  89045. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  89046. if (!this._physicsEngine) {
  89047. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  89048. return null;
  89049. }
  89050. if (this._physicsEngine.getImpostors().length === 0) {
  89051. return null;
  89052. }
  89053. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  89054. event.dispose(false);
  89055. return event;
  89056. };
  89057. return PhysicsHelper;
  89058. }());
  89059. BABYLON.PhysicsHelper = PhysicsHelper;
  89060. /***** Radial explosion *****/
  89061. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  89062. function PhysicsRadialExplosionEvent(scene) {
  89063. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  89064. this._rays = [];
  89065. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  89066. this._scene = scene;
  89067. }
  89068. /**
  89069. * Returns the data related to the radial explosion event (sphere & rays).
  89070. * @returns {PhysicsRadialExplosionEventData}
  89071. */
  89072. PhysicsRadialExplosionEvent.prototype.getData = function () {
  89073. this._dataFetched = true;
  89074. return {
  89075. sphere: this._sphere,
  89076. rays: this._rays,
  89077. };
  89078. };
  89079. /**
  89080. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  89081. * @param impostor
  89082. * @param {Vector3} origin the origin of the explosion
  89083. * @param {number} radius the explosion radius
  89084. * @param {number} strength the explosion strength
  89085. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  89086. * @returns {Nullable<PhysicsForceAndContactPoint>}
  89087. */
  89088. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  89089. if (impostor.mass === 0) {
  89090. return null;
  89091. }
  89092. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  89093. return null;
  89094. }
  89095. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  89096. return null;
  89097. }
  89098. var impostorObjectCenter = impostor.getObjectCenter();
  89099. var direction = impostorObjectCenter.subtract(origin);
  89100. var ray = new BABYLON.Ray(origin, direction, radius);
  89101. this._rays.push(ray);
  89102. var hit = ray.intersectsMesh(impostor.object);
  89103. var contactPoint = hit.pickedPoint;
  89104. if (!contactPoint) {
  89105. return null;
  89106. }
  89107. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  89108. if (distanceFromOrigin > radius) {
  89109. return null;
  89110. }
  89111. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  89112. ? strength
  89113. : strength * (1 - (distanceFromOrigin / radius));
  89114. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  89115. return { force: force, contactPoint: contactPoint };
  89116. };
  89117. /**
  89118. * Disposes the sphere.
  89119. * @param {bolean} force
  89120. */
  89121. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  89122. var _this = this;
  89123. if (force === void 0) { force = true; }
  89124. if (force) {
  89125. this._sphere.dispose();
  89126. }
  89127. else {
  89128. setTimeout(function () {
  89129. if (!_this._dataFetched) {
  89130. _this._sphere.dispose();
  89131. }
  89132. }, 0);
  89133. }
  89134. };
  89135. /*** Helpers ***/
  89136. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  89137. if (!this._sphere) {
  89138. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  89139. this._sphere.isVisible = false;
  89140. }
  89141. };
  89142. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  89143. var impostorObject = impostor.object;
  89144. this._prepareSphere();
  89145. this._sphere.position = origin;
  89146. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  89147. this._sphere._updateBoundingInfo();
  89148. this._sphere.computeWorldMatrix(true);
  89149. return this._sphere.intersectsMesh(impostorObject, true);
  89150. };
  89151. return PhysicsRadialExplosionEvent;
  89152. }());
  89153. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  89154. /***** Gravitational Field *****/
  89155. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  89156. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  89157. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  89158. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  89159. this._physicsHelper = physicsHelper;
  89160. this._scene = scene;
  89161. this._origin = origin;
  89162. this._radius = radius;
  89163. this._strength = strength;
  89164. this._falloff = falloff;
  89165. this._tickCallback = this._tick.bind(this);
  89166. }
  89167. /**
  89168. * Returns the data related to the gravitational field event (sphere).
  89169. * @returns {PhysicsGravitationalFieldEventData}
  89170. */
  89171. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  89172. this._dataFetched = true;
  89173. return {
  89174. sphere: this._sphere,
  89175. };
  89176. };
  89177. /**
  89178. * Enables the gravitational field.
  89179. */
  89180. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  89181. this._tickCallback.call(this);
  89182. this._scene.registerBeforeRender(this._tickCallback);
  89183. };
  89184. /**
  89185. * Disables the gravitational field.
  89186. */
  89187. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  89188. this._scene.unregisterBeforeRender(this._tickCallback);
  89189. };
  89190. /**
  89191. * Disposes the sphere.
  89192. * @param {bolean} force
  89193. */
  89194. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  89195. var _this = this;
  89196. if (force === void 0) { force = true; }
  89197. if (force) {
  89198. this._sphere.dispose();
  89199. }
  89200. else {
  89201. setTimeout(function () {
  89202. if (!_this._dataFetched) {
  89203. _this._sphere.dispose();
  89204. }
  89205. }, 0);
  89206. }
  89207. };
  89208. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  89209. // Since the params won't change, we fetch the event only once
  89210. if (this._sphere) {
  89211. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  89212. }
  89213. else {
  89214. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  89215. if (radialExplosionEvent) {
  89216. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  89217. }
  89218. }
  89219. };
  89220. return PhysicsGravitationalFieldEvent;
  89221. }());
  89222. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  89223. /***** Updraft *****/
  89224. var PhysicsUpdraftEvent = /** @class */ (function () {
  89225. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  89226. this._scene = _scene;
  89227. this._origin = _origin;
  89228. this._radius = _radius;
  89229. this._strength = _strength;
  89230. this._height = _height;
  89231. this._updraftMode = _updraftMode;
  89232. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  89233. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  89234. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  89235. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  89236. this._physicsEngine = this._scene.getPhysicsEngine();
  89237. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  89238. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  89239. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  89240. this._originDirection = this._origin.subtract(this._originTop).normalize();
  89241. }
  89242. this._tickCallback = this._tick.bind(this);
  89243. }
  89244. /**
  89245. * Returns the data related to the updraft event (cylinder).
  89246. * @returns {PhysicsUpdraftEventData}
  89247. */
  89248. PhysicsUpdraftEvent.prototype.getData = function () {
  89249. this._dataFetched = true;
  89250. return {
  89251. cylinder: this._cylinder,
  89252. };
  89253. };
  89254. /**
  89255. * Enables the updraft.
  89256. */
  89257. PhysicsUpdraftEvent.prototype.enable = function () {
  89258. this._tickCallback.call(this);
  89259. this._scene.registerBeforeRender(this._tickCallback);
  89260. };
  89261. /**
  89262. * Disables the cortex.
  89263. */
  89264. PhysicsUpdraftEvent.prototype.disable = function () {
  89265. this._scene.unregisterBeforeRender(this._tickCallback);
  89266. };
  89267. /**
  89268. * Disposes the sphere.
  89269. * @param {bolean} force
  89270. */
  89271. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  89272. var _this = this;
  89273. if (force === void 0) { force = true; }
  89274. if (force) {
  89275. this._cylinder.dispose();
  89276. }
  89277. else {
  89278. setTimeout(function () {
  89279. if (!_this._dataFetched) {
  89280. _this._cylinder.dispose();
  89281. }
  89282. }, 0);
  89283. }
  89284. };
  89285. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  89286. if (impostor.mass === 0) {
  89287. return null;
  89288. }
  89289. if (!this._intersectsWithCylinder(impostor)) {
  89290. return null;
  89291. }
  89292. var impostorObjectCenter = impostor.getObjectCenter();
  89293. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  89294. var direction = this._originDirection;
  89295. }
  89296. else {
  89297. var direction = impostorObjectCenter.subtract(this._originTop);
  89298. }
  89299. var multiplier = this._strength * -1;
  89300. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  89301. return { force: force, contactPoint: impostorObjectCenter };
  89302. };
  89303. PhysicsUpdraftEvent.prototype._tick = function () {
  89304. var _this = this;
  89305. this._physicsEngine.getImpostors().forEach(function (impostor) {
  89306. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  89307. if (!impostorForceAndContactPoint) {
  89308. return;
  89309. }
  89310. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  89311. });
  89312. };
  89313. /*** Helpers ***/
  89314. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  89315. if (!this._cylinder) {
  89316. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  89317. height: this._height,
  89318. diameter: this._radius * 2,
  89319. }, this._scene);
  89320. this._cylinder.isVisible = false;
  89321. }
  89322. };
  89323. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  89324. var impostorObject = impostor.object;
  89325. this._prepareCylinder();
  89326. this._cylinder.position = this._cylinderPosition;
  89327. return this._cylinder.intersectsMesh(impostorObject, true);
  89328. };
  89329. return PhysicsUpdraftEvent;
  89330. }());
  89331. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  89332. /***** Vortex *****/
  89333. var PhysicsVortexEvent = /** @class */ (function () {
  89334. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  89335. this._scene = _scene;
  89336. this._origin = _origin;
  89337. this._radius = _radius;
  89338. this._strength = _strength;
  89339. this._height = _height;
  89340. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  89341. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  89342. this._updraftMultiplier = 0.02;
  89343. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  89344. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  89345. this._physicsEngine = this._scene.getPhysicsEngine();
  89346. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  89347. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  89348. this._tickCallback = this._tick.bind(this);
  89349. }
  89350. /**
  89351. * Returns the data related to the vortex event (cylinder).
  89352. * @returns {PhysicsVortexEventData}
  89353. */
  89354. PhysicsVortexEvent.prototype.getData = function () {
  89355. this._dataFetched = true;
  89356. return {
  89357. cylinder: this._cylinder,
  89358. };
  89359. };
  89360. /**
  89361. * Enables the vortex.
  89362. */
  89363. PhysicsVortexEvent.prototype.enable = function () {
  89364. this._tickCallback.call(this);
  89365. this._scene.registerBeforeRender(this._tickCallback);
  89366. };
  89367. /**
  89368. * Disables the cortex.
  89369. */
  89370. PhysicsVortexEvent.prototype.disable = function () {
  89371. this._scene.unregisterBeforeRender(this._tickCallback);
  89372. };
  89373. /**
  89374. * Disposes the sphere.
  89375. * @param {bolean} force
  89376. */
  89377. PhysicsVortexEvent.prototype.dispose = function (force) {
  89378. var _this = this;
  89379. if (force === void 0) { force = true; }
  89380. if (force) {
  89381. this._cylinder.dispose();
  89382. }
  89383. else {
  89384. setTimeout(function () {
  89385. if (!_this._dataFetched) {
  89386. _this._cylinder.dispose();
  89387. }
  89388. }, 0);
  89389. }
  89390. };
  89391. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  89392. if (impostor.mass === 0) {
  89393. return null;
  89394. }
  89395. if (!this._intersectsWithCylinder(impostor)) {
  89396. return null;
  89397. }
  89398. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  89399. return null;
  89400. }
  89401. var impostorObjectCenter = impostor.getObjectCenter();
  89402. 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)
  89403. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  89404. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  89405. var hit = ray.intersectsMesh(impostor.object);
  89406. var contactPoint = hit.pickedPoint;
  89407. if (!contactPoint) {
  89408. return null;
  89409. }
  89410. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  89411. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  89412. var directionToOrigin = contactPoint.normalize();
  89413. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  89414. directionToOrigin = directionToOrigin.negate();
  89415. }
  89416. // TODO: find a more physically based solution
  89417. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  89418. var forceX = directionToOrigin.x * this._strength / 8;
  89419. var forceY = directionToOrigin.y * this._updraftMultiplier;
  89420. var forceZ = directionToOrigin.z * this._strength / 8;
  89421. }
  89422. else {
  89423. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  89424. var forceY = this._originTop.y * this._updraftMultiplier;
  89425. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  89426. }
  89427. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  89428. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  89429. return { force: force, contactPoint: impostorObjectCenter };
  89430. };
  89431. PhysicsVortexEvent.prototype._tick = function () {
  89432. var _this = this;
  89433. this._physicsEngine.getImpostors().forEach(function (impostor) {
  89434. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  89435. if (!impostorForceAndContactPoint) {
  89436. return;
  89437. }
  89438. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  89439. });
  89440. };
  89441. /*** Helpers ***/
  89442. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  89443. if (!this._cylinder) {
  89444. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  89445. height: this._height,
  89446. diameter: this._radius * 2,
  89447. }, this._scene);
  89448. this._cylinder.isVisible = false;
  89449. }
  89450. };
  89451. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  89452. var impostorObject = impostor.object;
  89453. this._prepareCylinder();
  89454. this._cylinder.position = this._cylinderPosition;
  89455. return this._cylinder.intersectsMesh(impostorObject, true);
  89456. };
  89457. return PhysicsVortexEvent;
  89458. }());
  89459. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  89460. /***** Enums *****/
  89461. /**
  89462. * The strenght of the force in correspondence to the distance of the affected object
  89463. */
  89464. var PhysicsRadialImpulseFalloff;
  89465. (function (PhysicsRadialImpulseFalloff) {
  89466. /** Defines that impulse is constant in strength across it's whole radius */
  89467. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  89468. /** DEfines that impulse gets weaker if it's further from the origin */
  89469. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  89470. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  89471. /**
  89472. * The strenght of the force in correspondence to the distance of the affected object
  89473. */
  89474. var PhysicsUpdraftMode;
  89475. (function (PhysicsUpdraftMode) {
  89476. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  89477. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  89478. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  89479. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  89480. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  89481. })(BABYLON || (BABYLON = {}));
  89482. //# sourceMappingURL=babylon.physicsHelper.js.map
  89483. var BABYLON;
  89484. (function (BABYLON) {
  89485. var CannonJSPlugin = /** @class */ (function () {
  89486. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  89487. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  89488. if (iterations === void 0) { iterations = 10; }
  89489. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  89490. this.name = "CannonJSPlugin";
  89491. this._physicsMaterials = new Array();
  89492. this._fixedTimeStep = 1 / 60;
  89493. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  89494. this.BJSCANNON = CANNON;
  89495. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  89496. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  89497. this._tmpPosition = BABYLON.Vector3.Zero();
  89498. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  89499. this._tmpUnityRotation = new BABYLON.Quaternion();
  89500. if (!this.isSupported()) {
  89501. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  89502. return;
  89503. }
  89504. this._extendNamespace();
  89505. this.world = new this.BJSCANNON.World();
  89506. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  89507. this.world.solver.iterations = iterations;
  89508. }
  89509. CannonJSPlugin.prototype.setGravity = function (gravity) {
  89510. this.world.gravity.copy(gravity);
  89511. };
  89512. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  89513. this._fixedTimeStep = timeStep;
  89514. };
  89515. CannonJSPlugin.prototype.getTimeStep = function () {
  89516. return this._fixedTimeStep;
  89517. };
  89518. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  89519. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  89520. };
  89521. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  89522. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  89523. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  89524. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  89525. };
  89526. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  89527. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  89528. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  89529. impostor.physicsBody.applyForce(impulse, worldPoint);
  89530. };
  89531. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  89532. //parent-child relationship. Does this impostor has a parent impostor?
  89533. if (impostor.parent) {
  89534. if (impostor.physicsBody) {
  89535. this.removePhysicsBody(impostor);
  89536. //TODO is that needed?
  89537. impostor.forceUpdate();
  89538. }
  89539. return;
  89540. }
  89541. //should a new body be created for this impostor?
  89542. if (impostor.isBodyInitRequired()) {
  89543. var shape = this._createShape(impostor);
  89544. //unregister events, if body is being changed
  89545. var oldBody = impostor.physicsBody;
  89546. if (oldBody) {
  89547. this.removePhysicsBody(impostor);
  89548. }
  89549. //create the body and material
  89550. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  89551. var bodyCreationObject = {
  89552. mass: impostor.getParam("mass"),
  89553. material: material
  89554. };
  89555. // A simple extend, in case native options were used.
  89556. var nativeOptions = impostor.getParam("nativeOptions");
  89557. for (var key in nativeOptions) {
  89558. if (nativeOptions.hasOwnProperty(key)) {
  89559. bodyCreationObject[key] = nativeOptions[key];
  89560. }
  89561. }
  89562. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  89563. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  89564. this.world.addEventListener("preStep", impostor.beforeStep);
  89565. this.world.addEventListener("postStep", impostor.afterStep);
  89566. impostor.physicsBody.addShape(shape);
  89567. this.world.add(impostor.physicsBody);
  89568. //try to keep the body moving in the right direction by taking old properties.
  89569. //Should be tested!
  89570. if (oldBody) {
  89571. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  89572. impostor.physicsBody[param].copy(oldBody[param]);
  89573. });
  89574. }
  89575. this._processChildMeshes(impostor);
  89576. }
  89577. //now update the body's transformation
  89578. this._updatePhysicsBodyTransformation(impostor);
  89579. };
  89580. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  89581. var _this = this;
  89582. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  89583. var currentRotation = mainImpostor.object.rotationQuaternion;
  89584. if (meshChildren.length) {
  89585. var processMesh = function (localPosition, mesh) {
  89586. if (!currentRotation || !mesh.rotationQuaternion) {
  89587. return;
  89588. }
  89589. var childImpostor = mesh.getPhysicsImpostor();
  89590. if (childImpostor) {
  89591. var parent = childImpostor.parent;
  89592. if (parent !== mainImpostor) {
  89593. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  89594. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  89595. if (childImpostor.physicsBody) {
  89596. _this.removePhysicsBody(childImpostor);
  89597. childImpostor.physicsBody = null;
  89598. }
  89599. childImpostor.parent = mainImpostor;
  89600. childImpostor.resetUpdateFlags();
  89601. 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));
  89602. //Add the mass of the children.
  89603. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  89604. }
  89605. }
  89606. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  89607. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  89608. };
  89609. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  89610. }
  89611. };
  89612. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  89613. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  89614. this.world.removeEventListener("preStep", impostor.beforeStep);
  89615. this.world.removeEventListener("postStep", impostor.afterStep);
  89616. this.world.remove(impostor.physicsBody);
  89617. };
  89618. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  89619. var mainBody = impostorJoint.mainImpostor.physicsBody;
  89620. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  89621. if (!mainBody || !connectedBody) {
  89622. return;
  89623. }
  89624. var constraint;
  89625. var jointData = impostorJoint.joint.jointData;
  89626. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  89627. var constraintData = {
  89628. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  89629. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  89630. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  89631. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  89632. maxForce: jointData.nativeParams.maxForce,
  89633. collideConnected: !!jointData.collision
  89634. };
  89635. switch (impostorJoint.joint.type) {
  89636. case BABYLON.PhysicsJoint.HingeJoint:
  89637. case BABYLON.PhysicsJoint.Hinge2Joint:
  89638. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  89639. break;
  89640. case BABYLON.PhysicsJoint.DistanceJoint:
  89641. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  89642. break;
  89643. case BABYLON.PhysicsJoint.SpringJoint:
  89644. var springData = jointData;
  89645. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  89646. restLength: springData.length,
  89647. stiffness: springData.stiffness,
  89648. damping: springData.damping,
  89649. localAnchorA: constraintData.pivotA,
  89650. localAnchorB: constraintData.pivotB
  89651. });
  89652. break;
  89653. case BABYLON.PhysicsJoint.LockJoint:
  89654. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  89655. break;
  89656. case BABYLON.PhysicsJoint.PointToPointJoint:
  89657. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  89658. default:
  89659. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  89660. break;
  89661. }
  89662. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  89663. constraint.collideConnected = !!jointData.collision;
  89664. impostorJoint.joint.physicsJoint = constraint;
  89665. //don't add spring as constraint, as it is not one.
  89666. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  89667. this.world.addConstraint(constraint);
  89668. }
  89669. else {
  89670. impostorJoint.joint.jointData.forceApplicationCallback = impostorJoint.joint.jointData.forceApplicationCallback || function () {
  89671. constraint.applyForce();
  89672. };
  89673. impostorJoint.mainImpostor.registerAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback);
  89674. }
  89675. };
  89676. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  89677. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  89678. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  89679. }
  89680. else {
  89681. impostorJoint.mainImpostor.unregisterAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback);
  89682. }
  89683. };
  89684. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  89685. var index;
  89686. var mat;
  89687. for (index = 0; index < this._physicsMaterials.length; index++) {
  89688. mat = this._physicsMaterials[index];
  89689. if (mat.friction === friction && mat.restitution === restitution) {
  89690. return mat;
  89691. }
  89692. }
  89693. var currentMat = new this.BJSCANNON.Material(name);
  89694. currentMat.friction = friction;
  89695. currentMat.restitution = restitution;
  89696. this._physicsMaterials.push(currentMat);
  89697. return currentMat;
  89698. };
  89699. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  89700. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  89701. };
  89702. CannonJSPlugin.prototype._createShape = function (impostor) {
  89703. var object = impostor.object;
  89704. var returnValue;
  89705. var extendSize = impostor.getObjectExtendSize();
  89706. switch (impostor.type) {
  89707. case BABYLON.PhysicsImpostor.SphereImpostor:
  89708. var radiusX = extendSize.x;
  89709. var radiusY = extendSize.y;
  89710. var radiusZ = extendSize.z;
  89711. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  89712. break;
  89713. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  89714. case BABYLON.PhysicsImpostor.CylinderImpostor:
  89715. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  89716. break;
  89717. case BABYLON.PhysicsImpostor.BoxImpostor:
  89718. var box = extendSize.scale(0.5);
  89719. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  89720. break;
  89721. case BABYLON.PhysicsImpostor.PlaneImpostor:
  89722. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  89723. returnValue = new this.BJSCANNON.Plane();
  89724. break;
  89725. case BABYLON.PhysicsImpostor.MeshImpostor:
  89726. // should transform the vertex data to world coordinates!!
  89727. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  89728. var rawFaces = object.getIndices ? object.getIndices() : [];
  89729. if (!rawVerts)
  89730. return;
  89731. // get only scale! so the object could transform correctly.
  89732. var oldPosition = object.position.clone();
  89733. var oldRotation = object.rotation && object.rotation.clone();
  89734. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  89735. object.position.copyFromFloats(0, 0, 0);
  89736. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  89737. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  89738. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  89739. var transform = object.computeWorldMatrix(true);
  89740. // convert rawVerts to object space
  89741. var temp = new Array();
  89742. var index;
  89743. for (index = 0; index < rawVerts.length; index += 3) {
  89744. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  89745. }
  89746. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  89747. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  89748. //now set back the transformation!
  89749. object.position.copyFrom(oldPosition);
  89750. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  89751. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  89752. break;
  89753. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  89754. var oldPosition2 = object.position.clone();
  89755. var oldRotation2 = object.rotation && object.rotation.clone();
  89756. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  89757. object.position.copyFromFloats(0, 0, 0);
  89758. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  89759. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  89760. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  89761. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  89762. returnValue = this._createHeightmap(object);
  89763. object.position.copyFrom(oldPosition2);
  89764. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  89765. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  89766. object.computeWorldMatrix(true);
  89767. break;
  89768. case BABYLON.PhysicsImpostor.ParticleImpostor:
  89769. returnValue = new this.BJSCANNON.Particle();
  89770. break;
  89771. }
  89772. return returnValue;
  89773. };
  89774. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  89775. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  89776. var transform = object.computeWorldMatrix(true);
  89777. // convert rawVerts to object space
  89778. var temp = new Array();
  89779. var index;
  89780. for (index = 0; index < pos.length; index += 3) {
  89781. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  89782. }
  89783. pos = temp;
  89784. var matrix = new Array();
  89785. //For now pointDepth will not be used and will be automatically calculated.
  89786. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  89787. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  89788. var boundingInfo = object.getBoundingInfo();
  89789. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  89790. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  89791. var elementSize = dim * 2 / arraySize;
  89792. for (var i = 0; i < pos.length; i = i + 3) {
  89793. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  89794. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  89795. var y = -pos[i + 2] + minY;
  89796. if (!matrix[x]) {
  89797. matrix[x] = [];
  89798. }
  89799. if (!matrix[x][z]) {
  89800. matrix[x][z] = y;
  89801. }
  89802. matrix[x][z] = Math.max(y, matrix[x][z]);
  89803. }
  89804. for (var x = 0; x <= arraySize; ++x) {
  89805. if (!matrix[x]) {
  89806. var loc = 1;
  89807. while (!matrix[(x + loc) % arraySize]) {
  89808. loc++;
  89809. }
  89810. matrix[x] = matrix[(x + loc) % arraySize].slice();
  89811. //console.log("missing x", x);
  89812. }
  89813. for (var z = 0; z <= arraySize; ++z) {
  89814. if (!matrix[x][z]) {
  89815. var loc = 1;
  89816. var newValue;
  89817. while (newValue === undefined) {
  89818. newValue = matrix[x][(z + loc++) % arraySize];
  89819. }
  89820. matrix[x][z] = newValue;
  89821. }
  89822. }
  89823. }
  89824. var shape = new this.BJSCANNON.Heightfield(matrix, {
  89825. elementSize: elementSize
  89826. });
  89827. //For future reference, needed for body transformation
  89828. shape.minY = minY;
  89829. return shape;
  89830. };
  89831. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  89832. var object = impostor.object;
  89833. //make sure it is updated...
  89834. object.computeWorldMatrix && object.computeWorldMatrix(true);
  89835. // The delta between the mesh position and the mesh bounding box center
  89836. var bInfo = object.getBoundingInfo();
  89837. if (!bInfo)
  89838. return;
  89839. var center = impostor.getObjectCenter();
  89840. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  89841. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  89842. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  89843. this._tmpPosition.copyFrom(center);
  89844. var quaternion = object.rotationQuaternion;
  89845. if (!quaternion) {
  89846. return;
  89847. }
  89848. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  89849. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  89850. //-90 DEG in X, precalculated
  89851. quaternion = quaternion.multiply(this._minus90X);
  89852. //Invert! (Precalculated, 90 deg in X)
  89853. //No need to clone. this will never change.
  89854. impostor.setDeltaRotation(this._plus90X);
  89855. }
  89856. //If it is a heightfield, if should be centered.
  89857. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  89858. var mesh = object;
  89859. var boundingInfo = mesh.getBoundingInfo();
  89860. //calculate the correct body position:
  89861. var rotationQuaternion = mesh.rotationQuaternion;
  89862. mesh.rotationQuaternion = this._tmpUnityRotation;
  89863. mesh.computeWorldMatrix(true);
  89864. //get original center with no rotation
  89865. var c = center.clone();
  89866. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  89867. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  89868. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  89869. mesh.setPreTransformMatrix(p);
  89870. mesh.computeWorldMatrix(true);
  89871. //calculate the translation
  89872. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  89873. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  89874. //add it inverted to the delta
  89875. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  89876. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  89877. //rotation is back
  89878. mesh.rotationQuaternion = rotationQuaternion;
  89879. mesh.setPreTransformMatrix(oldPivot);
  89880. mesh.computeWorldMatrix(true);
  89881. }
  89882. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  89883. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  89884. //this._tmpPosition.copyFrom(object.position);
  89885. }
  89886. impostor.setDeltaPosition(this._tmpDeltaPosition);
  89887. //Now update the impostor object
  89888. impostor.physicsBody.position.copy(this._tmpPosition);
  89889. impostor.physicsBody.quaternion.copy(quaternion);
  89890. };
  89891. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  89892. impostor.object.position.copyFrom(impostor.physicsBody.position);
  89893. if (impostor.object.rotationQuaternion) {
  89894. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  89895. }
  89896. };
  89897. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  89898. impostor.physicsBody.position.copy(newPosition);
  89899. impostor.physicsBody.quaternion.copy(newRotation);
  89900. };
  89901. CannonJSPlugin.prototype.isSupported = function () {
  89902. return this.BJSCANNON !== undefined;
  89903. };
  89904. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  89905. impostor.physicsBody.velocity.copy(velocity);
  89906. };
  89907. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  89908. impostor.physicsBody.angularVelocity.copy(velocity);
  89909. };
  89910. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  89911. var v = impostor.physicsBody.velocity;
  89912. if (!v) {
  89913. return null;
  89914. }
  89915. return new BABYLON.Vector3(v.x, v.y, v.z);
  89916. };
  89917. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  89918. var v = impostor.physicsBody.angularVelocity;
  89919. if (!v) {
  89920. return null;
  89921. }
  89922. return new BABYLON.Vector3(v.x, v.y, v.z);
  89923. };
  89924. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  89925. impostor.physicsBody.mass = mass;
  89926. impostor.physicsBody.updateMassProperties();
  89927. };
  89928. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  89929. return impostor.physicsBody.mass;
  89930. };
  89931. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  89932. return impostor.physicsBody.material.friction;
  89933. };
  89934. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  89935. impostor.physicsBody.material.friction = friction;
  89936. };
  89937. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  89938. return impostor.physicsBody.material.restitution;
  89939. };
  89940. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  89941. impostor.physicsBody.material.restitution = restitution;
  89942. };
  89943. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  89944. impostor.physicsBody.sleep();
  89945. };
  89946. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  89947. impostor.physicsBody.wakeUp();
  89948. };
  89949. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  89950. joint.physicsJoint.distance = maxDistance;
  89951. };
  89952. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  89953. // if (!motorIndex) {
  89954. // joint.physicsJoint.enableMotor();
  89955. // }
  89956. // }
  89957. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  89958. // if (!motorIndex) {
  89959. // joint.physicsJoint.disableMotor();
  89960. // }
  89961. // }
  89962. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  89963. if (!motorIndex) {
  89964. joint.physicsJoint.enableMotor();
  89965. joint.physicsJoint.setMotorSpeed(speed);
  89966. if (maxForce) {
  89967. this.setLimit(joint, maxForce);
  89968. }
  89969. }
  89970. };
  89971. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  89972. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  89973. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  89974. };
  89975. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  89976. var body = impostor.physicsBody;
  89977. mesh.position.x = body.position.x;
  89978. mesh.position.y = body.position.y;
  89979. mesh.position.z = body.position.z;
  89980. if (mesh.rotationQuaternion) {
  89981. mesh.rotationQuaternion.x = body.quaternion.x;
  89982. mesh.rotationQuaternion.y = body.quaternion.y;
  89983. mesh.rotationQuaternion.z = body.quaternion.z;
  89984. mesh.rotationQuaternion.w = body.quaternion.w;
  89985. }
  89986. };
  89987. CannonJSPlugin.prototype.getRadius = function (impostor) {
  89988. var shape = impostor.physicsBody.shapes[0];
  89989. return shape.boundingSphereRadius;
  89990. };
  89991. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  89992. var shape = impostor.physicsBody.shapes[0];
  89993. result.x = shape.halfExtents.x * 2;
  89994. result.y = shape.halfExtents.y * 2;
  89995. result.z = shape.halfExtents.z * 2;
  89996. };
  89997. CannonJSPlugin.prototype.dispose = function () {
  89998. };
  89999. CannonJSPlugin.prototype._extendNamespace = function () {
  90000. //this will force cannon to execute at least one step when using interpolation
  90001. var step_tmp1 = new this.BJSCANNON.Vec3();
  90002. var Engine = this.BJSCANNON;
  90003. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  90004. maxSubSteps = maxSubSteps || 10;
  90005. timeSinceLastCalled = timeSinceLastCalled || 0;
  90006. if (timeSinceLastCalled === 0) {
  90007. this.internalStep(dt);
  90008. this.time += dt;
  90009. }
  90010. else {
  90011. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  90012. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  90013. var t0 = performance.now();
  90014. for (var i = 0; i !== internalSteps; i++) {
  90015. this.internalStep(dt);
  90016. if (performance.now() - t0 > dt * 1000) {
  90017. break;
  90018. }
  90019. }
  90020. this.time += timeSinceLastCalled;
  90021. var h = this.time % dt;
  90022. var h_div_dt = h / dt;
  90023. var interpvelo = step_tmp1;
  90024. var bodies = this.bodies;
  90025. for (var j = 0; j !== bodies.length; j++) {
  90026. var b = bodies[j];
  90027. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  90028. b.position.vsub(b.previousPosition, interpvelo);
  90029. interpvelo.scale(h_div_dt, interpvelo);
  90030. b.position.vadd(interpvelo, b.interpolatedPosition);
  90031. }
  90032. else {
  90033. b.interpolatedPosition.copy(b.position);
  90034. b.interpolatedQuaternion.copy(b.quaternion);
  90035. }
  90036. }
  90037. }
  90038. };
  90039. };
  90040. return CannonJSPlugin;
  90041. }());
  90042. BABYLON.CannonJSPlugin = CannonJSPlugin;
  90043. })(BABYLON || (BABYLON = {}));
  90044. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  90045. var BABYLON;
  90046. (function (BABYLON) {
  90047. var OimoJSPlugin = /** @class */ (function () {
  90048. function OimoJSPlugin(iterations) {
  90049. this.name = "OimoJSPlugin";
  90050. this._tmpImpostorsArray = [];
  90051. this._tmpPositionVector = BABYLON.Vector3.Zero();
  90052. this.BJSOIMO = OIMO;
  90053. this.world = new this.BJSOIMO.World({
  90054. iterations: iterations
  90055. });
  90056. this.world.clear();
  90057. }
  90058. OimoJSPlugin.prototype.setGravity = function (gravity) {
  90059. this.world.gravity.copy(gravity);
  90060. };
  90061. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  90062. this.world.timeStep = timeStep;
  90063. };
  90064. OimoJSPlugin.prototype.getTimeStep = function () {
  90065. return this.world.timeStep;
  90066. };
  90067. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  90068. var _this = this;
  90069. impostors.forEach(function (impostor) {
  90070. impostor.beforeStep();
  90071. });
  90072. this.world.step();
  90073. impostors.forEach(function (impostor) {
  90074. impostor.afterStep();
  90075. //update the ordered impostors array
  90076. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  90077. });
  90078. //check for collisions
  90079. var contact = this.world.contacts;
  90080. while (contact !== null) {
  90081. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  90082. contact = contact.next;
  90083. continue;
  90084. }
  90085. //is this body colliding with any other? get the impostor
  90086. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  90087. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  90088. if (!mainImpostor || !collidingImpostor) {
  90089. contact = contact.next;
  90090. continue;
  90091. }
  90092. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  90093. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  90094. contact = contact.next;
  90095. }
  90096. };
  90097. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  90098. var mass = impostor.physicsBody.mass;
  90099. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  90100. };
  90101. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  90102. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  90103. this.applyImpulse(impostor, force, contactPoint);
  90104. };
  90105. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  90106. var _this = this;
  90107. //parent-child relationship. Does this impostor has a parent impostor?
  90108. if (impostor.parent) {
  90109. if (impostor.physicsBody) {
  90110. this.removePhysicsBody(impostor);
  90111. //TODO is that needed?
  90112. impostor.forceUpdate();
  90113. }
  90114. return;
  90115. }
  90116. if (impostor.isBodyInitRequired()) {
  90117. var bodyConfig = {
  90118. name: impostor.uniqueId,
  90119. //Oimo must have mass, also for static objects.
  90120. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  90121. size: [],
  90122. type: [],
  90123. pos: [],
  90124. posShape: [],
  90125. rot: [],
  90126. rotShape: [],
  90127. move: impostor.getParam("mass") !== 0,
  90128. density: impostor.getParam("mass"),
  90129. friction: impostor.getParam("friction"),
  90130. restitution: impostor.getParam("restitution"),
  90131. //Supporting older versions of Oimo
  90132. world: this.world
  90133. };
  90134. var impostors = [impostor];
  90135. var addToArray = function (parent) {
  90136. if (!parent.getChildMeshes)
  90137. return;
  90138. parent.getChildMeshes().forEach(function (m) {
  90139. if (m.physicsImpostor) {
  90140. impostors.push(m.physicsImpostor);
  90141. //m.physicsImpostor._init();
  90142. }
  90143. });
  90144. };
  90145. addToArray(impostor.object);
  90146. var checkWithEpsilon_1 = function (value) {
  90147. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  90148. };
  90149. var globalQuaternion_1 = new BABYLON.Quaternion();
  90150. impostors.forEach(function (i) {
  90151. if (!i.object.rotationQuaternion) {
  90152. return;
  90153. }
  90154. //get the correct bounding box
  90155. var oldQuaternion = i.object.rotationQuaternion;
  90156. globalQuaternion_1 = oldQuaternion.clone();
  90157. var rot = oldQuaternion.toEulerAngles();
  90158. var extendSize = i.getObjectExtendSize();
  90159. var radToDeg = 57.295779513082320876;
  90160. if (i === impostor) {
  90161. var center = impostor.getObjectCenter();
  90162. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  90163. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  90164. //Can also use Array.prototype.push.apply
  90165. bodyConfig.pos.push(center.x);
  90166. bodyConfig.pos.push(center.y);
  90167. bodyConfig.pos.push(center.z);
  90168. bodyConfig.posShape.push(0, 0, 0);
  90169. //tmp solution
  90170. bodyConfig.rot.push(0);
  90171. bodyConfig.rot.push(0);
  90172. bodyConfig.rot.push(0);
  90173. bodyConfig.rotShape.push(0, 0, 0);
  90174. }
  90175. else {
  90176. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  90177. bodyConfig.posShape.push(localPosition.x);
  90178. bodyConfig.posShape.push(localPosition.y);
  90179. bodyConfig.posShape.push(localPosition.z);
  90180. bodyConfig.pos.push(0, 0, 0);
  90181. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  90182. bodyConfig.rot.push(0);
  90183. bodyConfig.rot.push(0);
  90184. bodyConfig.rot.push(0);
  90185. bodyConfig.rotShape.push(rot.x * radToDeg);
  90186. bodyConfig.rotShape.push(rot.y * radToDeg);
  90187. bodyConfig.rotShape.push(rot.z * radToDeg);
  90188. }
  90189. // register mesh
  90190. switch (i.type) {
  90191. case BABYLON.PhysicsImpostor.ParticleImpostor:
  90192. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  90193. case BABYLON.PhysicsImpostor.SphereImpostor:
  90194. var radiusX = extendSize.x;
  90195. var radiusY = extendSize.y;
  90196. var radiusZ = extendSize.z;
  90197. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  90198. bodyConfig.type.push('sphere');
  90199. //due to the way oimo works with compounds, add 3 times
  90200. bodyConfig.size.push(size);
  90201. bodyConfig.size.push(size);
  90202. bodyConfig.size.push(size);
  90203. break;
  90204. case BABYLON.PhysicsImpostor.CylinderImpostor:
  90205. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  90206. var sizeY = checkWithEpsilon_1(extendSize.y);
  90207. bodyConfig.type.push('cylinder');
  90208. bodyConfig.size.push(sizeX);
  90209. bodyConfig.size.push(sizeY);
  90210. //due to the way oimo works with compounds, add one more value.
  90211. bodyConfig.size.push(sizeY);
  90212. break;
  90213. case BABYLON.PhysicsImpostor.PlaneImpostor:
  90214. case BABYLON.PhysicsImpostor.BoxImpostor:
  90215. default:
  90216. var sizeX = checkWithEpsilon_1(extendSize.x);
  90217. var sizeY = checkWithEpsilon_1(extendSize.y);
  90218. var sizeZ = checkWithEpsilon_1(extendSize.z);
  90219. bodyConfig.type.push('box');
  90220. //if (i === impostor) {
  90221. bodyConfig.size.push(sizeX);
  90222. bodyConfig.size.push(sizeY);
  90223. bodyConfig.size.push(sizeZ);
  90224. //} else {
  90225. // bodyConfig.size.push(0,0,0);
  90226. //}
  90227. break;
  90228. }
  90229. //actually not needed, but hey...
  90230. i.object.rotationQuaternion = oldQuaternion;
  90231. });
  90232. impostor.physicsBody = this.world.add(bodyConfig);
  90233. // set the quaternion, ignoring the previously defined (euler) rotation
  90234. impostor.physicsBody.resetQuaternion(globalQuaternion_1);
  90235. // update with delta 0, so the body will reveive the new rotation.
  90236. impostor.physicsBody.updatePosition(0);
  90237. }
  90238. else {
  90239. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  90240. }
  90241. impostor.setDeltaPosition(this._tmpPositionVector);
  90242. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  90243. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  90244. };
  90245. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  90246. //impostor.physicsBody.dispose();
  90247. //Same as : (older oimo versions)
  90248. this.world.removeRigidBody(impostor.physicsBody);
  90249. };
  90250. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  90251. var mainBody = impostorJoint.mainImpostor.physicsBody;
  90252. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  90253. if (!mainBody || !connectedBody) {
  90254. return;
  90255. }
  90256. var jointData = impostorJoint.joint.jointData;
  90257. var options = jointData.nativeParams || {};
  90258. var type;
  90259. var nativeJointData = {
  90260. body1: mainBody,
  90261. body2: connectedBody,
  90262. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  90263. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  90264. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  90265. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  90266. min: options.min,
  90267. max: options.max,
  90268. collision: options.collision || jointData.collision,
  90269. spring: options.spring,
  90270. //supporting older version of Oimo
  90271. world: this.world
  90272. };
  90273. switch (impostorJoint.joint.type) {
  90274. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  90275. type = "jointBall";
  90276. break;
  90277. case BABYLON.PhysicsJoint.SpringJoint:
  90278. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  90279. var springData = jointData;
  90280. nativeJointData.min = springData.length || nativeJointData.min;
  90281. //Max should also be set, just make sure it is at least min
  90282. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  90283. case BABYLON.PhysicsJoint.DistanceJoint:
  90284. type = "jointDistance";
  90285. nativeJointData.max = jointData.maxDistance;
  90286. break;
  90287. case BABYLON.PhysicsJoint.PrismaticJoint:
  90288. type = "jointPrisme";
  90289. break;
  90290. case BABYLON.PhysicsJoint.SliderJoint:
  90291. type = "jointSlide";
  90292. break;
  90293. case BABYLON.PhysicsJoint.WheelJoint:
  90294. type = "jointWheel";
  90295. break;
  90296. case BABYLON.PhysicsJoint.HingeJoint:
  90297. default:
  90298. type = "jointHinge";
  90299. break;
  90300. }
  90301. nativeJointData.type = type;
  90302. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  90303. };
  90304. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  90305. //Bug in Oimo prevents us from disposing a joint in the playground
  90306. //joint.joint.physicsJoint.dispose();
  90307. //So we will bruteforce it!
  90308. try {
  90309. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  90310. }
  90311. catch (e) {
  90312. BABYLON.Tools.Warn(e);
  90313. }
  90314. };
  90315. OimoJSPlugin.prototype.isSupported = function () {
  90316. return this.BJSOIMO !== undefined;
  90317. };
  90318. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  90319. if (!impostor.physicsBody.sleeping) {
  90320. //TODO check that
  90321. /*if (impostor.physicsBody.shapes.next) {
  90322. var parentShape = this._getLastShape(impostor.physicsBody);
  90323. impostor.object.position.copyFrom(parentShape.position);
  90324. console.log(parentShape.position);
  90325. } else {*/
  90326. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  90327. //}
  90328. if (impostor.object.rotationQuaternion) {
  90329. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  90330. }
  90331. }
  90332. };
  90333. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  90334. var body = impostor.physicsBody;
  90335. body.position.copy(newPosition);
  90336. body.orientation.copy(newRotation);
  90337. body.syncShapes();
  90338. body.awake();
  90339. };
  90340. /*private _getLastShape(body: any): any {
  90341. var lastShape = body.shapes;
  90342. while (lastShape.next) {
  90343. lastShape = lastShape.next;
  90344. }
  90345. return lastShape;
  90346. }*/
  90347. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  90348. impostor.physicsBody.linearVelocity.copy(velocity);
  90349. };
  90350. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  90351. impostor.physicsBody.angularVelocity.copy(velocity);
  90352. };
  90353. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  90354. var v = impostor.physicsBody.linearVelocity;
  90355. if (!v) {
  90356. return null;
  90357. }
  90358. return new BABYLON.Vector3(v.x, v.y, v.z);
  90359. };
  90360. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  90361. var v = impostor.physicsBody.angularVelocity;
  90362. if (!v) {
  90363. return null;
  90364. }
  90365. return new BABYLON.Vector3(v.x, v.y, v.z);
  90366. };
  90367. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  90368. var staticBody = mass === 0;
  90369. //this will actually set the body's density and not its mass.
  90370. //But this is how oimo treats the mass variable.
  90371. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  90372. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  90373. };
  90374. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  90375. return impostor.physicsBody.shapes.density;
  90376. };
  90377. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  90378. return impostor.physicsBody.shapes.friction;
  90379. };
  90380. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  90381. impostor.physicsBody.shapes.friction = friction;
  90382. };
  90383. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  90384. return impostor.physicsBody.shapes.restitution;
  90385. };
  90386. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  90387. impostor.physicsBody.shapes.restitution = restitution;
  90388. };
  90389. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  90390. impostor.physicsBody.sleep();
  90391. };
  90392. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  90393. impostor.physicsBody.awake();
  90394. };
  90395. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  90396. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  90397. if (minDistance !== void 0) {
  90398. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  90399. }
  90400. };
  90401. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  90402. //TODO separate rotational and transational motors.
  90403. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  90404. if (motor) {
  90405. motor.setMotor(speed, maxForce);
  90406. }
  90407. };
  90408. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  90409. //TODO separate rotational and transational motors.
  90410. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  90411. if (motor) {
  90412. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  90413. }
  90414. };
  90415. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  90416. var body = impostor.physicsBody;
  90417. mesh.position.x = body.position.x;
  90418. mesh.position.y = body.position.y;
  90419. mesh.position.z = body.position.z;
  90420. if (mesh.rotationQuaternion) {
  90421. mesh.rotationQuaternion.x = body.orientation.x;
  90422. mesh.rotationQuaternion.y = body.orientation.y;
  90423. mesh.rotationQuaternion.z = body.orientation.z;
  90424. mesh.rotationQuaternion.w = body.orientation.s;
  90425. }
  90426. };
  90427. OimoJSPlugin.prototype.getRadius = function (impostor) {
  90428. return impostor.physicsBody.shapes.radius;
  90429. };
  90430. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  90431. var shape = impostor.physicsBody.shapes;
  90432. result.x = shape.halfWidth * 2;
  90433. result.y = shape.halfHeight * 2;
  90434. result.z = shape.halfDepth * 2;
  90435. };
  90436. OimoJSPlugin.prototype.dispose = function () {
  90437. this.world.clear();
  90438. };
  90439. return OimoJSPlugin;
  90440. }());
  90441. BABYLON.OimoJSPlugin = OimoJSPlugin;
  90442. })(BABYLON || (BABYLON = {}));
  90443. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  90444. var BABYLON;
  90445. (function (BABYLON) {
  90446. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  90447. // All values and structures referenced from:
  90448. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  90449. var DDS_MAGIC = 0x20534444;
  90450. var
  90451. //DDSD_CAPS = 0x1,
  90452. //DDSD_HEIGHT = 0x2,
  90453. //DDSD_WIDTH = 0x4,
  90454. //DDSD_PITCH = 0x8,
  90455. //DDSD_PIXELFORMAT = 0x1000,
  90456. DDSD_MIPMAPCOUNT = 0x20000;
  90457. //DDSD_LINEARSIZE = 0x80000,
  90458. //DDSD_DEPTH = 0x800000;
  90459. // var DDSCAPS_COMPLEX = 0x8,
  90460. // DDSCAPS_MIPMAP = 0x400000,
  90461. // DDSCAPS_TEXTURE = 0x1000;
  90462. var DDSCAPS2_CUBEMAP = 0x200;
  90463. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  90464. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  90465. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  90466. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  90467. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  90468. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  90469. // DDSCAPS2_VOLUME = 0x200000;
  90470. var
  90471. //DDPF_ALPHAPIXELS = 0x1,
  90472. //DDPF_ALPHA = 0x2,
  90473. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  90474. //DDPF_YUV = 0x200,
  90475. DDPF_LUMINANCE = 0x20000;
  90476. function FourCCToInt32(value) {
  90477. return value.charCodeAt(0) +
  90478. (value.charCodeAt(1) << 8) +
  90479. (value.charCodeAt(2) << 16) +
  90480. (value.charCodeAt(3) << 24);
  90481. }
  90482. function Int32ToFourCC(value) {
  90483. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  90484. }
  90485. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  90486. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  90487. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  90488. var FOURCC_DX10 = FourCCToInt32("DX10");
  90489. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  90490. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  90491. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  90492. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  90493. var headerLengthInt = 31; // The header length in 32 bit ints
  90494. // Offsets into the header array
  90495. var off_magic = 0;
  90496. var off_size = 1;
  90497. var off_flags = 2;
  90498. var off_height = 3;
  90499. var off_width = 4;
  90500. var off_mipmapCount = 7;
  90501. var off_pfFlags = 20;
  90502. var off_pfFourCC = 21;
  90503. var off_RGBbpp = 22;
  90504. var off_RMask = 23;
  90505. var off_GMask = 24;
  90506. var off_BMask = 25;
  90507. var off_AMask = 26;
  90508. // var off_caps1 = 27;
  90509. var off_caps2 = 28;
  90510. // var off_caps3 = 29;
  90511. // var off_caps4 = 30;
  90512. var off_dxgiFormat = 32;
  90513. ;
  90514. var DDSTools = /** @class */ (function () {
  90515. function DDSTools() {
  90516. }
  90517. DDSTools.GetDDSInfo = function (arrayBuffer) {
  90518. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  90519. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  90520. var mipmapCount = 1;
  90521. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  90522. mipmapCount = Math.max(1, header[off_mipmapCount]);
  90523. }
  90524. var fourCC = header[off_pfFourCC];
  90525. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  90526. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  90527. switch (fourCC) {
  90528. case FOURCC_D3DFMT_R16G16B16A16F:
  90529. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  90530. break;
  90531. case FOURCC_D3DFMT_R32G32B32A32F:
  90532. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  90533. break;
  90534. case FOURCC_DX10:
  90535. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  90536. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  90537. break;
  90538. }
  90539. }
  90540. return {
  90541. width: header[off_width],
  90542. height: header[off_height],
  90543. mipmapCount: mipmapCount,
  90544. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  90545. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  90546. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  90547. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  90548. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  90549. dxgiFormat: dxgiFormat,
  90550. textureType: textureType
  90551. };
  90552. };
  90553. DDSTools._ToHalfFloat = function (value) {
  90554. if (!DDSTools._FloatView) {
  90555. DDSTools._FloatView = new Float32Array(1);
  90556. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  90557. }
  90558. DDSTools._FloatView[0] = value;
  90559. var x = DDSTools._Int32View[0];
  90560. var bits = (x >> 16) & 0x8000; /* Get the sign */
  90561. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  90562. var e = (x >> 23) & 0xff; /* Using int is faster here */
  90563. /* If zero, or denormal, or exponent underflows too much for a denormal
  90564. * half, return signed zero. */
  90565. if (e < 103) {
  90566. return bits;
  90567. }
  90568. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  90569. if (e > 142) {
  90570. bits |= 0x7c00;
  90571. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  90572. * not Inf, so make sure we set one mantissa bit too. */
  90573. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  90574. return bits;
  90575. }
  90576. /* If exponent underflows but not too much, return a denormal */
  90577. if (e < 113) {
  90578. m |= 0x0800;
  90579. /* Extra rounding may overflow and set mantissa to 0 and exponent
  90580. * to 1, which is OK. */
  90581. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  90582. return bits;
  90583. }
  90584. bits |= ((e - 112) << 10) | (m >> 1);
  90585. bits += m & 1;
  90586. return bits;
  90587. };
  90588. DDSTools._FromHalfFloat = function (value) {
  90589. var s = (value & 0x8000) >> 15;
  90590. var e = (value & 0x7C00) >> 10;
  90591. var f = value & 0x03FF;
  90592. if (e === 0) {
  90593. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  90594. }
  90595. else if (e == 0x1F) {
  90596. return f ? NaN : ((s ? -1 : 1) * Infinity);
  90597. }
  90598. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  90599. };
  90600. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  90601. var destArray = new Float32Array(dataLength);
  90602. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  90603. var index = 0;
  90604. for (var y = 0; y < height; y++) {
  90605. for (var x = 0; x < width; x++) {
  90606. var srcPos = (x + y * width) * 4;
  90607. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  90608. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  90609. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  90610. if (DDSTools.StoreLODInAlphaChannel) {
  90611. destArray[index + 3] = lod;
  90612. }
  90613. else {
  90614. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  90615. }
  90616. index += 4;
  90617. }
  90618. }
  90619. return destArray;
  90620. };
  90621. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  90622. if (DDSTools.StoreLODInAlphaChannel) {
  90623. var destArray = new Uint16Array(dataLength);
  90624. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  90625. var index = 0;
  90626. for (var y = 0; y < height; y++) {
  90627. for (var x = 0; x < width; x++) {
  90628. var srcPos = (x + y * width) * 4;
  90629. destArray[index] = srcData[srcPos];
  90630. destArray[index + 1] = srcData[srcPos + 1];
  90631. destArray[index + 2] = srcData[srcPos + 2];
  90632. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  90633. index += 4;
  90634. }
  90635. }
  90636. return destArray;
  90637. }
  90638. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  90639. };
  90640. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  90641. if (DDSTools.StoreLODInAlphaChannel) {
  90642. var destArray = new Float32Array(dataLength);
  90643. var srcData = new Float32Array(arrayBuffer, dataOffset);
  90644. var index = 0;
  90645. for (var y = 0; y < height; y++) {
  90646. for (var x = 0; x < width; x++) {
  90647. var srcPos = (x + y * width) * 4;
  90648. destArray[index] = srcData[srcPos];
  90649. destArray[index + 1] = srcData[srcPos + 1];
  90650. destArray[index + 2] = srcData[srcPos + 2];
  90651. destArray[index + 3] = lod;
  90652. index += 4;
  90653. }
  90654. }
  90655. return destArray;
  90656. }
  90657. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  90658. };
  90659. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  90660. var destArray = new Uint8Array(dataLength);
  90661. var srcData = new Float32Array(arrayBuffer, dataOffset);
  90662. var index = 0;
  90663. for (var y = 0; y < height; y++) {
  90664. for (var x = 0; x < width; x++) {
  90665. var srcPos = (x + y * width) * 4;
  90666. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  90667. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  90668. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  90669. if (DDSTools.StoreLODInAlphaChannel) {
  90670. destArray[index + 3] = lod;
  90671. }
  90672. else {
  90673. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  90674. }
  90675. index += 4;
  90676. }
  90677. }
  90678. return destArray;
  90679. };
  90680. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  90681. var destArray = new Uint8Array(dataLength);
  90682. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  90683. var index = 0;
  90684. for (var y = 0; y < height; y++) {
  90685. for (var x = 0; x < width; x++) {
  90686. var srcPos = (x + y * width) * 4;
  90687. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  90688. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  90689. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  90690. if (DDSTools.StoreLODInAlphaChannel) {
  90691. destArray[index + 3] = lod;
  90692. }
  90693. else {
  90694. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  90695. }
  90696. index += 4;
  90697. }
  90698. }
  90699. return destArray;
  90700. };
  90701. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  90702. var byteArray = new Uint8Array(dataLength);
  90703. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  90704. var index = 0;
  90705. for (var y = 0; y < height; y++) {
  90706. for (var x = 0; x < width; x++) {
  90707. var srcPos = (x + y * width) * 4;
  90708. byteArray[index] = srcData[srcPos + rOffset];
  90709. byteArray[index + 1] = srcData[srcPos + gOffset];
  90710. byteArray[index + 2] = srcData[srcPos + bOffset];
  90711. byteArray[index + 3] = srcData[srcPos + aOffset];
  90712. index += 4;
  90713. }
  90714. }
  90715. return byteArray;
  90716. };
  90717. DDSTools._ExtractLongWordOrder = function (value) {
  90718. if (value === 0 || value === 255 || value === -16777216) {
  90719. return 0;
  90720. }
  90721. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  90722. };
  90723. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  90724. var byteArray = new Uint8Array(dataLength);
  90725. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  90726. var index = 0;
  90727. for (var y = 0; y < height; y++) {
  90728. for (var x = 0; x < width; x++) {
  90729. var srcPos = (x + y * width) * 3;
  90730. byteArray[index] = srcData[srcPos + rOffset];
  90731. byteArray[index + 1] = srcData[srcPos + gOffset];
  90732. byteArray[index + 2] = srcData[srcPos + bOffset];
  90733. index += 3;
  90734. }
  90735. }
  90736. return byteArray;
  90737. };
  90738. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  90739. var byteArray = new Uint8Array(dataLength);
  90740. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  90741. var index = 0;
  90742. for (var y = 0; y < height; y++) {
  90743. for (var x = 0; x < width; x++) {
  90744. var srcPos = (x + y * width);
  90745. byteArray[index] = srcData[srcPos];
  90746. index++;
  90747. }
  90748. }
  90749. return byteArray;
  90750. };
  90751. /**
  90752. * Uploads DDS Levels to a Babylon Texture
  90753. * @hidden
  90754. */
  90755. DDSTools.UploadDDSLevels = function (engine, texture, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  90756. if (lodIndex === void 0) { lodIndex = -1; }
  90757. var sphericalPolynomialFaces = null;
  90758. if (info.sphericalPolynomial) {
  90759. sphericalPolynomialFaces = new Array();
  90760. }
  90761. var ext = engine.getCaps().s3tc;
  90762. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  90763. var fourCC, width, height, dataLength = 0, dataOffset;
  90764. var byteArray, mipmapCount, mip;
  90765. var internalCompressedFormat = 0;
  90766. var blockBytes = 1;
  90767. if (header[off_magic] !== DDS_MAGIC) {
  90768. BABYLON.Tools.Error("Invalid magic number in DDS header");
  90769. return;
  90770. }
  90771. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  90772. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  90773. return;
  90774. }
  90775. if (info.isCompressed && !ext) {
  90776. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  90777. return;
  90778. }
  90779. var bpp = header[off_RGBbpp];
  90780. dataOffset = header[off_size] + 4;
  90781. var computeFormats = false;
  90782. if (info.isFourCC) {
  90783. fourCC = header[off_pfFourCC];
  90784. switch (fourCC) {
  90785. case FOURCC_DXT1:
  90786. blockBytes = 8;
  90787. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  90788. break;
  90789. case FOURCC_DXT3:
  90790. blockBytes = 16;
  90791. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  90792. break;
  90793. case FOURCC_DXT5:
  90794. blockBytes = 16;
  90795. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  90796. break;
  90797. case FOURCC_D3DFMT_R16G16B16A16F:
  90798. computeFormats = true;
  90799. break;
  90800. case FOURCC_D3DFMT_R32G32B32A32F:
  90801. computeFormats = true;
  90802. break;
  90803. case FOURCC_DX10:
  90804. // There is an additionnal header so dataOffset need to be changed
  90805. dataOffset += 5 * 4; // 5 uints
  90806. var supported = false;
  90807. switch (info.dxgiFormat) {
  90808. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  90809. computeFormats = true;
  90810. supported = true;
  90811. break;
  90812. case DXGI_FORMAT_B8G8R8X8_UNORM:
  90813. info.isRGB = true;
  90814. info.isFourCC = false;
  90815. bpp = 32;
  90816. supported = true;
  90817. break;
  90818. }
  90819. if (supported) {
  90820. break;
  90821. }
  90822. default:
  90823. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  90824. return;
  90825. }
  90826. }
  90827. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  90828. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  90829. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  90830. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  90831. if (computeFormats) {
  90832. internalCompressedFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  90833. }
  90834. mipmapCount = 1;
  90835. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  90836. mipmapCount = Math.max(1, header[off_mipmapCount]);
  90837. }
  90838. for (var face = 0; face < faces; face++) {
  90839. width = header[off_width];
  90840. height = header[off_height];
  90841. for (mip = 0; mip < mipmapCount; ++mip) {
  90842. if (lodIndex === -1 || lodIndex === mip) {
  90843. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  90844. var i = (lodIndex === -1) ? mip : 0;
  90845. if (!info.isCompressed && info.isFourCC) {
  90846. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  90847. dataLength = width * height * 4;
  90848. var floatArray = null;
  90849. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  90850. if (bpp === 128) {
  90851. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  90852. if (sphericalPolynomialFaces && i == 0) {
  90853. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  90854. }
  90855. }
  90856. else if (bpp === 64) {
  90857. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  90858. if (sphericalPolynomialFaces && i == 0) {
  90859. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  90860. }
  90861. }
  90862. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  90863. }
  90864. else {
  90865. if (bpp === 128) {
  90866. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  90867. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  90868. if (sphericalPolynomialFaces && i == 0) {
  90869. sphericalPolynomialFaces.push(floatArray);
  90870. }
  90871. }
  90872. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  90873. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  90874. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  90875. if (sphericalPolynomialFaces && i == 0) {
  90876. sphericalPolynomialFaces.push(floatArray);
  90877. }
  90878. }
  90879. else { // 64
  90880. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  90881. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  90882. if (sphericalPolynomialFaces && i == 0) {
  90883. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  90884. }
  90885. }
  90886. }
  90887. if (floatArray) {
  90888. engine._uploadDataToTextureDirectly(texture, floatArray, face, i);
  90889. }
  90890. }
  90891. else if (info.isRGB) {
  90892. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  90893. if (bpp === 24) {
  90894. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGB;
  90895. dataLength = width * height * 3;
  90896. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  90897. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  90898. }
  90899. else { // 32
  90900. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  90901. dataLength = width * height * 4;
  90902. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  90903. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  90904. }
  90905. }
  90906. else if (info.isLuminance) {
  90907. var unpackAlignment = engine._getUnpackAlignement();
  90908. var unpaddedRowSize = width;
  90909. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  90910. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  90911. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  90912. texture.format = BABYLON.Engine.TEXTUREFORMAT_LUMINANCE;
  90913. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  90914. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  90915. }
  90916. else {
  90917. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  90918. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  90919. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  90920. engine._uploadCompressedDataToTextureDirectly(texture, internalCompressedFormat, width, height, byteArray, face, i);
  90921. }
  90922. }
  90923. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  90924. width *= 0.5;
  90925. height *= 0.5;
  90926. width = Math.max(1.0, width);
  90927. height = Math.max(1.0, height);
  90928. }
  90929. if (currentFace !== undefined) {
  90930. // Loading a single face
  90931. break;
  90932. }
  90933. }
  90934. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  90935. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  90936. size: header[off_width],
  90937. right: sphericalPolynomialFaces[0],
  90938. left: sphericalPolynomialFaces[1],
  90939. up: sphericalPolynomialFaces[2],
  90940. down: sphericalPolynomialFaces[3],
  90941. front: sphericalPolynomialFaces[4],
  90942. back: sphericalPolynomialFaces[5],
  90943. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  90944. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  90945. gammaSpace: false,
  90946. });
  90947. }
  90948. else {
  90949. info.sphericalPolynomial = undefined;
  90950. }
  90951. };
  90952. DDSTools.StoreLODInAlphaChannel = false;
  90953. return DDSTools;
  90954. }());
  90955. BABYLON.DDSTools = DDSTools;
  90956. })(BABYLON || (BABYLON = {}));
  90957. //# sourceMappingURL=babylon.dds.js.map
  90958. var BABYLON;
  90959. (function (BABYLON) {
  90960. /**
  90961. * Implementation of the DDS Texture Loader.
  90962. */
  90963. var DDSTextureLoader = /** @class */ (function () {
  90964. function DDSTextureLoader() {
  90965. /**
  90966. * Defines wether the loader supports cascade loading the different faces.
  90967. */
  90968. this.supportCascades = true;
  90969. }
  90970. /**
  90971. * This returns if the loader support the current file information.
  90972. * @param extension defines the file extension of the file being loaded
  90973. * @param textureFormatInUse defines the current compressed format in use iun the engine
  90974. * @param fallback defines the fallback internal texture if any
  90975. * @param isBase64 defines whether the texture is encoded as a base64
  90976. * @param isBuffer defines whether the texture data are stored as a buffer
  90977. * @returns true if the loader can load the specified file
  90978. */
  90979. DDSTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  90980. return extension.indexOf(".dds") === 0;
  90981. };
  90982. /**
  90983. * Transform the url before loading if required.
  90984. * @param rootUrl the url of the texture
  90985. * @param textureFormatInUse defines the current compressed format in use iun the engine
  90986. * @returns the transformed texture
  90987. */
  90988. DDSTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  90989. return rootUrl;
  90990. };
  90991. /**
  90992. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  90993. * @param rootUrl the url of the texture
  90994. * @param textureFormatInUse defines the current compressed format in use iun the engine
  90995. * @returns the fallback texture
  90996. */
  90997. DDSTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  90998. return null;
  90999. };
  91000. /**
  91001. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  91002. * @param data contains the texture data
  91003. * @param texture defines the BabylonJS internal texture
  91004. * @param createPolynomials will be true if polynomials have been requested
  91005. * @param onLoad defines the callback to trigger once the texture is ready
  91006. * @param onError defines the callback to trigger in case of error
  91007. */
  91008. DDSTextureLoader.prototype.loadCubeData = function (imgs, texture, createPolynomials, onLoad, onError) {
  91009. var engine = texture.getEngine();
  91010. var info;
  91011. var loadMipmap = false;
  91012. if (Array.isArray(imgs)) {
  91013. for (var index = 0; index < imgs.length; index++) {
  91014. var data_1 = imgs[index];
  91015. info = BABYLON.DDSTools.GetDDSInfo(data_1);
  91016. texture.width = info.width;
  91017. texture.height = info.height;
  91018. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  91019. engine._unpackFlipY(info.isCompressed);
  91020. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data_1, info, loadMipmap, 6, -1, index);
  91021. if (!info.isFourCC && info.mipmapCount === 1) {
  91022. engine.generateMipMapsForCubemap(texture);
  91023. }
  91024. }
  91025. }
  91026. else {
  91027. var data = imgs;
  91028. info = BABYLON.DDSTools.GetDDSInfo(data);
  91029. texture.width = info.width;
  91030. texture.height = info.height;
  91031. if (createPolynomials) {
  91032. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  91033. }
  91034. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  91035. engine._unpackFlipY(info.isCompressed);
  91036. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data, info, loadMipmap, 6);
  91037. if (!info.isFourCC && info.mipmapCount === 1) {
  91038. engine.generateMipMapsForCubemap(texture);
  91039. }
  91040. }
  91041. engine._setCubeMapTextureParams(loadMipmap);
  91042. texture.isReady = true;
  91043. if (onLoad) {
  91044. onLoad({ isDDS: true, width: texture.width, info: info, data: imgs, texture: texture });
  91045. }
  91046. };
  91047. /**
  91048. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  91049. * @param data contains the texture data
  91050. * @param texture defines the BabylonJS internal texture
  91051. * @param callback defines the method to call once ready to upload
  91052. */
  91053. DDSTextureLoader.prototype.loadData = function (data, texture, callback) {
  91054. var info = BABYLON.DDSTools.GetDDSInfo(data);
  91055. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps && ((info.width >> (info.mipmapCount - 1)) === 1);
  91056. callback(info.width, info.height, loadMipmap, info.isFourCC, function () {
  91057. BABYLON.DDSTools.UploadDDSLevels(texture.getEngine(), texture, data, info, loadMipmap, 1);
  91058. });
  91059. };
  91060. return DDSTextureLoader;
  91061. }());
  91062. // Register the loader.
  91063. BABYLON.Engine._TextureLoaders.push(new DDSTextureLoader());
  91064. })(BABYLON || (BABYLON = {}));
  91065. //# sourceMappingURL=babylon.ddsTextureLoader.js.map
  91066. var BABYLON;
  91067. (function (BABYLON) {
  91068. /*
  91069. * Based on jsTGALoader - Javascript loader for TGA file
  91070. * By Vincent Thibault
  91071. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  91072. */
  91073. var TGATools = /** @class */ (function () {
  91074. function TGATools() {
  91075. }
  91076. TGATools.GetTGAHeader = function (data) {
  91077. var offset = 0;
  91078. var header = {
  91079. id_length: data[offset++],
  91080. colormap_type: data[offset++],
  91081. image_type: data[offset++],
  91082. colormap_index: data[offset++] | data[offset++] << 8,
  91083. colormap_length: data[offset++] | data[offset++] << 8,
  91084. colormap_size: data[offset++],
  91085. origin: [
  91086. data[offset++] | data[offset++] << 8,
  91087. data[offset++] | data[offset++] << 8
  91088. ],
  91089. width: data[offset++] | data[offset++] << 8,
  91090. height: data[offset++] | data[offset++] << 8,
  91091. pixel_size: data[offset++],
  91092. flags: data[offset++]
  91093. };
  91094. return header;
  91095. };
  91096. /**
  91097. * Uploads TGA content to a Babylon Texture
  91098. * @hidden
  91099. */
  91100. TGATools.UploadContent = function (texture, data) {
  91101. // Not enough data to contain header ?
  91102. if (data.length < 19) {
  91103. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  91104. return;
  91105. }
  91106. // Read Header
  91107. var offset = 18;
  91108. var header = TGATools.GetTGAHeader(data);
  91109. // Assume it's a valid Targa file.
  91110. if (header.id_length + offset > data.length) {
  91111. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  91112. return;
  91113. }
  91114. // Skip not needed data
  91115. offset += header.id_length;
  91116. var use_rle = false;
  91117. var use_pal = false;
  91118. var use_grey = false;
  91119. // Get some informations.
  91120. switch (header.image_type) {
  91121. case TGATools._TYPE_RLE_INDEXED:
  91122. use_rle = true;
  91123. case TGATools._TYPE_INDEXED:
  91124. use_pal = true;
  91125. break;
  91126. case TGATools._TYPE_RLE_RGB:
  91127. use_rle = true;
  91128. case TGATools._TYPE_RGB:
  91129. // use_rgb = true;
  91130. break;
  91131. case TGATools._TYPE_RLE_GREY:
  91132. use_rle = true;
  91133. case TGATools._TYPE_GREY:
  91134. use_grey = true;
  91135. break;
  91136. }
  91137. var pixel_data;
  91138. // var numAlphaBits = header.flags & 0xf;
  91139. var pixel_size = header.pixel_size >> 3;
  91140. var pixel_total = header.width * header.height * pixel_size;
  91141. // Read palettes
  91142. var palettes;
  91143. if (use_pal) {
  91144. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  91145. }
  91146. // Read LRE
  91147. if (use_rle) {
  91148. pixel_data = new Uint8Array(pixel_total);
  91149. var c, count, i;
  91150. var localOffset = 0;
  91151. var pixels = new Uint8Array(pixel_size);
  91152. while (offset < pixel_total && localOffset < pixel_total) {
  91153. c = data[offset++];
  91154. count = (c & 0x7f) + 1;
  91155. // RLE pixels
  91156. if (c & 0x80) {
  91157. // Bind pixel tmp array
  91158. for (i = 0; i < pixel_size; ++i) {
  91159. pixels[i] = data[offset++];
  91160. }
  91161. // Copy pixel array
  91162. for (i = 0; i < count; ++i) {
  91163. pixel_data.set(pixels, localOffset + i * pixel_size);
  91164. }
  91165. localOffset += pixel_size * count;
  91166. }
  91167. // Raw pixels
  91168. else {
  91169. count *= pixel_size;
  91170. for (i = 0; i < count; ++i) {
  91171. pixel_data[localOffset + i] = data[offset++];
  91172. }
  91173. localOffset += count;
  91174. }
  91175. }
  91176. }
  91177. // RAW Pixels
  91178. else {
  91179. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  91180. }
  91181. // Load to texture
  91182. var x_start, y_start, x_step, y_step, y_end, x_end;
  91183. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  91184. default:
  91185. case TGATools._ORIGIN_UL:
  91186. x_start = 0;
  91187. x_step = 1;
  91188. x_end = header.width;
  91189. y_start = 0;
  91190. y_step = 1;
  91191. y_end = header.height;
  91192. break;
  91193. case TGATools._ORIGIN_BL:
  91194. x_start = 0;
  91195. x_step = 1;
  91196. x_end = header.width;
  91197. y_start = header.height - 1;
  91198. y_step = -1;
  91199. y_end = -1;
  91200. break;
  91201. case TGATools._ORIGIN_UR:
  91202. x_start = header.width - 1;
  91203. x_step = -1;
  91204. x_end = -1;
  91205. y_start = 0;
  91206. y_step = 1;
  91207. y_end = header.height;
  91208. break;
  91209. case TGATools._ORIGIN_BR:
  91210. x_start = header.width - 1;
  91211. x_step = -1;
  91212. x_end = -1;
  91213. y_start = header.height - 1;
  91214. y_step = -1;
  91215. y_end = -1;
  91216. break;
  91217. }
  91218. // Load the specify method
  91219. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  91220. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  91221. var engine = texture.getEngine();
  91222. engine._uploadDataToTextureDirectly(texture, imageData);
  91223. };
  91224. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  91225. var image = pixel_data, colormap = palettes;
  91226. var width = header.width, height = header.height;
  91227. var color, i = 0, x, y;
  91228. var imageData = new Uint8Array(width * height * 4);
  91229. for (y = y_start; y !== y_end; y += y_step) {
  91230. for (x = x_start; x !== x_end; x += x_step, i++) {
  91231. color = image[i];
  91232. imageData[(x + width * y) * 4 + 3] = 255;
  91233. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  91234. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  91235. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  91236. }
  91237. }
  91238. return imageData;
  91239. };
  91240. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  91241. var image = pixel_data;
  91242. var width = header.width, height = header.height;
  91243. var color, i = 0, x, y;
  91244. var imageData = new Uint8Array(width * height * 4);
  91245. for (y = y_start; y !== y_end; y += y_step) {
  91246. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  91247. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  91248. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  91249. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  91250. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  91251. imageData[(x + width * y) * 4 + 0] = r;
  91252. imageData[(x + width * y) * 4 + 1] = g;
  91253. imageData[(x + width * y) * 4 + 2] = b;
  91254. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  91255. }
  91256. }
  91257. return imageData;
  91258. };
  91259. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  91260. var image = pixel_data;
  91261. var width = header.width, height = header.height;
  91262. var i = 0, x, y;
  91263. var imageData = new Uint8Array(width * height * 4);
  91264. for (y = y_start; y !== y_end; y += y_step) {
  91265. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  91266. imageData[(x + width * y) * 4 + 3] = 255;
  91267. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  91268. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  91269. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  91270. }
  91271. }
  91272. return imageData;
  91273. };
  91274. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  91275. var image = pixel_data;
  91276. var width = header.width, height = header.height;
  91277. var i = 0, x, y;
  91278. var imageData = new Uint8Array(width * height * 4);
  91279. for (y = y_start; y !== y_end; y += y_step) {
  91280. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  91281. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  91282. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  91283. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  91284. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  91285. }
  91286. }
  91287. return imageData;
  91288. };
  91289. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  91290. var image = pixel_data;
  91291. var width = header.width, height = header.height;
  91292. var color, i = 0, x, y;
  91293. var imageData = new Uint8Array(width * height * 4);
  91294. for (y = y_start; y !== y_end; y += y_step) {
  91295. for (x = x_start; x !== x_end; x += x_step, i++) {
  91296. color = image[i];
  91297. imageData[(x + width * y) * 4 + 0] = color;
  91298. imageData[(x + width * y) * 4 + 1] = color;
  91299. imageData[(x + width * y) * 4 + 2] = color;
  91300. imageData[(x + width * y) * 4 + 3] = 255;
  91301. }
  91302. }
  91303. return imageData;
  91304. };
  91305. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  91306. var image = pixel_data;
  91307. var width = header.width, height = header.height;
  91308. var i = 0, x, y;
  91309. var imageData = new Uint8Array(width * height * 4);
  91310. for (y = y_start; y !== y_end; y += y_step) {
  91311. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  91312. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  91313. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  91314. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  91315. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  91316. }
  91317. }
  91318. return imageData;
  91319. };
  91320. //private static _TYPE_NO_DATA = 0;
  91321. TGATools._TYPE_INDEXED = 1;
  91322. TGATools._TYPE_RGB = 2;
  91323. TGATools._TYPE_GREY = 3;
  91324. TGATools._TYPE_RLE_INDEXED = 9;
  91325. TGATools._TYPE_RLE_RGB = 10;
  91326. TGATools._TYPE_RLE_GREY = 11;
  91327. TGATools._ORIGIN_MASK = 0x30;
  91328. TGATools._ORIGIN_SHIFT = 0x04;
  91329. TGATools._ORIGIN_BL = 0x00;
  91330. TGATools._ORIGIN_BR = 0x01;
  91331. TGATools._ORIGIN_UL = 0x02;
  91332. TGATools._ORIGIN_UR = 0x03;
  91333. return TGATools;
  91334. }());
  91335. BABYLON.TGATools = TGATools;
  91336. })(BABYLON || (BABYLON = {}));
  91337. //# sourceMappingURL=babylon.tga.js.map
  91338. var BABYLON;
  91339. (function (BABYLON) {
  91340. /**
  91341. * Implementation of the TGA Texture Loader.
  91342. */
  91343. var TGATextureLoader = /** @class */ (function () {
  91344. function TGATextureLoader() {
  91345. /**
  91346. * Defines wether the loader supports cascade loading the different faces.
  91347. */
  91348. this.supportCascades = false;
  91349. }
  91350. /**
  91351. * This returns if the loader support the current file information.
  91352. * @param extension defines the file extension of the file being loaded
  91353. * @param textureFormatInUse defines the current compressed format in use iun the engine
  91354. * @param fallback defines the fallback internal texture if any
  91355. * @param isBase64 defines whether the texture is encoded as a base64
  91356. * @param isBuffer defines whether the texture data are stored as a buffer
  91357. * @returns true if the loader can load the specified file
  91358. */
  91359. TGATextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  91360. return extension.indexOf(".tga") === 0;
  91361. };
  91362. /**
  91363. * Transform the url before loading if required.
  91364. * @param rootUrl the url of the texture
  91365. * @param textureFormatInUse defines the current compressed format in use iun the engine
  91366. * @returns the transformed texture
  91367. */
  91368. TGATextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  91369. return rootUrl;
  91370. };
  91371. /**
  91372. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  91373. * @param rootUrl the url of the texture
  91374. * @param textureFormatInUse defines the current compressed format in use iun the engine
  91375. * @returns the fallback texture
  91376. */
  91377. TGATextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  91378. return null;
  91379. };
  91380. /**
  91381. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  91382. * @param data contains the texture data
  91383. * @param texture defines the BabylonJS internal texture
  91384. * @param createPolynomials will be true if polynomials have been requested
  91385. * @param onLoad defines the callback to trigger once the texture is ready
  91386. * @param onError defines the callback to trigger in case of error
  91387. */
  91388. TGATextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  91389. throw ".env not supported in Cube.";
  91390. };
  91391. /**
  91392. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  91393. * @param data contains the texture data
  91394. * @param texture defines the BabylonJS internal texture
  91395. * @param callback defines the method to call once ready to upload
  91396. */
  91397. TGATextureLoader.prototype.loadData = function (data, texture, callback) {
  91398. var uintData = new Uint8Array(data);
  91399. var header = BABYLON.TGATools.GetTGAHeader(uintData);
  91400. callback(header.width, header.height, texture.generateMipMaps, false, function () {
  91401. BABYLON.TGATools.UploadContent(texture, uintData);
  91402. });
  91403. };
  91404. return TGATextureLoader;
  91405. }());
  91406. // Register the loader.
  91407. BABYLON.Engine._TextureLoaders.push(new TGATextureLoader());
  91408. })(BABYLON || (BABYLON = {}));
  91409. //# sourceMappingURL=babylon.tgaTextureLoader.js.map
  91410. var BABYLON;
  91411. (function (BABYLON) {
  91412. /**
  91413. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  91414. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  91415. */
  91416. var KhronosTextureContainer = /** @class */ (function () {
  91417. /**
  91418. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  91419. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  91420. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  91421. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  91422. */
  91423. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  91424. this.arrayBuffer = arrayBuffer;
  91425. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  91426. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  91427. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  91428. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  91429. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  91430. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  91431. BABYLON.Tools.Error("texture missing KTX identifier");
  91432. return;
  91433. }
  91434. // load the reset of the header in native 32 bit int
  91435. var header = new Int32Array(this.arrayBuffer, 12, 13);
  91436. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  91437. var oppositeEndianess = header[0] === 0x01020304;
  91438. // read all the header elements in order they exist in the file, without modification (sans endainness)
  91439. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  91440. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  91441. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  91442. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  91443. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  91444. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  91445. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  91446. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  91447. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  91448. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  91449. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  91450. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  91451. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  91452. if (this.glType !== 0) {
  91453. BABYLON.Tools.Error("only compressed formats currently supported");
  91454. return;
  91455. }
  91456. else {
  91457. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  91458. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  91459. }
  91460. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  91461. BABYLON.Tools.Error("only 2D textures currently supported");
  91462. return;
  91463. }
  91464. if (this.numberOfArrayElements !== 0) {
  91465. BABYLON.Tools.Error("texture arrays not currently supported");
  91466. return;
  91467. }
  91468. if (this.numberOfFaces !== facesExpected) {
  91469. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  91470. return;
  91471. }
  91472. // we now have a completely validated file, so could use existence of loadType as success
  91473. // would need to make this more elaborate & adjust checks above to support more than one load type
  91474. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  91475. }
  91476. // not as fast hardware based, but will probably never need to use
  91477. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  91478. return ((val & 0xFF) << 24)
  91479. | ((val & 0xFF00) << 8)
  91480. | ((val >> 8) & 0xFF00)
  91481. | ((val >> 24) & 0xFF);
  91482. };
  91483. /**
  91484. * Uploads KTX content to a Babylon Texture.
  91485. * It is assumed that the texture has already been created & is currently bound
  91486. * @hidden
  91487. */
  91488. KhronosTextureContainer.prototype.uploadLevels = function (texture, loadMipmaps) {
  91489. switch (this.loadType) {
  91490. case KhronosTextureContainer.COMPRESSED_2D:
  91491. this._upload2DCompressedLevels(texture, loadMipmaps);
  91492. break;
  91493. case KhronosTextureContainer.TEX_2D:
  91494. case KhronosTextureContainer.COMPRESSED_3D:
  91495. case KhronosTextureContainer.TEX_3D:
  91496. }
  91497. };
  91498. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (texture, loadMipmaps) {
  91499. // initialize width & height for level 1
  91500. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  91501. var width = this.pixelWidth;
  91502. var height = this.pixelHeight;
  91503. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  91504. for (var level = 0; level < mipmapCount; level++) {
  91505. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  91506. dataOffset += 4; //image data starts from next multiple of 4 offset. Each face refers to same imagesize field above.
  91507. for (var face = 0; face < this.numberOfFaces; face++) {
  91508. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset, imageSize);
  91509. var engine = texture.getEngine();
  91510. engine._uploadCompressedDataToTextureDirectly(texture, this.glInternalFormat, width, height, byteArray, face, level);
  91511. dataOffset += imageSize; // add size of the image for the next face/mipmap
  91512. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  91513. }
  91514. width = Math.max(1.0, width * 0.5);
  91515. height = Math.max(1.0, height * 0.5);
  91516. }
  91517. };
  91518. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  91519. // load types
  91520. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  91521. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  91522. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  91523. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  91524. return KhronosTextureContainer;
  91525. }());
  91526. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  91527. })(BABYLON || (BABYLON = {}));
  91528. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  91529. var BABYLON;
  91530. (function (BABYLON) {
  91531. /**
  91532. * Implementation of the KTX Texture Loader.
  91533. */
  91534. var KTXTextureLoader = /** @class */ (function () {
  91535. function KTXTextureLoader() {
  91536. /**
  91537. * Defines wether the loader supports cascade loading the different faces.
  91538. */
  91539. this.supportCascades = false;
  91540. }
  91541. /**
  91542. * This returns if the loader support the current file information.
  91543. * @param extension defines the file extension of the file being loaded
  91544. * @param textureFormatInUse defines the current compressed format in use iun the engine
  91545. * @param fallback defines the fallback internal texture if any
  91546. * @param isBase64 defines whether the texture is encoded as a base64
  91547. * @param isBuffer defines whether the texture data are stored as a buffer
  91548. * @returns true if the loader can load the specified file
  91549. */
  91550. KTXTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  91551. if (textureFormatInUse && !isBase64 && !fallback && !isBuffer) {
  91552. return true;
  91553. }
  91554. return false;
  91555. };
  91556. /**
  91557. * Transform the url before loading if required.
  91558. * @param rootUrl the url of the texture
  91559. * @param textureFormatInUse defines the current compressed format in use iun the engine
  91560. * @returns the transformed texture
  91561. */
  91562. KTXTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  91563. var lastDot = rootUrl.lastIndexOf('.');
  91564. return (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + textureFormatInUse;
  91565. };
  91566. /**
  91567. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  91568. * @param rootUrl the url of the texture
  91569. * @param textureFormatInUse defines the current compressed format in use iun the engine
  91570. * @returns the fallback texture
  91571. */
  91572. KTXTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  91573. // remove the format appended to the rootUrl in the original createCubeTexture call.
  91574. var exp = new RegExp("" + textureFormatInUse + "$");
  91575. return rootUrl.replace(exp, "");
  91576. };
  91577. /**
  91578. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  91579. * @param data contains the texture data
  91580. * @param texture defines the BabylonJS internal texture
  91581. * @param createPolynomials will be true if polynomials have been requested
  91582. * @param onLoad defines the callback to trigger once the texture is ready
  91583. * @param onError defines the callback to trigger in case of error
  91584. */
  91585. KTXTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  91586. if (Array.isArray(data)) {
  91587. return;
  91588. }
  91589. var engine = texture.getEngine();
  91590. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  91591. var loadMipmap = ktx.numberOfMipmapLevels > 1 && texture.generateMipMaps;
  91592. engine._unpackFlipY(true);
  91593. ktx.uploadLevels(texture, texture.generateMipMaps);
  91594. texture.width = ktx.pixelWidth;
  91595. texture.height = ktx.pixelHeight;
  91596. engine._setCubeMapTextureParams(loadMipmap);
  91597. texture.isReady = true;
  91598. };
  91599. /**
  91600. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  91601. * @param data contains the texture data
  91602. * @param texture defines the BabylonJS internal texture
  91603. * @param callback defines the method to call once ready to upload
  91604. */
  91605. KTXTextureLoader.prototype.loadData = function (data, texture, callback) {
  91606. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  91607. callback(ktx.pixelWidth, ktx.pixelHeight, false, true, function () {
  91608. ktx.uploadLevels(texture, texture.generateMipMaps);
  91609. });
  91610. };
  91611. return KTXTextureLoader;
  91612. }());
  91613. // Register the loader.
  91614. BABYLON.Engine._TextureLoaders.unshift(new KTXTextureLoader());
  91615. })(BABYLON || (BABYLON = {}));
  91616. //# sourceMappingURL=babylon.ktxTextureLoader.js.map
  91617. var BABYLON;
  91618. (function (BABYLON) {
  91619. /**
  91620. * Sets of helpers addressing the serialization and deserialization of environment texture
  91621. * stored in a BabylonJS env file.
  91622. * Those files are usually stored as .env files.
  91623. */
  91624. var EnvironmentTextureTools = /** @class */ (function () {
  91625. function EnvironmentTextureTools() {
  91626. }
  91627. /**
  91628. * Gets the environment info from an env file.
  91629. * @param data The array buffer containing the .env bytes.
  91630. * @returns the environment file info (the json header) if successfully parsed.
  91631. */
  91632. EnvironmentTextureTools.GetEnvInfo = function (data) {
  91633. var dataView = new DataView(data);
  91634. var pos = 0;
  91635. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  91636. if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {
  91637. BABYLON.Tools.Error('Not a babylon environment map');
  91638. return null;
  91639. }
  91640. }
  91641. // Read json manifest - collect characters up to null terminator
  91642. var manifestString = '';
  91643. var charCode = 0x00;
  91644. while ((charCode = dataView.getUint8(pos++))) {
  91645. manifestString += String.fromCharCode(charCode);
  91646. }
  91647. var manifest = JSON.parse(manifestString);
  91648. if (manifest.specular) {
  91649. // Extend the header with the position of the payload.
  91650. manifest.specular.specularDataPosition = pos;
  91651. // Fallback to 0.8 exactly if lodGenerationScale is not defined for backward compatibility.
  91652. manifest.specular.lodGenerationScale = manifest.specular.lodGenerationScale || 0.8;
  91653. }
  91654. return manifest;
  91655. };
  91656. /**
  91657. * Creates an environment texture from a loaded cube texture.
  91658. * @param texture defines the cube texture to convert in env file
  91659. * @return a promise containing the environment data if succesfull.
  91660. */
  91661. EnvironmentTextureTools.CreateEnvTextureAsync = function (texture) {
  91662. var _this = this;
  91663. var internalTexture = texture.getInternalTexture();
  91664. if (!internalTexture) {
  91665. return Promise.reject("The cube texture is invalid.");
  91666. }
  91667. if (!texture._prefiltered) {
  91668. return Promise.reject("The cube texture is invalid (not prefiltered).");
  91669. }
  91670. var engine = internalTexture.getEngine();
  91671. if (engine && engine.premultipliedAlpha) {
  91672. return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.");
  91673. }
  91674. if (texture.textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  91675. return Promise.reject("The cube texture should allow HDR (Full Float or Half Float).");
  91676. }
  91677. var canvas = engine.getRenderingCanvas();
  91678. if (!canvas) {
  91679. return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");
  91680. }
  91681. var textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  91682. if (!engine.getCaps().textureFloatRender) {
  91683. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  91684. if (!engine.getCaps().textureHalfFloatRender) {
  91685. return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
  91686. }
  91687. }
  91688. var cubeWidth = internalTexture.width;
  91689. var hostingScene = new BABYLON.Scene(engine);
  91690. var specularTextures = {};
  91691. var promises = [];
  91692. // Read and collect all mipmaps data from the cube.
  91693. var mipmapsCount = BABYLON.Scalar.Log2(internalTexture.width);
  91694. mipmapsCount = Math.round(mipmapsCount);
  91695. var _loop_1 = function (i) {
  91696. var faceWidth = Math.pow(2, mipmapsCount - i);
  91697. var _loop_2 = function (face) {
  91698. var data = texture.readPixels(face, i);
  91699. // Creates a temp texture with the face data.
  91700. var tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);
  91701. // And rgbdEncode them.
  91702. var promise = new Promise(function (resolve, reject) {
  91703. 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);
  91704. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  91705. rgbdPostProcess.onApply = function (effect) {
  91706. effect._bindTexture("textureSampler", tempTexture);
  91707. };
  91708. // As the process needs to happen on the main canvas, keep track of the current size
  91709. var currentW = engine.getRenderWidth();
  91710. var currentH = engine.getRenderHeight();
  91711. // Set the desired size for the texture
  91712. engine.setSize(faceWidth, faceWidth);
  91713. hostingScene.postProcessManager.directRender([rgbdPostProcess], null);
  91714. // Reading datas from WebGL
  91715. BABYLON.Tools.ToBlob(canvas, function (blob) {
  91716. var fileReader = new FileReader();
  91717. fileReader.onload = function (event) {
  91718. var arrayBuffer = event.target.result;
  91719. specularTextures[i * 6 + face] = arrayBuffer;
  91720. resolve();
  91721. };
  91722. fileReader.readAsArrayBuffer(blob);
  91723. });
  91724. // Reapply the previous canvas size
  91725. engine.setSize(currentW, currentH);
  91726. });
  91727. });
  91728. promises.push(promise);
  91729. };
  91730. // All faces of the cube.
  91731. for (var face = 0; face < 6; face++) {
  91732. _loop_2(face);
  91733. }
  91734. };
  91735. for (var i = 0; i <= mipmapsCount; i++) {
  91736. _loop_1(i);
  91737. }
  91738. // Once all the textures haves been collected as RGBD stored in PNGs
  91739. return Promise.all(promises).then(function () {
  91740. // We can delete the hosting scene keeping track of all the creation objects
  91741. hostingScene.dispose();
  91742. // Creates the json header for the env texture
  91743. var info = {
  91744. version: 1,
  91745. width: cubeWidth,
  91746. irradiance: _this._CreateEnvTextureIrradiance(texture),
  91747. specular: {
  91748. mipmaps: [],
  91749. lodGenerationScale: texture.lodGenerationScale
  91750. }
  91751. };
  91752. // Sets the specular image data information
  91753. var position = 0;
  91754. for (var i = 0; i <= mipmapsCount; i++) {
  91755. for (var face = 0; face < 6; face++) {
  91756. var byteLength = specularTextures[i * 6 + face].byteLength;
  91757. info.specular.mipmaps.push({
  91758. length: byteLength,
  91759. position: position
  91760. });
  91761. position += byteLength;
  91762. }
  91763. }
  91764. // Encode the JSON as an array buffer
  91765. var infoString = JSON.stringify(info);
  91766. var infoBuffer = new ArrayBuffer(infoString.length + 1);
  91767. var infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.
  91768. for (var i = 0, strLen = infoString.length; i < strLen; i++) {
  91769. infoView[i] = infoString.charCodeAt(i);
  91770. }
  91771. // Ends up with a null terminator for easier parsing
  91772. infoView[infoString.length] = 0x00;
  91773. // Computes the final required size and creates the storage
  91774. var totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;
  91775. var finalBuffer = new ArrayBuffer(totalSize);
  91776. var finalBufferView = new Uint8Array(finalBuffer);
  91777. var dataView = new DataView(finalBuffer);
  91778. // Copy the magic bytes identifying the file in
  91779. var pos = 0;
  91780. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  91781. dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);
  91782. }
  91783. // Add the json info
  91784. finalBufferView.set(new Uint8Array(infoBuffer), pos);
  91785. pos += infoBuffer.byteLength;
  91786. // Finally inserts the texture data
  91787. for (var i = 0; i <= mipmapsCount; i++) {
  91788. for (var face = 0; face < 6; face++) {
  91789. var dataBuffer = specularTextures[i * 6 + face];
  91790. finalBufferView.set(new Uint8Array(dataBuffer), pos);
  91791. pos += dataBuffer.byteLength;
  91792. }
  91793. }
  91794. // Voila
  91795. return finalBuffer;
  91796. });
  91797. };
  91798. /**
  91799. * Creates a JSON representation of the spherical data.
  91800. * @param texture defines the texture containing the polynomials
  91801. * @return the JSON representation of the spherical info
  91802. */
  91803. EnvironmentTextureTools._CreateEnvTextureIrradiance = function (texture) {
  91804. var polynmials = texture.sphericalPolynomial;
  91805. if (polynmials == null) {
  91806. return null;
  91807. }
  91808. return {
  91809. x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
  91810. y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
  91811. z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
  91812. xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
  91813. yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
  91814. zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
  91815. yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
  91816. zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
  91817. xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
  91818. };
  91819. };
  91820. /**
  91821. * Uploads the texture info contained in the env file to the GPU.
  91822. * @param texture defines the internal texture to upload to
  91823. * @param arrayBuffer defines the buffer cotaining the data to load
  91824. * @param info defines the texture info retrieved through the GetEnvInfo method
  91825. * @returns a promise
  91826. */
  91827. EnvironmentTextureTools.UploadEnvLevelsAsync = function (texture, arrayBuffer, info) {
  91828. if (info.version !== 1) {
  91829. throw new Error("Unsupported babylon environment map version \"" + info.version + "\"");
  91830. }
  91831. var specularInfo = info.specular;
  91832. if (!specularInfo) {
  91833. // Nothing else parsed so far
  91834. return Promise.resolve();
  91835. }
  91836. // Double checks the enclosed info
  91837. var mipmapsCount = BABYLON.Scalar.Log2(info.width);
  91838. mipmapsCount = Math.round(mipmapsCount) + 1;
  91839. if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
  91840. throw new Error("Unsupported specular mipmaps number \"" + specularInfo.mipmaps.length + "\"");
  91841. }
  91842. texture._lodGenerationScale = specularInfo.lodGenerationScale;
  91843. var imageData = new Array(mipmapsCount);
  91844. for (var i = 0; i < mipmapsCount; i++) {
  91845. imageData[i] = new Array(6);
  91846. for (var face = 0; face < 6; face++) {
  91847. var imageInfo = specularInfo.mipmaps[i * 6 + face];
  91848. imageData[i][face] = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition + imageInfo.position, imageInfo.length);
  91849. }
  91850. }
  91851. return EnvironmentTextureTools.UploadLevelsAsync(texture, imageData);
  91852. };
  91853. /**
  91854. * Uploads the levels of image data to the GPU.
  91855. * @param texture defines the internal texture to upload to
  91856. * @param imageData defines the array buffer views of image data [mipmap][face]
  91857. * @returns a promise
  91858. */
  91859. EnvironmentTextureTools.UploadLevelsAsync = function (texture, imageData) {
  91860. if (!BABYLON.Tools.IsExponentOfTwo(texture.width)) {
  91861. throw new Error("Texture size must be a power of two");
  91862. }
  91863. var mipmapsCount = Math.round(BABYLON.Scalar.Log2(texture.width)) + 1;
  91864. // Gets everything ready.
  91865. var engine = texture.getEngine();
  91866. var expandTexture = false;
  91867. var generateNonLODTextures = false;
  91868. var rgbdPostProcess = null;
  91869. var cubeRtt = null;
  91870. var lodTextures = null;
  91871. var caps = engine.getCaps();
  91872. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  91873. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  91874. texture.generateMipMaps = true;
  91875. engine.updateTextureSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE, texture);
  91876. // Add extra process if texture lod is not supported
  91877. if (!caps.textureLOD) {
  91878. expandTexture = false;
  91879. generateNonLODTextures = true;
  91880. lodTextures = {};
  91881. }
  91882. // in webgl 1 there are no ways to either render or copy lod level information for float textures.
  91883. else if (engine.webGLVersion < 2) {
  91884. expandTexture = false;
  91885. }
  91886. // If half float available we can uncompress the texture
  91887. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  91888. expandTexture = true;
  91889. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  91890. }
  91891. // If full float available we can uncompress the texture
  91892. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  91893. expandTexture = true;
  91894. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  91895. }
  91896. // Expand the texture if possible
  91897. if (expandTexture) {
  91898. // Simply run through the decode PP
  91899. rgbdPostProcess = new BABYLON.PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);
  91900. texture._isRGBD = false;
  91901. texture.invertY = false;
  91902. cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
  91903. generateDepthBuffer: false,
  91904. generateMipMaps: true,
  91905. generateStencilBuffer: false,
  91906. samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
  91907. type: texture.type,
  91908. format: BABYLON.Engine.TEXTUREFORMAT_RGBA
  91909. });
  91910. }
  91911. else {
  91912. texture._isRGBD = true;
  91913. texture.invertY = true;
  91914. // In case of missing support, applies the same patch than DDS files.
  91915. if (generateNonLODTextures) {
  91916. var mipSlices = 3;
  91917. var scale = texture._lodGenerationScale;
  91918. var offset = texture._lodGenerationOffset;
  91919. for (var i = 0; i < mipSlices; i++) {
  91920. //compute LOD from even spacing in smoothness (matching shader calculation)
  91921. var smoothness = i / (mipSlices - 1);
  91922. var roughness = 1 - smoothness;
  91923. var minLODIndex = offset; // roughness = 0
  91924. var maxLODIndex = (mipmapsCount - 1) * scale + offset; // roughness = 1 (mipmaps start from 0)
  91925. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  91926. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  91927. var glTextureFromLod = new BABYLON.InternalTexture(engine, BABYLON.InternalTexture.DATASOURCE_TEMP);
  91928. glTextureFromLod.isCube = true;
  91929. glTextureFromLod.invertY = true;
  91930. glTextureFromLod.generateMipMaps = false;
  91931. engine.updateTextureSamplingMode(BABYLON.Texture.LINEAR_LINEAR, glTextureFromLod);
  91932. // Wrap in a base texture for easy binding.
  91933. var lodTexture = new BABYLON.BaseTexture(null);
  91934. lodTexture.isCube = true;
  91935. lodTexture._texture = glTextureFromLod;
  91936. lodTextures[mipmapIndex] = lodTexture;
  91937. switch (i) {
  91938. case 0:
  91939. texture._lodTextureLow = lodTexture;
  91940. break;
  91941. case 1:
  91942. texture._lodTextureMid = lodTexture;
  91943. break;
  91944. case 2:
  91945. texture._lodTextureHigh = lodTexture;
  91946. break;
  91947. }
  91948. }
  91949. }
  91950. }
  91951. var promises = [];
  91952. var _loop_3 = function (i) {
  91953. var _loop_4 = function (face) {
  91954. // Constructs an image element from image data
  91955. var bytes = imageData[i][face];
  91956. var blob = new Blob([bytes], { type: 'image/png' });
  91957. var url = URL.createObjectURL(blob);
  91958. var image = new Image();
  91959. image.src = url;
  91960. // Enqueue promise to upload to the texture.
  91961. var promise = new Promise(function (resolve, reject) {
  91962. image.onload = function () {
  91963. if (expandTexture) {
  91964. var tempTexture_1 = engine.createTexture(null, true, true, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, function (message) {
  91965. reject(message);
  91966. }, image);
  91967. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  91968. // Uncompress the data to a RTT
  91969. rgbdPostProcess.onApply = function (effect) {
  91970. effect._bindTexture("textureSampler", tempTexture_1);
  91971. effect.setFloat2("scale", 1, 1);
  91972. };
  91973. engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);
  91974. // Cleanup
  91975. engine.restoreDefaultFramebuffer();
  91976. tempTexture_1.dispose();
  91977. window.URL.revokeObjectURL(url);
  91978. resolve();
  91979. });
  91980. }
  91981. else {
  91982. engine._uploadImageToTexture(texture, image, face, i);
  91983. // Upload the face to the non lod texture support
  91984. if (generateNonLODTextures) {
  91985. var lodTexture = lodTextures[i];
  91986. if (lodTexture) {
  91987. engine._uploadImageToTexture(lodTexture._texture, image, face, 0);
  91988. }
  91989. }
  91990. resolve();
  91991. }
  91992. };
  91993. image.onerror = function (error) {
  91994. reject(error);
  91995. };
  91996. });
  91997. promises.push(promise);
  91998. };
  91999. // All faces
  92000. for (var face = 0; face < 6; face++) {
  92001. _loop_4(face);
  92002. }
  92003. };
  92004. // All mipmaps up to provided number of images
  92005. for (var i = 0; i < imageData.length; i++) {
  92006. _loop_3(i);
  92007. }
  92008. // Fill remaining mipmaps with black textures.
  92009. if (imageData.length < mipmapsCount) {
  92010. var data = void 0;
  92011. var size = Math.pow(2, mipmapsCount - 1 - imageData.length);
  92012. var dataLength = size * size * 4;
  92013. switch (texture.type) {
  92014. case BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT: {
  92015. data = new Uint8Array(dataLength);
  92016. break;
  92017. }
  92018. case BABYLON.Engine.TEXTURETYPE_HALF_FLOAT: {
  92019. data = new Uint16Array(dataLength);
  92020. break;
  92021. }
  92022. case BABYLON.Engine.TEXTURETYPE_FLOAT: {
  92023. data = new Float32Array(dataLength);
  92024. break;
  92025. }
  92026. }
  92027. for (var i = imageData.length; i < mipmapsCount; i++) {
  92028. for (var face = 0; face < 6; face++) {
  92029. engine._uploadArrayBufferViewToTexture(texture, data, face, i);
  92030. }
  92031. }
  92032. }
  92033. // Once all done, finishes the cleanup and return
  92034. return Promise.all(promises).then(function () {
  92035. // Release temp RTT.
  92036. if (cubeRtt) {
  92037. engine._releaseFramebufferObjects(cubeRtt);
  92038. cubeRtt._swapAndDie(texture);
  92039. }
  92040. // Release temp Post Process.
  92041. if (rgbdPostProcess) {
  92042. rgbdPostProcess.dispose();
  92043. }
  92044. // Flag internal texture as ready in case they are in use.
  92045. if (generateNonLODTextures) {
  92046. if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
  92047. texture._lodTextureHigh._texture.isReady = true;
  92048. }
  92049. if (texture._lodTextureMid && texture._lodTextureMid._texture) {
  92050. texture._lodTextureMid._texture.isReady = true;
  92051. }
  92052. if (texture._lodTextureLow && texture._lodTextureLow._texture) {
  92053. texture._lodTextureLow._texture.isReady = true;
  92054. }
  92055. }
  92056. });
  92057. };
  92058. /**
  92059. * Uploads spherical polynomials information to the texture.
  92060. * @param texture defines the texture we are trying to upload the information to
  92061. * @param info defines the environment texture info retrieved through the GetEnvInfo method
  92062. */
  92063. EnvironmentTextureTools.UploadEnvSpherical = function (texture, info) {
  92064. if (info.version !== 1) {
  92065. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  92066. }
  92067. var irradianceInfo = info.irradiance;
  92068. if (!irradianceInfo) {
  92069. return;
  92070. }
  92071. var sp = new BABYLON.SphericalPolynomial();
  92072. BABYLON.Vector3.FromArrayToRef(irradianceInfo.x, 0, sp.x);
  92073. BABYLON.Vector3.FromArrayToRef(irradianceInfo.y, 0, sp.y);
  92074. BABYLON.Vector3.FromArrayToRef(irradianceInfo.z, 0, sp.z);
  92075. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xx, 0, sp.xx);
  92076. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yy, 0, sp.yy);
  92077. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zz, 0, sp.zz);
  92078. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yz, 0, sp.yz);
  92079. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zx, 0, sp.zx);
  92080. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xy, 0, sp.xy);
  92081. texture._sphericalPolynomial = sp;
  92082. };
  92083. /**
  92084. * Magic number identifying the env file.
  92085. */
  92086. EnvironmentTextureTools._MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  92087. return EnvironmentTextureTools;
  92088. }());
  92089. BABYLON.EnvironmentTextureTools = EnvironmentTextureTools;
  92090. })(BABYLON || (BABYLON = {}));
  92091. //# sourceMappingURL=babylon.environmentTextureTools.js.map
  92092. var BABYLON;
  92093. (function (BABYLON) {
  92094. /**
  92095. * Implementation of the ENV Texture Loader.
  92096. */
  92097. var ENVTextureLoader = /** @class */ (function () {
  92098. function ENVTextureLoader() {
  92099. /**
  92100. * Defines wether the loader supports cascade loading the different faces.
  92101. */
  92102. this.supportCascades = false;
  92103. }
  92104. /**
  92105. * This returns if the loader support the current file information.
  92106. * @param extension defines the file extension of the file being loaded
  92107. * @param textureFormatInUse defines the current compressed format in use iun the engine
  92108. * @param fallback defines the fallback internal texture if any
  92109. * @param isBase64 defines whether the texture is encoded as a base64
  92110. * @param isBuffer defines whether the texture data are stored as a buffer
  92111. * @returns true if the loader can load the specified file
  92112. */
  92113. ENVTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  92114. return extension.indexOf(".env") === 0;
  92115. };
  92116. /**
  92117. * Transform the url before loading if required.
  92118. * @param rootUrl the url of the texture
  92119. * @param textureFormatInUse defines the current compressed format in use iun the engine
  92120. * @returns the transformed texture
  92121. */
  92122. ENVTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  92123. return rootUrl;
  92124. };
  92125. /**
  92126. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  92127. * @param rootUrl the url of the texture
  92128. * @param textureFormatInUse defines the current compressed format in use iun the engine
  92129. * @returns the fallback texture
  92130. */
  92131. ENVTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  92132. return null;
  92133. };
  92134. /**
  92135. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  92136. * @param data contains the texture data
  92137. * @param texture defines the BabylonJS internal texture
  92138. * @param createPolynomials will be true if polynomials have been requested
  92139. * @param onLoad defines the callback to trigger once the texture is ready
  92140. * @param onError defines the callback to trigger in case of error
  92141. */
  92142. ENVTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  92143. if (Array.isArray(data)) {
  92144. return;
  92145. }
  92146. data = data;
  92147. var info = BABYLON.EnvironmentTextureTools.GetEnvInfo(data);
  92148. if (info) {
  92149. texture.width = info.width;
  92150. texture.height = info.width;
  92151. BABYLON.EnvironmentTextureTools.UploadEnvSpherical(texture, info);
  92152. BABYLON.EnvironmentTextureTools.UploadEnvLevelsAsync(texture, data, info).then(function () {
  92153. texture.isReady = true;
  92154. if (onLoad) {
  92155. onLoad();
  92156. }
  92157. });
  92158. }
  92159. else if (onError) {
  92160. onError("Can not parse the environment file", null);
  92161. }
  92162. };
  92163. /**
  92164. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  92165. * @param data contains the texture data
  92166. * @param texture defines the BabylonJS internal texture
  92167. * @param callback defines the method to call once ready to upload
  92168. */
  92169. ENVTextureLoader.prototype.loadData = function (data, texture, callback) {
  92170. throw ".env not supported in 2d.";
  92171. };
  92172. return ENVTextureLoader;
  92173. }());
  92174. // Register the loader.
  92175. BABYLON.Engine._TextureLoaders.push(new ENVTextureLoader());
  92176. })(BABYLON || (BABYLON = {}));
  92177. //# sourceMappingURL=babylon.envTextureLoader.js.map
  92178. var BABYLON;
  92179. (function (BABYLON) {
  92180. /**
  92181. * Renders a layer on top of an existing scene
  92182. */
  92183. var UtilityLayerRenderer = /** @class */ (function () {
  92184. /**
  92185. * Instantiates a UtilityLayerRenderer
  92186. * @param originalScene the original scene that will be rendered on top of
  92187. */
  92188. function UtilityLayerRenderer(
  92189. /** the original scene that will be rendered on top of */
  92190. originalScene) {
  92191. var _this = this;
  92192. this.originalScene = originalScene;
  92193. this._pointerCaptures = {};
  92194. this._lastPointerEvents = {};
  92195. /**
  92196. * If the utility layer should automatically be rendered on top of existing scene
  92197. */
  92198. this.shouldRender = true;
  92199. /**
  92200. * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene
  92201. */
  92202. this.onlyCheckPointerDownEvents = true;
  92203. /**
  92204. * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)
  92205. */
  92206. this.processAllEvents = false;
  92207. /**
  92208. * Observable raised when the pointer move from the utility layer scene to the main scene
  92209. */
  92210. this.onPointerOutObservable = new BABYLON.Observable();
  92211. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  92212. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  92213. this.utilityLayerScene._allowPostProcessClearColor = false;
  92214. originalScene.getEngine().scenes.pop();
  92215. // Detach controls on utility scene, events will be fired by logic below to handle picking priority
  92216. this.utilityLayerScene.detachControl();
  92217. this._originalPointerObserver = originalScene.onPrePointerObservable.add(function (prePointerInfo, eventState) {
  92218. if (!_this.processAllEvents) {
  92219. if (prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERMOVE
  92220. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERUP
  92221. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERDOWN) {
  92222. return;
  92223. }
  92224. }
  92225. var pointerEvent = (prePointerInfo.event);
  92226. if (originalScene.isPointerCaptured(pointerEvent.pointerId)) {
  92227. _this._pointerCaptures[pointerEvent.pointerId] = false;
  92228. return;
  92229. }
  92230. var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);
  92231. if (!prePointerInfo.ray && utilityScenePick) {
  92232. prePointerInfo.ray = utilityScenePick.ray;
  92233. }
  92234. // always fire the prepointer oversvable
  92235. _this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);
  92236. // allow every non pointer down event to flow to the utility layer
  92237. if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON.PointerEventTypes.POINTERDOWN) {
  92238. if (!prePointerInfo.skipOnPointerObservable) {
  92239. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  92240. }
  92241. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
  92242. _this._pointerCaptures[pointerEvent.pointerId] = false;
  92243. }
  92244. return;
  92245. }
  92246. if (_this.utilityLayerScene.autoClearDepthAndStencil) {
  92247. // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene
  92248. if (utilityScenePick && utilityScenePick.hit) {
  92249. if (!prePointerInfo.skipOnPointerObservable) {
  92250. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  92251. }
  92252. prePointerInfo.skipOnPointerObservable = true;
  92253. }
  92254. }
  92255. else {
  92256. var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);
  92257. var pointerEvent_1 = (prePointerInfo.event);
  92258. // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray
  92259. if (originalScenePick && utilityScenePick) {
  92260. // No pick in utility scene
  92261. if (utilityScenePick.distance === 0 && originalScenePick.pickedMesh) {
  92262. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  92263. // We touched an utility mesh present in the main scene
  92264. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  92265. prePointerInfo.skipOnPointerObservable = true;
  92266. }
  92267. else if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  92268. _this._pointerCaptures[pointerEvent_1.pointerId] = true;
  92269. }
  92270. }
  92271. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {
  92272. // We pick something in utility scene or the pick in utility is closer than the one in main scene
  92273. _this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent_1);
  92274. // If a previous utility layer set this, do not unset this
  92275. if (!prePointerInfo.skipOnPointerObservable) {
  92276. prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;
  92277. }
  92278. }
  92279. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance > originalScenePick.distance)) {
  92280. // We have a pick in both scenes but main is closer than utility
  92281. // We touched an utility mesh present in the main scene
  92282. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  92283. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  92284. prePointerInfo.skipOnPointerObservable = true;
  92285. }
  92286. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  92287. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  92288. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  92289. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  92290. }
  92291. }
  92292. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent_1.pointerId]) {
  92293. _this._pointerCaptures[pointerEvent_1.pointerId] = false;
  92294. }
  92295. }
  92296. }
  92297. });
  92298. // Render directly on top of existing scene without clearing
  92299. this.utilityLayerScene.autoClear = false;
  92300. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  92301. if (_this.shouldRender) {
  92302. _this.render();
  92303. }
  92304. });
  92305. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  92306. _this.dispose();
  92307. });
  92308. this._updateCamera();
  92309. }
  92310. Object.defineProperty(UtilityLayerRenderer, "DefaultUtilityLayer", {
  92311. /**
  92312. * 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)
  92313. */
  92314. get: function () {
  92315. if (UtilityLayerRenderer._DefaultUtilityLayer == null) {
  92316. UtilityLayerRenderer._DefaultUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  92317. UtilityLayerRenderer._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  92318. UtilityLayerRenderer._DefaultUtilityLayer = null;
  92319. });
  92320. }
  92321. return UtilityLayerRenderer._DefaultUtilityLayer;
  92322. },
  92323. enumerable: true,
  92324. configurable: true
  92325. });
  92326. Object.defineProperty(UtilityLayerRenderer, "DefaultKeepDepthUtilityLayer", {
  92327. /**
  92328. * 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)
  92329. */
  92330. get: function () {
  92331. if (UtilityLayerRenderer._DefaultKeepDepthUtilityLayer == null) {
  92332. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  92333. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil = false;
  92334. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  92335. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  92336. });
  92337. }
  92338. return UtilityLayerRenderer._DefaultKeepDepthUtilityLayer;
  92339. },
  92340. enumerable: true,
  92341. configurable: true
  92342. });
  92343. UtilityLayerRenderer.prototype._notifyObservers = function (prePointerInfo, pickInfo, pointerEvent) {
  92344. if (!prePointerInfo.skipOnPointerObservable) {
  92345. this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, pickInfo));
  92346. this._lastPointerEvents[pointerEvent.pointerId] = parseInt(pointerEvent.pointerType);
  92347. }
  92348. };
  92349. /**
  92350. * Renders the utility layers scene on top of the original scene
  92351. */
  92352. UtilityLayerRenderer.prototype.render = function () {
  92353. this._updateCamera();
  92354. if (this.utilityLayerScene.activeCamera) {
  92355. // Set the camera's scene to utility layers scene
  92356. var oldScene = this.utilityLayerScene.activeCamera.getScene();
  92357. var camera = this.utilityLayerScene.activeCamera;
  92358. camera._scene = this.utilityLayerScene;
  92359. if (camera.leftCamera) {
  92360. camera.leftCamera._scene = this.utilityLayerScene;
  92361. }
  92362. if (camera.rightCamera) {
  92363. camera.rightCamera._scene = this.utilityLayerScene;
  92364. }
  92365. this.utilityLayerScene.render(false);
  92366. // Reset camera's scene back to original
  92367. camera._scene = oldScene;
  92368. if (camera.leftCamera) {
  92369. camera.leftCamera._scene = oldScene;
  92370. }
  92371. if (camera.rightCamera) {
  92372. camera.rightCamera._scene = oldScene;
  92373. }
  92374. }
  92375. };
  92376. /**
  92377. * Disposes of the renderer
  92378. */
  92379. UtilityLayerRenderer.prototype.dispose = function () {
  92380. this.onPointerOutObservable.clear();
  92381. if (this._afterRenderObserver) {
  92382. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  92383. }
  92384. if (this._sceneDisposeObserver) {
  92385. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  92386. }
  92387. if (this._originalPointerObserver) {
  92388. this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);
  92389. }
  92390. this.utilityLayerScene.dispose();
  92391. };
  92392. UtilityLayerRenderer.prototype._updateCamera = function () {
  92393. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  92394. };
  92395. UtilityLayerRenderer._DefaultUtilityLayer = null;
  92396. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  92397. return UtilityLayerRenderer;
  92398. }());
  92399. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  92400. })(BABYLON || (BABYLON = {}));
  92401. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  92402. //# sourceMappingURL=babylon.behavior.js.map
  92403. var BABYLON;
  92404. (function (BABYLON) {
  92405. /**
  92406. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  92407. */
  92408. var PointerDragBehavior = /** @class */ (function () {
  92409. /**
  92410. * Creates a pointer drag behavior that can be attached to a mesh
  92411. * @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)
  92412. */
  92413. function PointerDragBehavior(options) {
  92414. /**
  92415. * 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)
  92416. */
  92417. this.maxDragAngle = 0;
  92418. /**
  92419. * @hidden
  92420. */
  92421. this._useAlternatePickedPointAboveMaxDragAngle = false;
  92422. /**
  92423. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  92424. */
  92425. this.currentDraggingPointerID = -1;
  92426. /**
  92427. * If the behavior is currently in a dragging state
  92428. */
  92429. this.dragging = false;
  92430. /**
  92431. * 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)
  92432. */
  92433. this.dragDeltaRatio = 0.2;
  92434. /**
  92435. * If the drag plane orientation should be updated during the dragging (Default: true)
  92436. */
  92437. this.updateDragPlane = true;
  92438. // Debug mode will display drag planes to help visualize behavior
  92439. this._debugMode = false;
  92440. this._moving = false;
  92441. /**
  92442. * Fires each time the attached mesh is dragged with the pointer
  92443. * * delta between last drag position and current drag position in world space
  92444. * * dragDistance along the drag axis
  92445. * * dragPlaneNormal normal of the current drag plane used during the drag
  92446. * * dragPlanePoint in world space where the drag intersects the drag plane
  92447. */
  92448. this.onDragObservable = new BABYLON.Observable();
  92449. /**
  92450. * Fires each time a drag begins (eg. mouse down on mesh)
  92451. */
  92452. this.onDragStartObservable = new BABYLON.Observable();
  92453. /**
  92454. * Fires each time a drag ends (eg. mouse release after drag)
  92455. */
  92456. this.onDragEndObservable = new BABYLON.Observable();
  92457. /**
  92458. * If the attached mesh should be moved when dragged
  92459. */
  92460. this.moveAttached = true;
  92461. /**
  92462. * If the drag behavior will react to drag events (Default: true)
  92463. */
  92464. this.enabled = true;
  92465. /**
  92466. * If camera controls should be detached during the drag
  92467. */
  92468. this.detachCameraControls = true;
  92469. /**
  92470. * If set, the drag plane/axis will be rotated based on the attached mesh's world rotation (Default: true)
  92471. */
  92472. this.useObjectOrienationForDragging = true;
  92473. this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  92474. this._alternatePickedPoint = new BABYLON.Vector3(0, 0, 0);
  92475. this._worldDragAxis = new BABYLON.Vector3(0, 0, 0);
  92476. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  92477. this._attachedElement = null;
  92478. this._startDragRay = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  92479. this._lastPointerRay = {};
  92480. this._dragDelta = new BABYLON.Vector3();
  92481. // Variables to avoid instantiation in the below method
  92482. this._pointA = new BABYLON.Vector3(0, 0, 0);
  92483. this._pointB = new BABYLON.Vector3(0, 0, 0);
  92484. this._pointC = new BABYLON.Vector3(0, 0, 0);
  92485. this._lineA = new BABYLON.Vector3(0, 0, 0);
  92486. this._lineB = new BABYLON.Vector3(0, 0, 0);
  92487. this._localAxis = new BABYLON.Vector3(0, 0, 0);
  92488. this._lookAt = new BABYLON.Vector3(0, 0, 0);
  92489. this._options = options ? options : {};
  92490. var optionCount = 0;
  92491. if (this._options.dragAxis) {
  92492. optionCount++;
  92493. }
  92494. if (this._options.dragPlaneNormal) {
  92495. optionCount++;
  92496. }
  92497. if (optionCount > 1) {
  92498. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  92499. }
  92500. }
  92501. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  92502. /**
  92503. * The name of the behavior
  92504. */
  92505. get: function () {
  92506. return "PointerDrag";
  92507. },
  92508. enumerable: true,
  92509. configurable: true
  92510. });
  92511. /**
  92512. * Initializes the behavior
  92513. */
  92514. PointerDragBehavior.prototype.init = function () { };
  92515. /**
  92516. * Attaches the drag behavior the passed in mesh
  92517. * @param ownerNode The mesh that will be dragged around once attached
  92518. */
  92519. PointerDragBehavior.prototype.attach = function (ownerNode) {
  92520. var _this = this;
  92521. this._scene = ownerNode.getScene();
  92522. this._attachedNode = ownerNode;
  92523. // Initialize drag plane to not interfere with existing scene
  92524. if (!PointerDragBehavior._planeScene) {
  92525. if (this._debugMode) {
  92526. PointerDragBehavior._planeScene = this._scene;
  92527. }
  92528. else {
  92529. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  92530. PointerDragBehavior._planeScene.detachControl();
  92531. this._scene.getEngine().scenes.pop();
  92532. this._scene.onDisposeObservable.addOnce(function () {
  92533. PointerDragBehavior._planeScene.dispose();
  92534. PointerDragBehavior._planeScene = null;
  92535. });
  92536. }
  92537. }
  92538. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", this._debugMode ? 1 : 10000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  92539. // State of the drag
  92540. this.lastDragPosition = new BABYLON.Vector3(0, 0, 0);
  92541. var pickPredicate = function (m) {
  92542. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  92543. };
  92544. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  92545. if (!_this.enabled) {
  92546. return;
  92547. }
  92548. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  92549. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.pickedPoint && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  92550. _this._startDrag(pointerInfo.event.pointerId, pointerInfo.pickInfo.ray, pointerInfo.pickInfo.pickedPoint);
  92551. }
  92552. }
  92553. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  92554. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  92555. _this.releaseDrag();
  92556. }
  92557. }
  92558. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  92559. var pointerId = pointerInfo.event.pointerId;
  92560. // Keep track of last pointer ray, this is used simulating the start of a drag in startDrag()
  92561. if (!_this._lastPointerRay[pointerId]) {
  92562. _this._lastPointerRay[pointerId] = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  92563. }
  92564. if (pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  92565. _this._lastPointerRay[pointerId].origin.copyFrom(pointerInfo.pickInfo.ray.origin);
  92566. _this._lastPointerRay[pointerId].direction.copyFrom(pointerInfo.pickInfo.ray.direction);
  92567. if (_this.currentDraggingPointerID == pointerId && _this.dragging) {
  92568. _this._moveDrag(pointerInfo.pickInfo.ray);
  92569. }
  92570. }
  92571. }
  92572. });
  92573. this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  92574. if (_this._moving && _this.moveAttached) {
  92575. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(_this._attachedNode);
  92576. // Slowly move mesh to avoid jitter
  92577. _this._targetPosition.subtractToRef((_this._attachedNode).absolutePosition, _this._tmpVector);
  92578. _this._tmpVector.scaleInPlace(_this.dragDeltaRatio);
  92579. (_this._attachedNode).getAbsolutePosition().addToRef(_this._tmpVector, _this._tmpVector);
  92580. (_this._attachedNode).setAbsolutePosition(_this._tmpVector);
  92581. BABYLON.BoundingBoxGizmo._RestorePivotPoint(_this._attachedNode);
  92582. }
  92583. });
  92584. };
  92585. PointerDragBehavior.prototype.releaseDrag = function () {
  92586. this.dragging = false;
  92587. this.onDragEndObservable.notifyObservers({ dragPlanePoint: this.lastDragPosition, pointerId: this.currentDraggingPointerID });
  92588. this.currentDraggingPointerID = -1;
  92589. this._moving = false;
  92590. // Reattach camera controls
  92591. if (this.detachCameraControls && this._attachedElement && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
  92592. this._scene.activeCamera.attachControl(this._attachedElement, true);
  92593. }
  92594. };
  92595. /**
  92596. * Simulates the start of a pointer drag event on the behavior
  92597. * @param pointerId pointerID of the pointer that should be simulated (Default: 1 for mouse pointer)
  92598. * @param fromRay initial ray of the pointer to be simulated (Default: Ray from camera to attached mesh)
  92599. * @param startPickedPoint picked point of the pointer to be simulated (Default: attached mesh position)
  92600. */
  92601. PointerDragBehavior.prototype.startDrag = function (pointerId, fromRay, startPickedPoint) {
  92602. if (pointerId === void 0) { pointerId = 1; }
  92603. this._startDrag(pointerId, fromRay, startPickedPoint);
  92604. if (this._lastPointerRay[pointerId]) {
  92605. // if there was a last pointer ray drag the object there
  92606. this._moveDrag(this._lastPointerRay[pointerId]);
  92607. }
  92608. };
  92609. PointerDragBehavior.prototype._startDrag = function (pointerId, fromRay, startPickedPoint) {
  92610. if (pointerId === void 0) { pointerId = 1; }
  92611. if (!this._scene.activeCamera || this.dragging || !this._attachedNode) {
  92612. return;
  92613. }
  92614. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(this._attachedNode);
  92615. // Create start ray from the camera to the object
  92616. if (fromRay) {
  92617. this._startDragRay.direction.copyFrom(fromRay.direction);
  92618. this._startDragRay.origin.copyFrom(fromRay.origin);
  92619. }
  92620. else {
  92621. this._startDragRay.origin.copyFrom(this._scene.activeCamera.position);
  92622. this._attachedNode.getWorldMatrix().getTranslationToRef(this._tmpVector);
  92623. this._tmpVector.subtractToRef(this._scene.activeCamera.position, this._startDragRay.direction);
  92624. }
  92625. this._updateDragPlanePosition(this._startDragRay, startPickedPoint ? startPickedPoint : this._tmpVector);
  92626. var pickedPoint = this._pickWithRayOnDragPlane(this._startDragRay);
  92627. if (pickedPoint) {
  92628. this.dragging = true;
  92629. this.currentDraggingPointerID = pointerId;
  92630. this.lastDragPosition.copyFrom(pickedPoint);
  92631. this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint, pointerId: this.currentDraggingPointerID });
  92632. this._targetPosition.copyFrom((this._attachedNode).absolutePosition);
  92633. // Detatch camera controls
  92634. if (this.detachCameraControls && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
  92635. if (this._scene.activeCamera.inputs.attachedElement) {
  92636. this._attachedElement = this._scene.activeCamera.inputs.attachedElement;
  92637. this._scene.activeCamera.detachControl(this._scene.activeCamera.inputs.attachedElement);
  92638. }
  92639. else {
  92640. this._attachedElement = null;
  92641. }
  92642. }
  92643. }
  92644. BABYLON.BoundingBoxGizmo._RestorePivotPoint(this._attachedNode);
  92645. };
  92646. PointerDragBehavior.prototype._moveDrag = function (ray) {
  92647. this._moving = true;
  92648. var pickedPoint = this._pickWithRayOnDragPlane(ray);
  92649. if (pickedPoint) {
  92650. if (this.updateDragPlane) {
  92651. this._updateDragPlanePosition(ray, pickedPoint);
  92652. }
  92653. var dragLength = 0;
  92654. // depending on the drag mode option drag accordingly
  92655. if (this._options.dragAxis) {
  92656. // Convert local drag axis to world
  92657. BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._worldDragAxis);
  92658. // Project delta drag from the drag plane onto the drag axis
  92659. pickedPoint.subtractToRef(this.lastDragPosition, this._tmpVector);
  92660. dragLength = BABYLON.Vector3.Dot(this._tmpVector, this._worldDragAxis);
  92661. this._worldDragAxis.scaleToRef(dragLength, this._dragDelta);
  92662. }
  92663. else {
  92664. dragLength = this._dragDelta.length();
  92665. pickedPoint.subtractToRef(this.lastDragPosition, this._dragDelta);
  92666. }
  92667. this._targetPosition.addInPlace(this._dragDelta);
  92668. this.onDragObservable.notifyObservers({ dragDistance: dragLength, delta: this._dragDelta, dragPlanePoint: pickedPoint, dragPlaneNormal: this._dragPlane.forward, pointerId: this.currentDraggingPointerID });
  92669. this.lastDragPosition.copyFrom(pickedPoint);
  92670. }
  92671. };
  92672. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  92673. var _this = this;
  92674. if (!ray) {
  92675. return null;
  92676. }
  92677. // Calculate angle between plane normal and ray
  92678. var angle = Math.acos(BABYLON.Vector3.Dot(this._dragPlane.forward, ray.direction));
  92679. // Correct if ray is casted from oposite side
  92680. if (angle > Math.PI / 2) {
  92681. angle = Math.PI - angle;
  92682. }
  92683. // If the angle is too perpendicular to the plane pick another point on the plane where it is looking
  92684. if (this.maxDragAngle > 0 && angle > this.maxDragAngle) {
  92685. if (this._useAlternatePickedPointAboveMaxDragAngle) {
  92686. // Invert ray direction along the towards object axis
  92687. this._tmpVector.copyFrom(ray.direction);
  92688. (this._attachedNode).absolutePosition.subtractToRef(ray.origin, this._alternatePickedPoint);
  92689. this._alternatePickedPoint.normalize();
  92690. this._alternatePickedPoint.scaleInPlace(-2 * BABYLON.Vector3.Dot(this._alternatePickedPoint, this._tmpVector));
  92691. this._tmpVector.addInPlace(this._alternatePickedPoint);
  92692. // Project resulting vector onto the drag plane and add it to the attached nodes absolute position to get a picked point
  92693. var dot = BABYLON.Vector3.Dot(this._dragPlane.forward, this._tmpVector);
  92694. this._dragPlane.forward.scaleToRef(-dot, this._alternatePickedPoint);
  92695. this._alternatePickedPoint.addInPlace(this._tmpVector);
  92696. this._alternatePickedPoint.addInPlace((this._attachedNode).absolutePosition);
  92697. return this._alternatePickedPoint;
  92698. }
  92699. else {
  92700. return null;
  92701. }
  92702. }
  92703. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  92704. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  92705. return pickResult.pickedPoint;
  92706. }
  92707. else {
  92708. return null;
  92709. }
  92710. };
  92711. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  92712. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray, dragPlanePosition) {
  92713. this._pointA.copyFrom(dragPlanePosition);
  92714. if (this._options.dragAxis) {
  92715. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragAxis);
  92716. // Calculate plane normal in direction of camera but perpendicular to drag axis
  92717. this._pointA.addToRef(this._localAxis, this._pointB); // towards drag axis
  92718. ray.origin.subtractToRef(this._pointA, this._pointC);
  92719. this._pointA.addToRef(this._pointC.normalize(), this._pointC); // towards camera
  92720. // Get perpendicular line from direction to camera and drag axis
  92721. this._pointB.subtractToRef(this._pointA, this._lineA);
  92722. this._pointC.subtractToRef(this._pointA, this._lineB);
  92723. BABYLON.Vector3.CrossToRef(this._lineA, this._lineB, this._lookAt);
  92724. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  92725. BABYLON.Vector3.CrossToRef(this._lineA, this._lookAt, this._lookAt);
  92726. this._lookAt.normalize();
  92727. this._dragPlane.position.copyFrom(this._pointA);
  92728. this._pointA.subtractToRef(this._lookAt, this._lookAt);
  92729. this._dragPlane.lookAt(this._lookAt);
  92730. }
  92731. else if (this._options.dragPlaneNormal) {
  92732. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragPlaneNormal, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragPlaneNormal);
  92733. this._dragPlane.position.copyFrom(this._pointA);
  92734. this._pointA.subtractToRef(this._localAxis, this._lookAt);
  92735. this._dragPlane.lookAt(this._lookAt);
  92736. }
  92737. else {
  92738. this._dragPlane.position.copyFrom(this._pointA);
  92739. this._dragPlane.lookAt(ray.origin);
  92740. }
  92741. this._dragPlane.computeWorldMatrix(true);
  92742. };
  92743. /**
  92744. * Detaches the behavior from the mesh
  92745. */
  92746. PointerDragBehavior.prototype.detach = function () {
  92747. if (this._pointerObserver) {
  92748. this._scene.onPointerObservable.remove(this._pointerObserver);
  92749. }
  92750. if (this._beforeRenderObserver) {
  92751. this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  92752. }
  92753. };
  92754. return PointerDragBehavior;
  92755. }());
  92756. BABYLON.PointerDragBehavior = PointerDragBehavior;
  92757. })(BABYLON || (BABYLON = {}));
  92758. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  92759. var BABYLON;
  92760. (function (BABYLON) {
  92761. /**
  92762. * A behavior that when attached to a mesh will allow the mesh to be scaled
  92763. */
  92764. var MultiPointerScaleBehavior = /** @class */ (function () {
  92765. function MultiPointerScaleBehavior() {
  92766. this._startDistance = 0;
  92767. this._initialScale = new BABYLON.Vector3(0, 0, 0);
  92768. this._targetScale = new BABYLON.Vector3(0, 0, 0);
  92769. this._sceneRenderObserver = null;
  92770. this._dragBehaviorA = new BABYLON.PointerDragBehavior({});
  92771. this._dragBehaviorA.moveAttached = false;
  92772. this._dragBehaviorB = new BABYLON.PointerDragBehavior({});
  92773. this._dragBehaviorB.moveAttached = false;
  92774. }
  92775. Object.defineProperty(MultiPointerScaleBehavior.prototype, "name", {
  92776. /**
  92777. * The name of the behavior
  92778. */
  92779. get: function () {
  92780. return "MultiPointerScale";
  92781. },
  92782. enumerable: true,
  92783. configurable: true
  92784. });
  92785. /**
  92786. * Initializes the behavior
  92787. */
  92788. MultiPointerScaleBehavior.prototype.init = function () { };
  92789. MultiPointerScaleBehavior.prototype._getCurrentDistance = function () {
  92790. return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length();
  92791. };
  92792. /**
  92793. * Attaches the scale behavior the passed in mesh
  92794. * @param ownerNode The mesh that will be scaled around once attached
  92795. */
  92796. MultiPointerScaleBehavior.prototype.attach = function (ownerNode) {
  92797. var _this = this;
  92798. this._ownerNode = ownerNode;
  92799. // Create 2 drag behaviors such that each will only be triggered by a separate pointer
  92800. this._dragBehaviorA.onDragStartObservable.add(function (e) {
  92801. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  92802. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  92803. _this._dragBehaviorA.releaseDrag();
  92804. }
  92805. else {
  92806. _this._initialScale.copyFrom(ownerNode.scaling);
  92807. _this._startDistance = _this._getCurrentDistance();
  92808. }
  92809. }
  92810. });
  92811. this._dragBehaviorB.onDragStartObservable.add(function (e) {
  92812. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  92813. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  92814. _this._dragBehaviorB.releaseDrag();
  92815. }
  92816. else {
  92817. _this._initialScale.copyFrom(ownerNode.scaling);
  92818. _this._startDistance = _this._getCurrentDistance();
  92819. }
  92820. }
  92821. });
  92822. // Once both drag behaviors are active scale based on the distance between the two pointers
  92823. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  92824. behavior.onDragObservable.add(function () {
  92825. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  92826. var ratio = _this._getCurrentDistance() / _this._startDistance;
  92827. _this._initialScale.scaleToRef(ratio, _this._targetScale);
  92828. }
  92829. });
  92830. });
  92831. ownerNode.addBehavior(this._dragBehaviorA);
  92832. ownerNode.addBehavior(this._dragBehaviorB);
  92833. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  92834. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  92835. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  92836. var change = _this._targetScale.subtract(ownerNode.scaling).scaleInPlace(0.1);
  92837. if (change.length() > 0.01) {
  92838. ownerNode.scaling.addInPlace(change);
  92839. }
  92840. }
  92841. });
  92842. };
  92843. /**
  92844. * Detaches the behavior from the mesh
  92845. */
  92846. MultiPointerScaleBehavior.prototype.detach = function () {
  92847. var _this = this;
  92848. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  92849. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  92850. behavior.onDragStartObservable.clear();
  92851. behavior.onDragObservable.clear();
  92852. _this._ownerNode.removeBehavior(behavior);
  92853. });
  92854. };
  92855. return MultiPointerScaleBehavior;
  92856. }());
  92857. BABYLON.MultiPointerScaleBehavior = MultiPointerScaleBehavior;
  92858. })(BABYLON || (BABYLON = {}));
  92859. //# sourceMappingURL=babylon.multiPointerScaleBehavior.js.map
  92860. var BABYLON;
  92861. (function (BABYLON) {
  92862. /**
  92863. * 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
  92864. */
  92865. var SixDofDragBehavior = /** @class */ (function () {
  92866. function SixDofDragBehavior() {
  92867. this._sceneRenderObserver = null;
  92868. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  92869. this._moving = false;
  92870. this._startingOrientation = new BABYLON.Quaternion();
  92871. /**
  92872. * 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)
  92873. */
  92874. this.zDragFactor = 3;
  92875. /**
  92876. * If the behavior is currently in a dragging state
  92877. */
  92878. this.dragging = false;
  92879. /**
  92880. * 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)
  92881. */
  92882. this.dragDeltaRatio = 0.2;
  92883. /**
  92884. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  92885. */
  92886. this.currentDraggingPointerID = -1;
  92887. /**
  92888. * If camera controls should be detached during the drag
  92889. */
  92890. this.detachCameraControls = true;
  92891. }
  92892. Object.defineProperty(SixDofDragBehavior.prototype, "name", {
  92893. /**
  92894. * The name of the behavior
  92895. */
  92896. get: function () {
  92897. return "SixDofDrag";
  92898. },
  92899. enumerable: true,
  92900. configurable: true
  92901. });
  92902. /**
  92903. * Initializes the behavior
  92904. */
  92905. SixDofDragBehavior.prototype.init = function () { };
  92906. /**
  92907. * Attaches the scale behavior the passed in mesh
  92908. * @param ownerNode The mesh that will be scaled around once attached
  92909. */
  92910. SixDofDragBehavior.prototype.attach = function (ownerNode) {
  92911. var _this = this;
  92912. this._ownerNode = ownerNode;
  92913. this._scene = this._ownerNode.getScene();
  92914. if (!SixDofDragBehavior._virtualScene) {
  92915. SixDofDragBehavior._virtualScene = new BABYLON.Scene(this._scene.getEngine());
  92916. this._scene.getEngine().scenes.pop();
  92917. }
  92918. var pickedMesh = null;
  92919. var lastSixDofOriginPosition = new BABYLON.Vector3(0, 0, 0);
  92920. // Setup virtual meshes to be used for dragging without dirtying the existing scene
  92921. this._virtualOriginMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  92922. this._virtualOriginMesh.rotationQuaternion = new BABYLON.Quaternion();
  92923. this._virtualDragMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  92924. this._virtualDragMesh.rotationQuaternion = new BABYLON.Quaternion();
  92925. var pickPredicate = function (m) {
  92926. return _this._ownerNode == m || m.isDescendantOf(_this._ownerNode);
  92927. };
  92928. var attachedElement = null;
  92929. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  92930. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  92931. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  92932. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  92933. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  92934. }
  92935. pickedMesh = _this._ownerNode;
  92936. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(pickedMesh);
  92937. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  92938. // Set position and orientation of the controller
  92939. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  92940. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  92941. // Attach the virtual drag mesh to the virtual origin mesh so it can be dragged
  92942. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  92943. pickedMesh.computeWorldMatrix();
  92944. _this._virtualDragMesh.position.copyFrom(pickedMesh.absolutePosition);
  92945. if (!pickedMesh.rotationQuaternion) {
  92946. pickedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(pickedMesh.rotation.y, pickedMesh.rotation.x, pickedMesh.rotation.z);
  92947. }
  92948. var oldParent = pickedMesh.parent;
  92949. pickedMesh.setParent(null);
  92950. _this._virtualDragMesh.rotationQuaternion.copyFrom(pickedMesh.rotationQuaternion);
  92951. pickedMesh.setParent(oldParent);
  92952. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  92953. // Update state
  92954. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  92955. _this.dragging = true;
  92956. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  92957. // Detatch camera controls
  92958. if (_this.detachCameraControls && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  92959. if (_this._scene.activeCamera.inputs.attachedElement) {
  92960. attachedElement = _this._scene.activeCamera.inputs.attachedElement;
  92961. _this._scene.activeCamera.detachControl(_this._scene.activeCamera.inputs.attachedElement);
  92962. }
  92963. else {
  92964. attachedElement = null;
  92965. }
  92966. }
  92967. BABYLON.BoundingBoxGizmo._RestorePivotPoint(pickedMesh);
  92968. }
  92969. }
  92970. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  92971. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  92972. _this.dragging = false;
  92973. _this._moving = false;
  92974. _this.currentDraggingPointerID = -1;
  92975. pickedMesh = null;
  92976. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  92977. // Reattach camera controls
  92978. if (_this.detachCameraControls && attachedElement && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  92979. _this._scene.activeCamera.attachControl(attachedElement, true);
  92980. }
  92981. }
  92982. }
  92983. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  92984. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray && pickedMesh) {
  92985. var zDragFactor = _this.zDragFactor;
  92986. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  92987. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  92988. zDragFactor = 0;
  92989. }
  92990. // Calculate controller drag distance in controller space
  92991. var originDragDifference = pointerInfo.pickInfo.ray.origin.subtract(lastSixDofOriginPosition);
  92992. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  92993. var localOriginDragDifference = -BABYLON.Vector3.Dot(originDragDifference, pointerInfo.pickInfo.ray.direction);
  92994. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  92995. // Determine how much the controller moved to/away towards the dragged object and use this to move the object further when its further away
  92996. _this._virtualDragMesh.position.z -= _this._virtualDragMesh.position.z < 1 ? localOriginDragDifference * _this.zDragFactor : localOriginDragDifference * zDragFactor * _this._virtualDragMesh.position.z;
  92997. if (_this._virtualDragMesh.position.z < 0) {
  92998. _this._virtualDragMesh.position.z = 0;
  92999. }
  93000. // Update the controller position
  93001. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  93002. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  93003. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  93004. // Move the virtualObjectsPosition into the picked mesh's space if needed
  93005. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  93006. if (pickedMesh.parent) {
  93007. BABYLON.Vector3.TransformCoordinatesToRef(_this._targetPosition, BABYLON.Matrix.Invert(pickedMesh.parent.getWorldMatrix()), _this._targetPosition);
  93008. }
  93009. if (!_this._moving) {
  93010. _this._startingOrientation.copyFrom(_this._virtualDragMesh.rotationQuaternion);
  93011. }
  93012. _this._moving = true;
  93013. }
  93014. }
  93015. });
  93016. var tmpQuaternion = new BABYLON.Quaternion();
  93017. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  93018. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  93019. if (_this.dragging && _this._moving && pickedMesh) {
  93020. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(pickedMesh);
  93021. // Slowly move mesh to avoid jitter
  93022. pickedMesh.position.addInPlace(_this._targetPosition.subtract(pickedMesh.position).scale(_this.dragDeltaRatio));
  93023. // Get change in rotation
  93024. tmpQuaternion.copyFrom(_this._startingOrientation);
  93025. tmpQuaternion.x = -tmpQuaternion.x;
  93026. tmpQuaternion.y = -tmpQuaternion.y;
  93027. tmpQuaternion.z = -tmpQuaternion.z;
  93028. _this._virtualDragMesh.rotationQuaternion.multiplyToRef(tmpQuaternion, tmpQuaternion);
  93029. // Convert change in rotation to only y axis rotation
  93030. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpQuaternion.toEulerAngles("xyz").y, 0, 0, tmpQuaternion);
  93031. tmpQuaternion.multiplyToRef(_this._startingOrientation, tmpQuaternion);
  93032. // Slowly move mesh to avoid jitter
  93033. var oldParent = pickedMesh.parent;
  93034. pickedMesh.setParent(null);
  93035. BABYLON.Quaternion.SlerpToRef(pickedMesh.rotationQuaternion, tmpQuaternion, _this.dragDeltaRatio, pickedMesh.rotationQuaternion);
  93036. pickedMesh.setParent(oldParent);
  93037. BABYLON.BoundingBoxGizmo._RestorePivotPoint(pickedMesh);
  93038. }
  93039. });
  93040. };
  93041. /**
  93042. * Detaches the behavior from the mesh
  93043. */
  93044. SixDofDragBehavior.prototype.detach = function () {
  93045. if (this._scene) {
  93046. this._scene.onPointerObservable.remove(this._pointerObserver);
  93047. }
  93048. if (this._ownerNode) {
  93049. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  93050. }
  93051. if (this._virtualOriginMesh) {
  93052. this._virtualOriginMesh.dispose();
  93053. }
  93054. if (this._virtualDragMesh) {
  93055. this._virtualDragMesh.dispose();
  93056. }
  93057. };
  93058. return SixDofDragBehavior;
  93059. }());
  93060. BABYLON.SixDofDragBehavior = SixDofDragBehavior;
  93061. })(BABYLON || (BABYLON = {}));
  93062. //# sourceMappingURL=babylon.sixDofDragBehavior.js.map
  93063. var BABYLON;
  93064. (function (BABYLON) {
  93065. /**
  93066. * @hidden
  93067. */
  93068. var FaceDirectionInfo = /** @class */ (function () {
  93069. function FaceDirectionInfo(direction, rotatedDirection, diff, ignore) {
  93070. if (rotatedDirection === void 0) { rotatedDirection = new BABYLON.Vector3(); }
  93071. if (diff === void 0) { diff = 0; }
  93072. if (ignore === void 0) { ignore = false; }
  93073. this.direction = direction;
  93074. this.rotatedDirection = rotatedDirection;
  93075. this.diff = diff;
  93076. this.ignore = ignore;
  93077. }
  93078. return FaceDirectionInfo;
  93079. }());
  93080. /**
  93081. * A behavior that when attached to a mesh will will place a specified node on the meshes face pointing towards the camera
  93082. */
  93083. var AttachToBoxBehavior = /** @class */ (function () {
  93084. /**
  93085. * Creates the AttachToBoxBehavior, used to attach UI to the closest face of the box to a camera
  93086. * @param ui The transform node that should be attched to the mesh
  93087. */
  93088. function AttachToBoxBehavior(ui) {
  93089. this.ui = ui;
  93090. /**
  93091. * The name of the behavior
  93092. */
  93093. this.name = "AttachToBoxBehavior";
  93094. /**
  93095. * The distance away from the face of the mesh that the UI should be attached to (default: 0.15)
  93096. */
  93097. this.distanceAwayFromFace = 0.15;
  93098. /**
  93099. * The distance from the bottom of the face that the UI should be attached to (default: 0.15)
  93100. */
  93101. this.distanceAwayFromBottomOfFace = 0.15;
  93102. 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))];
  93103. this._tmpMatrix = new BABYLON.Matrix();
  93104. this._tmpVector = new BABYLON.Vector3();
  93105. this._zeroVector = BABYLON.Vector3.Zero();
  93106. this._lookAtTmpMatrix = new BABYLON.Matrix();
  93107. /* Does nothing */
  93108. }
  93109. /**
  93110. * Initializes the behavior
  93111. */
  93112. AttachToBoxBehavior.prototype.init = function () {
  93113. /* Does nothing */
  93114. };
  93115. AttachToBoxBehavior.prototype._closestFace = function (targetDirection) {
  93116. var _this = this;
  93117. // Go over each face and calculate the angle between the face's normal and targetDirection
  93118. this._faceVectors.forEach(function (v) {
  93119. if (!_this._target.rotationQuaternion) {
  93120. _this._target.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._target.rotation.y, _this._target.rotation.x, _this._target.rotation.z);
  93121. }
  93122. _this._target.rotationQuaternion.toRotationMatrix(_this._tmpMatrix);
  93123. BABYLON.Vector3.TransformCoordinatesToRef(v.direction, _this._tmpMatrix, v.rotatedDirection);
  93124. v.diff = BABYLON.Vector3.GetAngleBetweenVectors(v.rotatedDirection, targetDirection, BABYLON.Vector3.Cross(v.rotatedDirection, targetDirection));
  93125. });
  93126. // Return the face information of the one with the normal closeset to target direction
  93127. return this._faceVectors.reduce(function (min, p) {
  93128. if (min.ignore) {
  93129. return p;
  93130. }
  93131. else if (p.ignore) {
  93132. return min;
  93133. }
  93134. else {
  93135. return min.diff < p.diff ? min : p;
  93136. }
  93137. }, this._faceVectors[0]);
  93138. };
  93139. AttachToBoxBehavior.prototype._lookAtToRef = function (pos, up, ref) {
  93140. if (up === void 0) { up = new BABYLON.Vector3(0, 1, 0); }
  93141. BABYLON.Matrix.LookAtLHToRef(this._zeroVector, pos, up, this._lookAtTmpMatrix);
  93142. this._lookAtTmpMatrix.invert();
  93143. BABYLON.Quaternion.FromRotationMatrixToRef(this._lookAtTmpMatrix, ref);
  93144. };
  93145. /**
  93146. * Attaches the AttachToBoxBehavior to the passed in mesh
  93147. * @param target The mesh that the specified node will be attached to
  93148. */
  93149. AttachToBoxBehavior.prototype.attach = function (target) {
  93150. var _this = this;
  93151. this._target = target;
  93152. this._scene = this._target.getScene();
  93153. // Every frame, update the app bars position
  93154. this._onRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  93155. if (!_this._scene.activeCamera) {
  93156. return;
  93157. }
  93158. // Find the face closest to the cameras position
  93159. var cameraPos = _this._scene.activeCamera.position;
  93160. if (_this._scene.activeCamera.devicePosition) {
  93161. cameraPos = _this._scene.activeCamera.devicePosition;
  93162. }
  93163. var facing = _this._closestFace(cameraPos.subtract(target.position));
  93164. if (_this._scene.activeCamera.leftCamera) {
  93165. _this._scene.activeCamera.leftCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  93166. }
  93167. else {
  93168. _this._scene.activeCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  93169. }
  93170. // Get camera up direction
  93171. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Vector3.Up(), _this._tmpMatrix, _this._tmpVector);
  93172. // Ignore faces to not select a parrelel face for the up vector of the UI
  93173. _this._faceVectors.forEach(function (v) {
  93174. if (facing.direction.x && v.direction.x) {
  93175. v.ignore = true;
  93176. }
  93177. if (facing.direction.y && v.direction.y) {
  93178. v.ignore = true;
  93179. }
  93180. if (facing.direction.z && v.direction.z) {
  93181. v.ignore = true;
  93182. }
  93183. });
  93184. var facingUp = _this._closestFace(_this._tmpVector);
  93185. // Unignore faces
  93186. _this._faceVectors.forEach(function (v) {
  93187. v.ignore = false;
  93188. });
  93189. // Position the app bar on that face
  93190. _this.ui.position.copyFrom(target.position);
  93191. if (facing.direction.x) {
  93192. facing.rotatedDirection.scaleToRef((target.scaling.x / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  93193. _this.ui.position.addInPlace(_this._tmpVector);
  93194. }
  93195. if (facing.direction.y) {
  93196. facing.rotatedDirection.scaleToRef((target.scaling.y / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  93197. _this.ui.position.addInPlace(_this._tmpVector);
  93198. }
  93199. if (facing.direction.z) {
  93200. facing.rotatedDirection.scaleToRef((target.scaling.z / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  93201. _this.ui.position.addInPlace(_this._tmpVector);
  93202. }
  93203. // Rotate to be oriented properly to the camera
  93204. if (!_this.ui.rotationQuaternion) {
  93205. _this.ui.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.ui.rotation.y, _this.ui.rotation.x, _this.ui.rotation.z);
  93206. }
  93207. facing.rotatedDirection.scaleToRef(-1, _this._tmpVector);
  93208. _this._lookAtToRef(_this._tmpVector, facingUp.rotatedDirection, _this.ui.rotationQuaternion);
  93209. // Place ui the correct distance from the bottom of the mesh
  93210. if (facingUp.direction.x) {
  93211. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.x / 2, _this._tmpVector);
  93212. }
  93213. if (facingUp.direction.y) {
  93214. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.y / 2, _this._tmpVector);
  93215. }
  93216. if (facingUp.direction.z) {
  93217. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.z / 2, _this._tmpVector);
  93218. }
  93219. _this.ui.position.addInPlace(_this._tmpVector);
  93220. });
  93221. };
  93222. /**
  93223. * Detaches the behavior from the mesh
  93224. */
  93225. AttachToBoxBehavior.prototype.detach = function () {
  93226. this._scene.onBeforeRenderObservable.remove(this._onRenderObserver);
  93227. };
  93228. return AttachToBoxBehavior;
  93229. }());
  93230. BABYLON.AttachToBoxBehavior = AttachToBoxBehavior;
  93231. })(BABYLON || (BABYLON = {}));
  93232. //# sourceMappingURL=babylon.attachToBoxBehavior.js.map
  93233. var BABYLON;
  93234. (function (BABYLON) {
  93235. /**
  93236. * A behavior that when attached to a mesh will allow the mesh to fade in and out
  93237. */
  93238. var FadeInOutBehavior = /** @class */ (function () {
  93239. /**
  93240. * Instatiates the FadeInOutBehavior
  93241. */
  93242. function FadeInOutBehavior() {
  93243. var _this = this;
  93244. /**
  93245. * Time in milliseconds to delay before fading in (Default: 0)
  93246. */
  93247. this.delay = 0;
  93248. /**
  93249. * Time in milliseconds for the mesh to fade in (Default: 300)
  93250. */
  93251. this.fadeInTime = 300;
  93252. this._millisecondsPerFrame = 1000 / 60;
  93253. this._hovered = false;
  93254. this._hoverValue = 0;
  93255. this._ownerNode = null;
  93256. this._update = function () {
  93257. if (_this._ownerNode) {
  93258. _this._hoverValue += _this._hovered ? _this._millisecondsPerFrame : -_this._millisecondsPerFrame;
  93259. _this._setAllVisibility(_this._ownerNode, (_this._hoverValue - _this.delay) / _this.fadeInTime);
  93260. if (_this._ownerNode.visibility > 1) {
  93261. _this._setAllVisibility(_this._ownerNode, 1);
  93262. _this._hoverValue = _this.fadeInTime + _this.delay;
  93263. return;
  93264. }
  93265. else if (_this._ownerNode.visibility < 0) {
  93266. _this._setAllVisibility(_this._ownerNode, 0);
  93267. if (_this._hoverValue < 0) {
  93268. _this._hoverValue = 0;
  93269. return;
  93270. }
  93271. }
  93272. setTimeout(_this._update, _this._millisecondsPerFrame);
  93273. }
  93274. };
  93275. }
  93276. Object.defineProperty(FadeInOutBehavior.prototype, "name", {
  93277. /**
  93278. * The name of the behavior
  93279. */
  93280. get: function () {
  93281. return "FadeInOut";
  93282. },
  93283. enumerable: true,
  93284. configurable: true
  93285. });
  93286. /**
  93287. * Initializes the behavior
  93288. */
  93289. FadeInOutBehavior.prototype.init = function () {
  93290. };
  93291. /**
  93292. * Attaches the fade behavior on the passed in mesh
  93293. * @param ownerNode The mesh that will be faded in/out once attached
  93294. */
  93295. FadeInOutBehavior.prototype.attach = function (ownerNode) {
  93296. this._ownerNode = ownerNode;
  93297. this._setAllVisibility(this._ownerNode, 0);
  93298. };
  93299. /**
  93300. * Detaches the behavior from the mesh
  93301. */
  93302. FadeInOutBehavior.prototype.detach = function () {
  93303. this._ownerNode = null;
  93304. };
  93305. /**
  93306. * Triggers the mesh to begin fading in or out
  93307. * @param value if the object should fade in or out (true to fade in)
  93308. */
  93309. FadeInOutBehavior.prototype.fadeIn = function (value) {
  93310. this._hovered = value;
  93311. this._update();
  93312. };
  93313. FadeInOutBehavior.prototype._setAllVisibility = function (mesh, value) {
  93314. var _this = this;
  93315. mesh.visibility = value;
  93316. mesh.getChildMeshes().forEach(function (c) {
  93317. _this._setAllVisibility(c, value);
  93318. });
  93319. };
  93320. return FadeInOutBehavior;
  93321. }());
  93322. BABYLON.FadeInOutBehavior = FadeInOutBehavior;
  93323. })(BABYLON || (BABYLON = {}));
  93324. //# sourceMappingURL=babylon.fadeInOutBehavior.js.map
  93325. var BABYLON;
  93326. (function (BABYLON) {
  93327. /**
  93328. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  93329. */
  93330. var Gizmo = /** @class */ (function () {
  93331. /**
  93332. * Creates a gizmo
  93333. * @param gizmoLayer The utility layer the gizmo will be added to
  93334. */
  93335. function Gizmo(
  93336. /** The utility layer the gizmo will be added to */
  93337. gizmoLayer) {
  93338. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  93339. var _this = this;
  93340. this.gizmoLayer = gizmoLayer;
  93341. /**
  93342. * Ratio for the scale of the gizmo (Default: 1)
  93343. */
  93344. this.scaleRatio = 1;
  93345. this._tmpMatrix = new BABYLON.Matrix();
  93346. /**
  93347. * If a custom mesh has been set (Default: false)
  93348. */
  93349. this._customMeshSet = false;
  93350. /**
  93351. * If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true)
  93352. */
  93353. this.updateGizmoRotationToMatchAttachedMesh = true;
  93354. /**
  93355. * If set the gizmo's position will be updated to match the attached mesh each frame (Default: true)
  93356. */
  93357. this.updateGizmoPositionToMatchAttachedMesh = true;
  93358. /**
  93359. * When set, the gizmo will always appear the same size no matter where the camera is (default: false)
  93360. */
  93361. this._updateScale = true;
  93362. this._interactionsEnabled = true;
  93363. this._tempVector = new BABYLON.Vector3();
  93364. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  93365. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  93366. _this._update();
  93367. });
  93368. this.attachedMesh = null;
  93369. }
  93370. Object.defineProperty(Gizmo.prototype, "attachedMesh", {
  93371. /**
  93372. * Mesh that the gizmo will be attached to. (eg. on a drag gizmo the mesh that will be dragged)
  93373. * * When set, interactions will be enabled
  93374. */
  93375. get: function () {
  93376. return this._attachedMesh;
  93377. },
  93378. set: function (value) {
  93379. this._attachedMesh = value;
  93380. this._rootMesh.setEnabled(value ? true : false);
  93381. this._attachedMeshChanged(value);
  93382. },
  93383. enumerable: true,
  93384. configurable: true
  93385. });
  93386. /**
  93387. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  93388. * @param mesh The mesh to replace the default mesh of the gizmo
  93389. */
  93390. Gizmo.prototype.setCustomMesh = function (mesh) {
  93391. if (mesh.getScene() != this.gizmoLayer.utilityLayerScene) {
  93392. throw "When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)";
  93393. }
  93394. this._rootMesh.getChildMeshes().forEach(function (c) {
  93395. c.dispose();
  93396. });
  93397. mesh.parent = this._rootMesh;
  93398. this._customMeshSet = true;
  93399. };
  93400. Gizmo.prototype._attachedMeshChanged = function (value) {
  93401. };
  93402. /**
  93403. * @hidden
  93404. * Updates the gizmo to match the attached mesh's position/rotation
  93405. */
  93406. Gizmo.prototype._update = function () {
  93407. if (this.attachedMesh) {
  93408. if (this.updateGizmoRotationToMatchAttachedMesh) {
  93409. if (!this._rootMesh.rotationQuaternion) {
  93410. this._rootMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._rootMesh.rotation.y, this._rootMesh.rotation.x, this._rootMesh.rotation.z);
  93411. }
  93412. // Remove scaling before getting rotation matrix to get rotation matrix unmodified by scale
  93413. this._tempVector.copyFrom(this.attachedMesh.scaling);
  93414. if (this.attachedMesh.scaling.x < 0) {
  93415. this.attachedMesh.scaling.x *= -1;
  93416. }
  93417. if (this.attachedMesh.scaling.y < 0) {
  93418. this.attachedMesh.scaling.y *= -1;
  93419. }
  93420. if (this.attachedMesh.scaling.z < 0) {
  93421. this.attachedMesh.scaling.z *= -1;
  93422. }
  93423. this.attachedMesh.computeWorldMatrix().getRotationMatrixToRef(this._tmpMatrix);
  93424. this.attachedMesh.scaling.copyFrom(this._tempVector);
  93425. this.attachedMesh.computeWorldMatrix();
  93426. BABYLON.Quaternion.FromRotationMatrixToRef(this._tmpMatrix, this._rootMesh.rotationQuaternion);
  93427. }
  93428. else if (this._rootMesh.rotationQuaternion) {
  93429. this._rootMesh.rotationQuaternion.set(0, 0, 0, 1);
  93430. }
  93431. if (this.updateGizmoPositionToMatchAttachedMesh) {
  93432. this._rootMesh.position.copyFrom(this.attachedMesh.absolutePosition);
  93433. }
  93434. if (this._updateScale && this.gizmoLayer.utilityLayerScene.activeCamera && this.attachedMesh) {
  93435. var cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.position;
  93436. if (this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition) {
  93437. cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition;
  93438. }
  93439. this._rootMesh.position.subtractToRef(cameraPosition, this._tempVector);
  93440. var dist = this._tempVector.length() * this.scaleRatio;
  93441. this._rootMesh.scaling.set(dist, dist, dist);
  93442. }
  93443. }
  93444. };
  93445. /**
  93446. * Disposes of the gizmo
  93447. */
  93448. Gizmo.prototype.dispose = function () {
  93449. this._rootMesh.dispose();
  93450. if (this._beforeRenderObserver) {
  93451. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  93452. }
  93453. };
  93454. return Gizmo;
  93455. }());
  93456. BABYLON.Gizmo = Gizmo;
  93457. })(BABYLON || (BABYLON = {}));
  93458. //# sourceMappingURL=babylon.gizmo.js.map
  93459. var BABYLON;
  93460. (function (BABYLON) {
  93461. /**
  93462. * Single axis drag gizmo
  93463. */
  93464. var AxisDragGizmo = /** @class */ (function (_super) {
  93465. __extends(AxisDragGizmo, _super);
  93466. /**
  93467. * Creates an AxisDragGizmo
  93468. * @param gizmoLayer The utility layer the gizmo will be added to
  93469. * @param dragAxis The axis which the gizmo will be able to drag on
  93470. * @param color The color of the gizmo
  93471. */
  93472. function AxisDragGizmo(dragAxis, color, gizmoLayer) {
  93473. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  93474. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  93475. var _this = _super.call(this, gizmoLayer) || this;
  93476. _this._pointerObserver = null;
  93477. /**
  93478. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  93479. */
  93480. _this.snapDistance = 0;
  93481. /**
  93482. * Event that fires each time the gizmo snaps to a new location.
  93483. * * snapDistance is the the change in distance
  93484. */
  93485. _this.onSnapObservable = new BABYLON.Observable();
  93486. // Create Material
  93487. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  93488. coloredMaterial.disableLighting = true;
  93489. coloredMaterial.emissiveColor = color;
  93490. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  93491. hoverMaterial.disableLighting = true;
  93492. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  93493. // Build mesh on root node
  93494. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  93495. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 1.5, diameterBottom: 0.75, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  93496. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  93497. arrowTail.color = coloredMaterial.emissiveColor;
  93498. arrow.addChild(arrowMesh);
  93499. arrow.addChild(arrowTail);
  93500. // Position arrow pointing in its drag axis
  93501. arrowMesh.scaling.scaleInPlace(0.05);
  93502. arrowMesh.material = coloredMaterial;
  93503. arrowMesh.rotation.x = Math.PI / 2;
  93504. arrowMesh.position.z += 0.3;
  93505. arrowTail.scaling.scaleInPlace(0.26);
  93506. arrowTail.rotation.x = Math.PI / 2;
  93507. arrowTail.material = coloredMaterial;
  93508. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  93509. arrow.scaling.scaleInPlace(1 / 3);
  93510. _this._rootMesh.addChild(arrow);
  93511. var currentSnapDragDistance = 0;
  93512. var tmpVector = new BABYLON.Vector3();
  93513. var tmpSnapEvent = { snapDistance: 0 };
  93514. // Add drag behavior to handle events when the gizmo is dragged
  93515. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  93516. _this.dragBehavior.moveAttached = false;
  93517. _this._rootMesh.addBehavior(_this.dragBehavior);
  93518. var localDelta = new BABYLON.Vector3();
  93519. var tmpMatrix = new BABYLON.Matrix();
  93520. _this.dragBehavior.onDragObservable.add(function (event) {
  93521. if (_this.attachedMesh) {
  93522. // Convert delta to local translation if it has a parent
  93523. if (_this.attachedMesh.parent) {
  93524. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  93525. tmpMatrix.setTranslationFromFloats(0, 0, 0);
  93526. BABYLON.Vector3.TransformCoordinatesToRef(event.delta, tmpMatrix, localDelta);
  93527. }
  93528. else {
  93529. localDelta.copyFrom(event.delta);
  93530. }
  93531. // Snapping logic
  93532. if (_this.snapDistance == 0) {
  93533. _this.attachedMesh.position.addInPlace(localDelta);
  93534. }
  93535. else {
  93536. currentSnapDragDistance += event.dragDistance;
  93537. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  93538. var dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / _this.snapDistance);
  93539. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  93540. localDelta.normalizeToRef(tmpVector);
  93541. tmpVector.scaleInPlace(_this.snapDistance * dragSteps);
  93542. _this.attachedMesh.position.addInPlace(tmpVector);
  93543. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  93544. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  93545. }
  93546. }
  93547. }
  93548. });
  93549. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  93550. if (_this._customMeshSet) {
  93551. return;
  93552. }
  93553. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  93554. var material = isHovered ? hoverMaterial : coloredMaterial;
  93555. _this._rootMesh.getChildMeshes().forEach(function (m) {
  93556. m.material = material;
  93557. if (m.color) {
  93558. m.color = material.emissiveColor;
  93559. }
  93560. });
  93561. });
  93562. return _this;
  93563. }
  93564. AxisDragGizmo.prototype._attachedMeshChanged = function (value) {
  93565. if (this.dragBehavior) {
  93566. this.dragBehavior.enabled = value ? true : false;
  93567. }
  93568. };
  93569. /**
  93570. * Disposes of the gizmo
  93571. */
  93572. AxisDragGizmo.prototype.dispose = function () {
  93573. this.onSnapObservable.clear();
  93574. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  93575. this.dragBehavior.detach();
  93576. _super.prototype.dispose.call(this);
  93577. };
  93578. return AxisDragGizmo;
  93579. }(BABYLON.Gizmo));
  93580. BABYLON.AxisDragGizmo = AxisDragGizmo;
  93581. })(BABYLON || (BABYLON = {}));
  93582. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  93583. var BABYLON;
  93584. (function (BABYLON) {
  93585. /**
  93586. * Single axis scale gizmo
  93587. */
  93588. var AxisScaleGizmo = /** @class */ (function (_super) {
  93589. __extends(AxisScaleGizmo, _super);
  93590. /**
  93591. * Creates an AxisScaleGizmo
  93592. * @param gizmoLayer The utility layer the gizmo will be added to
  93593. * @param dragAxis The axis which the gizmo will be able to scale on
  93594. * @param color The color of the gizmo
  93595. */
  93596. function AxisScaleGizmo(dragAxis, color, gizmoLayer) {
  93597. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  93598. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  93599. var _this = _super.call(this, gizmoLayer) || this;
  93600. _this._pointerObserver = null;
  93601. /**
  93602. * Scale distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  93603. */
  93604. _this.snapDistance = 0;
  93605. /**
  93606. * Event that fires each time the gizmo snaps to a new location.
  93607. * * snapDistance is the the change in distance
  93608. */
  93609. _this.onSnapObservable = new BABYLON.Observable();
  93610. /**
  93611. * If the scaling operation should be done on all axis (default: false)
  93612. */
  93613. _this.uniformScaling = false;
  93614. // Create Material
  93615. _this._coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  93616. _this._coloredMaterial.disableLighting = true;
  93617. _this._coloredMaterial.emissiveColor = color;
  93618. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  93619. hoverMaterial.disableLighting = true;
  93620. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  93621. // Build mesh on root node
  93622. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  93623. var arrowMesh = BABYLON.MeshBuilder.CreateBox("yPosMesh", { size: 0.4 }, gizmoLayer.utilityLayerScene);
  93624. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  93625. arrowTail.color = _this._coloredMaterial.emissiveColor;
  93626. arrow.addChild(arrowMesh);
  93627. arrow.addChild(arrowTail);
  93628. // Position arrow pointing in its drag axis
  93629. arrowMesh.scaling.scaleInPlace(0.1);
  93630. arrowMesh.material = _this._coloredMaterial;
  93631. arrowMesh.rotation.x = Math.PI / 2;
  93632. arrowMesh.position.z += 0.3;
  93633. arrowTail.scaling.scaleInPlace(0.26);
  93634. arrowTail.rotation.x = Math.PI / 2;
  93635. arrowTail.material = _this._coloredMaterial;
  93636. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  93637. _this._rootMesh.addChild(arrow);
  93638. arrow.scaling.scaleInPlace(1 / 3);
  93639. // Add drag behavior to handle events when the gizmo is dragged
  93640. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  93641. _this.dragBehavior.moveAttached = false;
  93642. _this._rootMesh.addBehavior(_this.dragBehavior);
  93643. var currentSnapDragDistance = 0;
  93644. var tmpVector = new BABYLON.Vector3();
  93645. var tmpSnapEvent = { snapDistance: 0 };
  93646. _this.dragBehavior.onDragObservable.add(function (event) {
  93647. if (_this.attachedMesh) {
  93648. // Snapping logic
  93649. var snapped = false;
  93650. var dragSteps = 0;
  93651. if (_this.uniformScaling) {
  93652. _this.attachedMesh.scaling.normalizeToRef(tmpVector);
  93653. if (tmpVector.y < 0) {
  93654. tmpVector.scaleInPlace(-1);
  93655. }
  93656. }
  93657. else {
  93658. tmpVector.copyFrom(dragAxis);
  93659. }
  93660. if (_this.snapDistance == 0) {
  93661. tmpVector.scaleToRef(event.dragDistance, tmpVector);
  93662. }
  93663. else {
  93664. currentSnapDragDistance += event.dragDistance;
  93665. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  93666. dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  93667. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  93668. tmpVector.scaleToRef(_this.snapDistance * dragSteps, tmpVector);
  93669. snapped = true;
  93670. }
  93671. else {
  93672. tmpVector.scaleInPlace(0);
  93673. }
  93674. }
  93675. _this.attachedMesh.scaling.addInPlace(tmpVector);
  93676. if (snapped) {
  93677. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  93678. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  93679. }
  93680. }
  93681. });
  93682. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  93683. if (_this._customMeshSet) {
  93684. return;
  93685. }
  93686. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  93687. var material = isHovered ? hoverMaterial : _this._coloredMaterial;
  93688. _this._rootMesh.getChildMeshes().forEach(function (m) {
  93689. m.material = material;
  93690. if (m.color) {
  93691. m.color = material.emissiveColor;
  93692. }
  93693. });
  93694. });
  93695. return _this;
  93696. }
  93697. AxisScaleGizmo.prototype._attachedMeshChanged = function (value) {
  93698. if (this.dragBehavior) {
  93699. this.dragBehavior.enabled = value ? true : false;
  93700. }
  93701. };
  93702. /**
  93703. * Disposes of the gizmo
  93704. */
  93705. AxisScaleGizmo.prototype.dispose = function () {
  93706. this.onSnapObservable.clear();
  93707. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  93708. this.dragBehavior.detach();
  93709. _super.prototype.dispose.call(this);
  93710. };
  93711. /**
  93712. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  93713. * @param mesh The mesh to replace the default mesh of the gizmo
  93714. * @param useGizmoMaterial If the gizmo's default material should be used (default: false)
  93715. */
  93716. AxisScaleGizmo.prototype.setCustomMesh = function (mesh, useGizmoMaterial) {
  93717. var _this = this;
  93718. if (useGizmoMaterial === void 0) { useGizmoMaterial = false; }
  93719. _super.prototype.setCustomMesh.call(this, mesh);
  93720. if (useGizmoMaterial) {
  93721. this._rootMesh.getChildMeshes().forEach(function (m) {
  93722. m.material = _this._coloredMaterial;
  93723. if (m.color) {
  93724. m.color = _this._coloredMaterial.emissiveColor;
  93725. }
  93726. });
  93727. this._customMeshSet = false;
  93728. }
  93729. };
  93730. return AxisScaleGizmo;
  93731. }(BABYLON.Gizmo));
  93732. BABYLON.AxisScaleGizmo = AxisScaleGizmo;
  93733. })(BABYLON || (BABYLON = {}));
  93734. //# sourceMappingURL=babylon.axisScaleGizmo.js.map
  93735. var BABYLON;
  93736. (function (BABYLON) {
  93737. /**
  93738. * Single plane rotation gizmo
  93739. */
  93740. var PlaneRotationGizmo = /** @class */ (function (_super) {
  93741. __extends(PlaneRotationGizmo, _super);
  93742. /**
  93743. * Creates a PlaneRotationGizmo
  93744. * @param gizmoLayer The utility layer the gizmo will be added to
  93745. * @param planeNormal The normal of the plane which the gizmo will be able to rotate on
  93746. * @param color The color of the gizmo
  93747. */
  93748. function PlaneRotationGizmo(planeNormal, color, gizmoLayer) {
  93749. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  93750. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  93751. var _this = _super.call(this, gizmoLayer) || this;
  93752. _this._pointerObserver = null;
  93753. /**
  93754. * Rotation distance in radians that the gizmo will snap to (Default: 0)
  93755. */
  93756. _this.snapDistance = 0;
  93757. /**
  93758. * Event that fires each time the gizmo snaps to a new location.
  93759. * * snapDistance is the the change in distance
  93760. */
  93761. _this.onSnapObservable = new BABYLON.Observable();
  93762. // Create Material
  93763. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  93764. coloredMaterial.disableLighting = true;
  93765. coloredMaterial.emissiveColor = color;
  93766. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  93767. hoverMaterial.disableLighting = true;
  93768. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  93769. // Build mesh on root node
  93770. var parentMesh = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  93771. // Create circle out of lines
  93772. var tessellation = 20;
  93773. var radius = 0.8;
  93774. var points = new Array();
  93775. for (var i = 0; i < tessellation; i++) {
  93776. var radian = (2 * Math.PI) * (i / (tessellation - 1));
  93777. points.push(new BABYLON.Vector3(radius * Math.sin(radian), 0, radius * Math.cos(radian)));
  93778. }
  93779. var rotationMesh = BABYLON.Mesh.CreateLines("", points, gizmoLayer.utilityLayerScene);
  93780. rotationMesh.color = coloredMaterial.emissiveColor;
  93781. // Position arrow pointing in its drag axis
  93782. rotationMesh.scaling.scaleInPlace(0.26);
  93783. rotationMesh.material = coloredMaterial;
  93784. rotationMesh.rotation.x = Math.PI / 2;
  93785. parentMesh.addChild(rotationMesh);
  93786. parentMesh.lookAt(_this._rootMesh.position.subtract(planeNormal));
  93787. _this._rootMesh.addChild(parentMesh);
  93788. parentMesh.scaling.scaleInPlace(1 / 3);
  93789. // Add drag behavior to handle events when the gizmo is dragged
  93790. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: planeNormal });
  93791. _this.dragBehavior.moveAttached = false;
  93792. _this.dragBehavior.maxDragAngle = Math.PI * 9 / 20;
  93793. _this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle = true;
  93794. _this._rootMesh.addBehavior(_this.dragBehavior);
  93795. var lastDragPosition = new BABYLON.Vector3();
  93796. _this.dragBehavior.onDragStartObservable.add(function (e) {
  93797. if (_this.attachedMesh) {
  93798. lastDragPosition.copyFrom(e.dragPlanePoint);
  93799. }
  93800. });
  93801. var rotationMatrix = new BABYLON.Matrix();
  93802. var planeNormalTowardsCamera = new BABYLON.Vector3();
  93803. var localPlaneNormalTowardsCamera = new BABYLON.Vector3();
  93804. var tmpSnapEvent = { snapDistance: 0 };
  93805. var currentSnapDragDistance = 0;
  93806. var tmpMatrix = new BABYLON.Matrix();
  93807. var tmpVector = new BABYLON.Vector3();
  93808. var amountToRotate = new BABYLON.Quaternion();
  93809. _this.dragBehavior.onDragObservable.add(function (event) {
  93810. if (_this.attachedMesh) {
  93811. if (!_this.attachedMesh.rotationQuaternion) {
  93812. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  93813. }
  93814. // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)
  93815. var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.absolutePosition).normalize();
  93816. var originalVector = lastDragPosition.subtract(_this.attachedMesh.absolutePosition).normalize();
  93817. var cross = BABYLON.Vector3.Cross(newVector, originalVector);
  93818. var dot = BABYLON.Vector3.Dot(newVector, originalVector);
  93819. var angle = Math.atan2(cross.length(), dot);
  93820. planeNormalTowardsCamera.copyFrom(planeNormal);
  93821. localPlaneNormalTowardsCamera.copyFrom(planeNormal);
  93822. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  93823. _this.attachedMesh.rotationQuaternion.toRotationMatrix(rotationMatrix);
  93824. localPlaneNormalTowardsCamera = BABYLON.Vector3.TransformCoordinates(planeNormalTowardsCamera, rotationMatrix);
  93825. }
  93826. // Flip up vector depending on which side the camera is on
  93827. if (gizmoLayer.utilityLayerScene.activeCamera) {
  93828. var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);
  93829. if (BABYLON.Vector3.Dot(camVec, localPlaneNormalTowardsCamera) > 0) {
  93830. planeNormalTowardsCamera.scaleInPlace(-1);
  93831. localPlaneNormalTowardsCamera.scaleInPlace(-1);
  93832. }
  93833. }
  93834. var halfCircleSide = BABYLON.Vector3.Dot(localPlaneNormalTowardsCamera, cross) > 0.0;
  93835. if (halfCircleSide)
  93836. angle = -angle;
  93837. // Snapping logic
  93838. var snapped = false;
  93839. if (_this.snapDistance != 0) {
  93840. currentSnapDragDistance += angle;
  93841. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  93842. var dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  93843. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  93844. angle = _this.snapDistance * dragSteps;
  93845. snapped = true;
  93846. }
  93847. else {
  93848. angle = 0;
  93849. }
  93850. }
  93851. // If the mesh has a parent, convert needed world rotation to local rotation
  93852. tmpMatrix.reset();
  93853. if (_this.attachedMesh.parent) {
  93854. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  93855. tmpMatrix.getRotationMatrixToRef(tmpMatrix);
  93856. BABYLON.Vector3.TransformCoordinatesToRef(planeNormalTowardsCamera, tmpMatrix, planeNormalTowardsCamera);
  93857. }
  93858. // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
  93859. var quaternionCoefficient = Math.sin(angle / 2);
  93860. amountToRotate.set(planeNormalTowardsCamera.x * quaternionCoefficient, planeNormalTowardsCamera.y * quaternionCoefficient, planeNormalTowardsCamera.z * quaternionCoefficient, Math.cos(angle / 2));
  93861. // 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
  93862. if (tmpMatrix.determinant() > 0) {
  93863. amountToRotate.toEulerAnglesToRef(tmpVector);
  93864. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpVector.y, -tmpVector.x, -tmpVector.z, amountToRotate);
  93865. }
  93866. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  93867. // Rotate selected mesh quaternion over fixed axis
  93868. _this.attachedMesh.rotationQuaternion.multiplyToRef(amountToRotate, _this.attachedMesh.rotationQuaternion);
  93869. }
  93870. else {
  93871. // Rotate selected mesh quaternion over rotated axis
  93872. amountToRotate.multiplyToRef(_this.attachedMesh.rotationQuaternion, _this.attachedMesh.rotationQuaternion);
  93873. }
  93874. lastDragPosition.copyFrom(event.dragPlanePoint);
  93875. if (snapped) {
  93876. tmpSnapEvent.snapDistance = angle;
  93877. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  93878. }
  93879. }
  93880. });
  93881. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  93882. if (_this._customMeshSet) {
  93883. return;
  93884. }
  93885. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  93886. var material = isHovered ? hoverMaterial : coloredMaterial;
  93887. _this._rootMesh.getChildMeshes().forEach(function (m) {
  93888. m.material = material;
  93889. if (m.color) {
  93890. m.color = material.emissiveColor;
  93891. }
  93892. });
  93893. });
  93894. return _this;
  93895. }
  93896. PlaneRotationGizmo.prototype._attachedMeshChanged = function (value) {
  93897. if (this.dragBehavior) {
  93898. this.dragBehavior.enabled = value ? true : false;
  93899. }
  93900. };
  93901. /**
  93902. * Disposes of the gizmo
  93903. */
  93904. PlaneRotationGizmo.prototype.dispose = function () {
  93905. this.onSnapObservable.clear();
  93906. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  93907. this.dragBehavior.detach();
  93908. _super.prototype.dispose.call(this);
  93909. };
  93910. return PlaneRotationGizmo;
  93911. }(BABYLON.Gizmo));
  93912. BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;
  93913. })(BABYLON || (BABYLON = {}));
  93914. //# sourceMappingURL=babylon.planeRotationGizmo.js.map
  93915. var BABYLON;
  93916. (function (BABYLON) {
  93917. /**
  93918. * Gizmo that enables dragging a mesh along 3 axis
  93919. */
  93920. var PositionGizmo = /** @class */ (function (_super) {
  93921. __extends(PositionGizmo, _super);
  93922. /**
  93923. * Creates a PositionGizmo
  93924. * @param gizmoLayer The utility layer the gizmo will be added to
  93925. */
  93926. function PositionGizmo(gizmoLayer) {
  93927. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  93928. var _this = _super.call(this, gizmoLayer) || this;
  93929. _this.xGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  93930. _this.yGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  93931. _this.zGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  93932. _this.attachedMesh = null;
  93933. return _this;
  93934. }
  93935. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  93936. set: function (mesh) {
  93937. if (this.xGizmo) {
  93938. this.xGizmo.attachedMesh = mesh;
  93939. this.yGizmo.attachedMesh = mesh;
  93940. this.zGizmo.attachedMesh = mesh;
  93941. }
  93942. },
  93943. enumerable: true,
  93944. configurable: true
  93945. });
  93946. Object.defineProperty(PositionGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  93947. get: function () {
  93948. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  93949. },
  93950. set: function (value) {
  93951. if (this.xGizmo) {
  93952. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  93953. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  93954. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  93955. }
  93956. },
  93957. enumerable: true,
  93958. configurable: true
  93959. });
  93960. Object.defineProperty(PositionGizmo.prototype, "snapDistance", {
  93961. get: function () {
  93962. return this.xGizmo.snapDistance;
  93963. },
  93964. /**
  93965. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  93966. */
  93967. set: function (value) {
  93968. if (this.xGizmo) {
  93969. this.xGizmo.snapDistance = value;
  93970. this.yGizmo.snapDistance = value;
  93971. this.zGizmo.snapDistance = value;
  93972. }
  93973. },
  93974. enumerable: true,
  93975. configurable: true
  93976. });
  93977. Object.defineProperty(PositionGizmo.prototype, "scaleRatio", {
  93978. get: function () {
  93979. return this.xGizmo.scaleRatio;
  93980. },
  93981. /**
  93982. * Ratio for the scale of the gizmo (Default: 1)
  93983. */
  93984. set: function (value) {
  93985. if (this.xGizmo) {
  93986. this.xGizmo.scaleRatio = value;
  93987. this.yGizmo.scaleRatio = value;
  93988. this.zGizmo.scaleRatio = value;
  93989. }
  93990. },
  93991. enumerable: true,
  93992. configurable: true
  93993. });
  93994. /**
  93995. * Disposes of the gizmo
  93996. */
  93997. PositionGizmo.prototype.dispose = function () {
  93998. this.xGizmo.dispose();
  93999. this.yGizmo.dispose();
  94000. this.zGizmo.dispose();
  94001. };
  94002. /**
  94003. * CustomMeshes are not supported by this gizmo
  94004. * @param mesh The mesh to replace the default mesh of the gizmo
  94005. */
  94006. PositionGizmo.prototype.setCustomMesh = function (mesh) {
  94007. 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)");
  94008. };
  94009. return PositionGizmo;
  94010. }(BABYLON.Gizmo));
  94011. BABYLON.PositionGizmo = PositionGizmo;
  94012. })(BABYLON || (BABYLON = {}));
  94013. //# sourceMappingURL=babylon.positionGizmo.js.map
  94014. var BABYLON;
  94015. (function (BABYLON) {
  94016. /**
  94017. * Gizmo that enables rotating a mesh along 3 axis
  94018. */
  94019. var RotationGizmo = /** @class */ (function (_super) {
  94020. __extends(RotationGizmo, _super);
  94021. /**
  94022. * Creates a RotationGizmo
  94023. * @param gizmoLayer The utility layer the gizmo will be added to
  94024. */
  94025. function RotationGizmo(gizmoLayer) {
  94026. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  94027. var _this = _super.call(this, gizmoLayer) || this;
  94028. _this.xGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  94029. _this.yGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  94030. _this.zGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  94031. _this.attachedMesh = null;
  94032. return _this;
  94033. }
  94034. Object.defineProperty(RotationGizmo.prototype, "attachedMesh", {
  94035. set: function (mesh) {
  94036. if (this.xGizmo) {
  94037. this.xGizmo.attachedMesh = mesh;
  94038. this.yGizmo.attachedMesh = mesh;
  94039. this.zGizmo.attachedMesh = mesh;
  94040. }
  94041. },
  94042. enumerable: true,
  94043. configurable: true
  94044. });
  94045. Object.defineProperty(RotationGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  94046. get: function () {
  94047. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  94048. },
  94049. set: function (value) {
  94050. if (this.xGizmo) {
  94051. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  94052. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  94053. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  94054. }
  94055. },
  94056. enumerable: true,
  94057. configurable: true
  94058. });
  94059. Object.defineProperty(RotationGizmo.prototype, "snapDistance", {
  94060. get: function () {
  94061. return this.xGizmo.snapDistance;
  94062. },
  94063. /**
  94064. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  94065. */
  94066. set: function (value) {
  94067. if (this.xGizmo) {
  94068. this.xGizmo.snapDistance = value;
  94069. this.yGizmo.snapDistance = value;
  94070. this.zGizmo.snapDistance = value;
  94071. }
  94072. },
  94073. enumerable: true,
  94074. configurable: true
  94075. });
  94076. Object.defineProperty(RotationGizmo.prototype, "scaleRatio", {
  94077. get: function () {
  94078. return this.xGizmo.scaleRatio;
  94079. },
  94080. /**
  94081. * Ratio for the scale of the gizmo (Default: 1)
  94082. */
  94083. set: function (value) {
  94084. if (this.xGizmo) {
  94085. this.xGizmo.scaleRatio = value;
  94086. this.yGizmo.scaleRatio = value;
  94087. this.zGizmo.scaleRatio = value;
  94088. }
  94089. },
  94090. enumerable: true,
  94091. configurable: true
  94092. });
  94093. /**
  94094. * Disposes of the gizmo
  94095. */
  94096. RotationGizmo.prototype.dispose = function () {
  94097. this.xGizmo.dispose();
  94098. this.yGizmo.dispose();
  94099. this.zGizmo.dispose();
  94100. };
  94101. /**
  94102. * CustomMeshes are not supported by this gizmo
  94103. * @param mesh The mesh to replace the default mesh of the gizmo
  94104. */
  94105. RotationGizmo.prototype.setCustomMesh = function (mesh) {
  94106. 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)");
  94107. };
  94108. return RotationGizmo;
  94109. }(BABYLON.Gizmo));
  94110. BABYLON.RotationGizmo = RotationGizmo;
  94111. })(BABYLON || (BABYLON = {}));
  94112. //# sourceMappingURL=babylon.rotationGizmo.js.map
  94113. var BABYLON;
  94114. (function (BABYLON) {
  94115. /**
  94116. * Gizmo that enables scaling a mesh along 3 axis
  94117. */
  94118. var ScaleGizmo = /** @class */ (function (_super) {
  94119. __extends(ScaleGizmo, _super);
  94120. /**
  94121. * Creates a ScaleGizmo
  94122. * @param gizmoLayer The utility layer the gizmo will be added to
  94123. */
  94124. function ScaleGizmo(gizmoLayer) {
  94125. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  94126. var _this = _super.call(this, gizmoLayer) || this;
  94127. _this.xGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  94128. _this.yGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  94129. _this.zGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  94130. // Create uniform scale gizmo
  94131. _this._uniformGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Yellow().scale(0.5), gizmoLayer);
  94132. _this._uniformGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  94133. _this._uniformGizmo.uniformScaling = true;
  94134. var octahedron = BABYLON.Mesh.CreatePolyhedron("", { type: 1 }, _this._uniformGizmo.gizmoLayer.utilityLayerScene);
  94135. octahedron.scaling.scaleInPlace(0.007);
  94136. _this._uniformGizmo.setCustomMesh(octahedron, true);
  94137. _this.attachedMesh = null;
  94138. return _this;
  94139. }
  94140. Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", {
  94141. set: function (mesh) {
  94142. if (this.xGizmo) {
  94143. this.xGizmo.attachedMesh = mesh;
  94144. this.yGizmo.attachedMesh = mesh;
  94145. this.zGizmo.attachedMesh = mesh;
  94146. this._uniformGizmo.attachedMesh = mesh;
  94147. }
  94148. },
  94149. enumerable: true,
  94150. configurable: true
  94151. });
  94152. Object.defineProperty(ScaleGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  94153. get: function () {
  94154. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  94155. },
  94156. set: function (value) {
  94157. if (this.xGizmo) {
  94158. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  94159. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  94160. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  94161. }
  94162. },
  94163. enumerable: true,
  94164. configurable: true
  94165. });
  94166. Object.defineProperty(ScaleGizmo.prototype, "snapDistance", {
  94167. get: function () {
  94168. return this.xGizmo.snapDistance;
  94169. },
  94170. /**
  94171. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  94172. */
  94173. set: function (value) {
  94174. if (this.xGizmo) {
  94175. this.xGizmo.snapDistance = value;
  94176. this.yGizmo.snapDistance = value;
  94177. this.zGizmo.snapDistance = value;
  94178. this._uniformGizmo.snapDistance = value;
  94179. }
  94180. },
  94181. enumerable: true,
  94182. configurable: true
  94183. });
  94184. Object.defineProperty(ScaleGizmo.prototype, "scaleRatio", {
  94185. get: function () {
  94186. return this.xGizmo.scaleRatio;
  94187. },
  94188. /**
  94189. * Ratio for the scale of the gizmo (Default: 1)
  94190. */
  94191. set: function (value) {
  94192. if (this.xGizmo) {
  94193. this.xGizmo.scaleRatio = value;
  94194. this.yGizmo.scaleRatio = value;
  94195. this.zGizmo.scaleRatio = value;
  94196. this._uniformGizmo.scaleRatio = value;
  94197. }
  94198. },
  94199. enumerable: true,
  94200. configurable: true
  94201. });
  94202. /**
  94203. * Disposes of the gizmo
  94204. */
  94205. ScaleGizmo.prototype.dispose = function () {
  94206. this.xGizmo.dispose();
  94207. this.yGizmo.dispose();
  94208. this.zGizmo.dispose();
  94209. this._uniformGizmo.dispose();
  94210. };
  94211. return ScaleGizmo;
  94212. }(BABYLON.Gizmo));
  94213. BABYLON.ScaleGizmo = ScaleGizmo;
  94214. })(BABYLON || (BABYLON = {}));
  94215. //# sourceMappingURL=babylon.scaleGizmo.js.map
  94216. var BABYLON;
  94217. (function (BABYLON) {
  94218. /**
  94219. * Bounding box gizmo
  94220. */
  94221. var BoundingBoxGizmo = /** @class */ (function (_super) {
  94222. __extends(BoundingBoxGizmo, _super);
  94223. /**
  94224. * Creates an BoundingBoxGizmo
  94225. * @param gizmoLayer The utility layer the gizmo will be added to
  94226. * @param color The color of the gizmo
  94227. */
  94228. function BoundingBoxGizmo(color, gizmoLayer) {
  94229. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  94230. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultKeepDepthUtilityLayer; }
  94231. var _this = _super.call(this, gizmoLayer) || this;
  94232. _this._boundingDimensions = new BABYLON.Vector3(1, 1, 1);
  94233. _this._renderObserver = null;
  94234. _this._pointerObserver = null;
  94235. _this._scaleDragSpeed = 0.2;
  94236. _this._tmpQuaternion = new BABYLON.Quaternion();
  94237. _this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  94238. _this._tmpRotationMatrix = new BABYLON.Matrix();
  94239. /**
  94240. * 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)
  94241. */
  94242. _this.ignoreChildren = false;
  94243. /**
  94244. * Returns true if a descendant should be included when computing the bounding box. When null, all descendants are included. If ignoreChildren is set this will be ignored. (Default: null)
  94245. */
  94246. _this.includeChildPredicate = null;
  94247. /**
  94248. * The size of the rotation spheres attached to the bounding box (Default: 0.1)
  94249. */
  94250. _this.rotationSphereSize = 0.1;
  94251. /**
  94252. * The size of the scale boxes attached to the bounding box (Default: 0.1)
  94253. */
  94254. _this.scaleBoxSize = 0.1;
  94255. /**
  94256. * 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)
  94257. */
  94258. _this.fixedDragMeshScreenSize = false;
  94259. /**
  94260. * The distance away from the object which the draggable meshes should appear world sized when fixedDragMeshScreenSize is set to true (default: 10)
  94261. */
  94262. _this.fixedDragMeshScreenSizeDistanceFactor = 10;
  94263. /**
  94264. * Fired when a rotation sphere or scale box is dragged
  94265. */
  94266. _this.onDragStartObservable = new BABYLON.Observable();
  94267. /**
  94268. * Fired when a scale box is dragged
  94269. */
  94270. _this.onScaleBoxDragObservable = new BABYLON.Observable();
  94271. /**
  94272. * Fired when a scale box drag is ended
  94273. */
  94274. _this.onScaleBoxDragEndObservable = new BABYLON.Observable();
  94275. /**
  94276. * Fired when a rotation sphere is dragged
  94277. */
  94278. _this.onRotationSphereDragObservable = new BABYLON.Observable();
  94279. /**
  94280. * Fired when a rotation sphere drag is ended
  94281. */
  94282. _this.onRotationSphereDragEndObservable = new BABYLON.Observable();
  94283. /**
  94284. * 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)
  94285. */
  94286. _this.scalePivot = null;
  94287. _this._existingMeshScale = new BABYLON.Vector3();
  94288. // Do not update the gizmo's scale so it has a fixed size to the object its attached to
  94289. _this._updateScale = false;
  94290. _this._anchorMesh = new BABYLON.AbstractMesh("anchor", gizmoLayer.utilityLayerScene);
  94291. // Create Materials
  94292. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  94293. coloredMaterial.disableLighting = true;
  94294. coloredMaterial.emissiveColor = color;
  94295. var hoverColoredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  94296. hoverColoredMaterial.disableLighting = true;
  94297. hoverColoredMaterial.emissiveColor = color.clone().add(new BABYLON.Color3(0.3, 0.3, 0.3));
  94298. // Build bounding box out of lines
  94299. _this._lineBoundingBox = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  94300. _this._lineBoundingBox.rotationQuaternion = new BABYLON.Quaternion();
  94301. var lines = [];
  94302. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0)] }, gizmoLayer.utilityLayerScene));
  94303. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  94304. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  94305. 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));
  94306. 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));
  94307. 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));
  94308. 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));
  94309. 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));
  94310. 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));
  94311. 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));
  94312. 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));
  94313. 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));
  94314. lines.forEach(function (l) {
  94315. l.color = color;
  94316. l.position.addInPlace(new BABYLON.Vector3(-_this._boundingDimensions.x / 2, -_this._boundingDimensions.y / 2, -_this._boundingDimensions.z / 2));
  94317. l.isPickable = false;
  94318. _this._lineBoundingBox.addChild(l);
  94319. });
  94320. _this._rootMesh.addChild(_this._lineBoundingBox);
  94321. // Create rotation spheres
  94322. _this._rotateSpheresParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  94323. _this._rotateSpheresParent.rotationQuaternion = new BABYLON.Quaternion();
  94324. var _loop_1 = function (i_1) {
  94325. var sphere = BABYLON.MeshBuilder.CreateSphere("", { diameter: 1 }, gizmoLayer.utilityLayerScene);
  94326. sphere.rotationQuaternion = new BABYLON.Quaternion();
  94327. sphere.material = coloredMaterial;
  94328. // Drag behavior
  94329. _dragBehavior = new BABYLON.PointerDragBehavior({});
  94330. _dragBehavior.moveAttached = false;
  94331. _dragBehavior.updateDragPlane = false;
  94332. sphere.addBehavior(_dragBehavior);
  94333. var startingTurnDirection = new BABYLON.Vector3(1, 0, 0);
  94334. var totalTurnAmountOfDrag = 0;
  94335. _dragBehavior.onDragStartObservable.add(function (event) {
  94336. startingTurnDirection.copyFrom(sphere.forward);
  94337. totalTurnAmountOfDrag = 0;
  94338. });
  94339. _dragBehavior.onDragObservable.add(function (event) {
  94340. _this.onRotationSphereDragObservable.notifyObservers({});
  94341. if (_this.attachedMesh) {
  94342. BoundingBoxGizmo._RemoveAndStorePivotPoint(_this.attachedMesh);
  94343. var worldDragDirection = startingTurnDirection;
  94344. // Project the world right on to the drag plane
  94345. var toSub = event.dragPlaneNormal.scale(BABYLON.Vector3.Dot(event.dragPlaneNormal, worldDragDirection));
  94346. var dragAxis = worldDragDirection.subtract(toSub).normalizeToNew();
  94347. // project drag delta on to the resulting drag axis and rotate based on that
  94348. var projectDist = -BABYLON.Vector3.Dot(dragAxis, event.delta);
  94349. // Make rotation relative to size of mesh.
  94350. projectDist = (projectDist / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  94351. // Rotate based on axis
  94352. if (!_this.attachedMesh.rotationQuaternion) {
  94353. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  94354. }
  94355. if (!_this._anchorMesh.rotationQuaternion) {
  94356. _this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._anchorMesh.rotation.y, _this._anchorMesh.rotation.x, _this._anchorMesh.rotation.z);
  94357. }
  94358. // Do not allow the object to turn more than a full circle
  94359. totalTurnAmountOfDrag += projectDist;
  94360. if (Math.abs(totalTurnAmountOfDrag) <= 2 * Math.PI) {
  94361. if (i_1 >= 8) {
  94362. BABYLON.Quaternion.RotationYawPitchRollToRef(0, 0, projectDist, _this._tmpQuaternion);
  94363. }
  94364. else if (i_1 >= 4) {
  94365. BABYLON.Quaternion.RotationYawPitchRollToRef(projectDist, 0, 0, _this._tmpQuaternion);
  94366. }
  94367. else {
  94368. BABYLON.Quaternion.RotationYawPitchRollToRef(0, projectDist, 0, _this._tmpQuaternion);
  94369. }
  94370. // Rotate around center of bounding box
  94371. _this._anchorMesh.addChild(_this.attachedMesh);
  94372. _this._anchorMesh.rotationQuaternion.multiplyToRef(_this._tmpQuaternion, _this._anchorMesh.rotationQuaternion);
  94373. _this._anchorMesh.removeChild(_this.attachedMesh);
  94374. }
  94375. _this.updateBoundingBox();
  94376. BoundingBoxGizmo._RestorePivotPoint(_this.attachedMesh);
  94377. }
  94378. });
  94379. // Selection/deselection
  94380. _dragBehavior.onDragStartObservable.add(function () {
  94381. _this.onDragStartObservable.notifyObservers({});
  94382. _this._selectNode(sphere);
  94383. });
  94384. _dragBehavior.onDragEndObservable.add(function () {
  94385. _this.onRotationSphereDragEndObservable.notifyObservers({});
  94386. _this._selectNode(null);
  94387. });
  94388. this_1._rotateSpheresParent.addChild(sphere);
  94389. };
  94390. var this_1 = this, _dragBehavior;
  94391. for (var i_1 = 0; i_1 < 12; i_1++) {
  94392. _loop_1(i_1);
  94393. }
  94394. _this._rootMesh.addChild(_this._rotateSpheresParent);
  94395. // Create scale cubes
  94396. _this._scaleBoxesParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  94397. _this._scaleBoxesParent.rotationQuaternion = new BABYLON.Quaternion();
  94398. for (var i = 0; i < 2; i++) {
  94399. for (var j = 0; j < 2; j++) {
  94400. var _loop_2 = function () {
  94401. var box = BABYLON.MeshBuilder.CreateBox("", { size: 1 }, gizmoLayer.utilityLayerScene);
  94402. box.material = coloredMaterial;
  94403. // Dragging logic
  94404. var dragAxis = new BABYLON.Vector3(i == 0 ? -1 : 1, j == 0 ? -1 : 1, k == 0 ? -1 : 1);
  94405. _dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  94406. _dragBehavior.moveAttached = false;
  94407. box.addBehavior(_dragBehavior);
  94408. _dragBehavior.onDragObservable.add(function (event) {
  94409. _this.onScaleBoxDragObservable.notifyObservers({});
  94410. if (_this.attachedMesh) {
  94411. BoundingBoxGizmo._RemoveAndStorePivotPoint(_this.attachedMesh);
  94412. var relativeDragDistance = (event.dragDistance / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  94413. var deltaScale = new BABYLON.Vector3(relativeDragDistance, relativeDragDistance, relativeDragDistance);
  94414. deltaScale.scaleInPlace(_this._scaleDragSpeed);
  94415. _this.updateBoundingBox();
  94416. if (_this.scalePivot) {
  94417. _this.attachedMesh.getWorldMatrix().getRotationMatrixToRef(_this._tmpRotationMatrix);
  94418. // Move anchor to desired pivot point (Bottom left corner + dimension/2)
  94419. _this._boundingDimensions.scaleToRef(0.5, _this._tmpVector);
  94420. BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
  94421. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  94422. _this._boundingDimensions.multiplyToRef(_this.scalePivot, _this._tmpVector);
  94423. BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
  94424. _this._anchorMesh.position.addInPlace(_this._tmpVector);
  94425. }
  94426. else {
  94427. // Scale from the position of the opposite corner
  94428. box.absolutePosition.subtractToRef(_this._anchorMesh.position, _this._tmpVector);
  94429. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  94430. }
  94431. _this._anchorMesh.addChild(_this.attachedMesh);
  94432. _this._anchorMesh.scaling.addInPlace(deltaScale);
  94433. if (_this._anchorMesh.scaling.x < 0 || _this._anchorMesh.scaling.y < 0 || _this._anchorMesh.scaling.z < 0) {
  94434. _this._anchorMesh.scaling.subtractInPlace(deltaScale);
  94435. }
  94436. _this._anchorMesh.removeChild(_this.attachedMesh);
  94437. BoundingBoxGizmo._RestorePivotPoint(_this.attachedMesh);
  94438. }
  94439. });
  94440. // Selection/deselection
  94441. _dragBehavior.onDragStartObservable.add(function () {
  94442. _this.onDragStartObservable.notifyObservers({});
  94443. _this._selectNode(box);
  94444. });
  94445. _dragBehavior.onDragEndObservable.add(function () {
  94446. _this.onScaleBoxDragEndObservable.notifyObservers({});
  94447. _this._selectNode(null);
  94448. });
  94449. this_2._scaleBoxesParent.addChild(box);
  94450. };
  94451. var this_2 = this, _dragBehavior;
  94452. for (var k = 0; k < 2; k++) {
  94453. _loop_2();
  94454. }
  94455. }
  94456. }
  94457. _this._rootMesh.addChild(_this._scaleBoxesParent);
  94458. // Hover color change
  94459. var pointerIds = new Array();
  94460. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  94461. if (!pointerIds[pointerInfo.event.pointerId]) {
  94462. _this._rotateSpheresParent.getChildMeshes().concat(_this._scaleBoxesParent.getChildMeshes()).forEach(function (mesh) {
  94463. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh == mesh) {
  94464. pointerIds[pointerInfo.event.pointerId] = mesh;
  94465. mesh.material = hoverColoredMaterial;
  94466. }
  94467. });
  94468. }
  94469. else {
  94470. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh != pointerIds[pointerInfo.event.pointerId]) {
  94471. pointerIds[pointerInfo.event.pointerId].material = coloredMaterial;
  94472. delete pointerIds[pointerInfo.event.pointerId];
  94473. }
  94474. }
  94475. });
  94476. // Update bounding box positions
  94477. _this._renderObserver = _this.gizmoLayer.originalScene.onBeforeRenderObservable.add(function () {
  94478. // Only update the bouding box if scaling has changed
  94479. if (_this.attachedMesh && !_this._existingMeshScale.equals(_this.attachedMesh.scaling)) {
  94480. _this.updateBoundingBox();
  94481. }
  94482. });
  94483. _this.updateBoundingBox();
  94484. return _this;
  94485. }
  94486. /** @hidden */
  94487. BoundingBoxGizmo._RemoveAndStorePivotPoint = function (mesh) {
  94488. if (mesh && BoundingBoxGizmo._PivotCached === 0) {
  94489. // Save old pivot and set pivot to 0,0,0
  94490. mesh.getPivotPointToRef(BoundingBoxGizmo._OldPivotPoint);
  94491. if (!BoundingBoxGizmo._OldPivotPoint.equalsToFloats(0, 0, 0)) {
  94492. mesh.setPivotMatrix(BABYLON.Matrix.IdentityReadOnly);
  94493. BoundingBoxGizmo._OldPivotPoint.subtractToRef(mesh.getPivotPoint(), BoundingBoxGizmo._PivotTranslation);
  94494. BoundingBoxGizmo._PivotTmpVector.copyFromFloats(1, 1, 1);
  94495. BoundingBoxGizmo._PivotTmpVector.subtractInPlace(mesh.scaling);
  94496. BoundingBoxGizmo._PivotTmpVector.multiplyInPlace(BoundingBoxGizmo._PivotTranslation);
  94497. mesh.position.addInPlace(BoundingBoxGizmo._PivotTmpVector);
  94498. }
  94499. }
  94500. BoundingBoxGizmo._PivotCached++;
  94501. };
  94502. /** @hidden */
  94503. BoundingBoxGizmo._RestorePivotPoint = function (mesh) {
  94504. if (mesh && !BoundingBoxGizmo._OldPivotPoint.equalsToFloats(0, 0, 0) && BoundingBoxGizmo._PivotCached === 1) {
  94505. mesh.setPivotPoint(BoundingBoxGizmo._OldPivotPoint);
  94506. BoundingBoxGizmo._PivotTmpVector.copyFromFloats(1, 1, 1);
  94507. BoundingBoxGizmo._PivotTmpVector.subtractInPlace(mesh.scaling);
  94508. BoundingBoxGizmo._PivotTmpVector.multiplyInPlace(BoundingBoxGizmo._PivotTranslation);
  94509. mesh.position.subtractInPlace(BoundingBoxGizmo._PivotTmpVector);
  94510. }
  94511. this._PivotCached--;
  94512. };
  94513. BoundingBoxGizmo.prototype._attachedMeshChanged = function (value) {
  94514. if (value) {
  94515. // Reset anchor mesh to match attached mesh's scale
  94516. // This is needed to avoid invalid box/sphere position on first drag
  94517. BoundingBoxGizmo._RemoveAndStorePivotPoint(value);
  94518. this._anchorMesh.addChild(value);
  94519. this._anchorMesh.removeChild(value);
  94520. BoundingBoxGizmo._RestorePivotPoint(value);
  94521. this.updateBoundingBox();
  94522. }
  94523. };
  94524. BoundingBoxGizmo.prototype._selectNode = function (selectedMesh) {
  94525. this._rotateSpheresParent.getChildMeshes()
  94526. .concat(this._scaleBoxesParent.getChildMeshes()).forEach(function (m, i) {
  94527. m.isVisible = (!selectedMesh || m == selectedMesh);
  94528. });
  94529. };
  94530. /**
  94531. * Updates the bounding box information for the Gizmo
  94532. */
  94533. BoundingBoxGizmo.prototype.updateBoundingBox = function () {
  94534. if (this.attachedMesh) {
  94535. BoundingBoxGizmo._RemoveAndStorePivotPoint(this.attachedMesh);
  94536. this._update();
  94537. // Rotate based on axis
  94538. if (!this.attachedMesh.rotationQuaternion) {
  94539. this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.attachedMesh.rotation.y, this.attachedMesh.rotation.x, this.attachedMesh.rotation.z);
  94540. }
  94541. if (!this._anchorMesh.rotationQuaternion) {
  94542. this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._anchorMesh.rotation.y, this._anchorMesh.rotation.x, this._anchorMesh.rotation.z);
  94543. }
  94544. this._anchorMesh.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  94545. // Store original position and reset mesh to origin before computing the bounding box
  94546. this._tmpQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  94547. this._tmpVector.copyFrom(this.attachedMesh.position);
  94548. this.attachedMesh.rotationQuaternion.set(0, 0, 0, 1);
  94549. this.attachedMesh.position.set(0, 0, 0);
  94550. // Update bounding dimensions/positions
  94551. var boundingMinMax = this.attachedMesh.getHierarchyBoundingVectors(!this.ignoreChildren, this.includeChildPredicate);
  94552. boundingMinMax.max.subtractToRef(boundingMinMax.min, this._boundingDimensions);
  94553. // Update gizmo to match bounding box scaling and rotation
  94554. this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions);
  94555. 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);
  94556. this._rotateSpheresParent.position.copyFrom(this._lineBoundingBox.position);
  94557. this._scaleBoxesParent.position.copyFrom(this._lineBoundingBox.position);
  94558. this._lineBoundingBox.computeWorldMatrix();
  94559. this._anchorMesh.position.copyFrom(this._lineBoundingBox.absolutePosition);
  94560. // restore position/rotation values
  94561. this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion);
  94562. this.attachedMesh.position.copyFrom(this._tmpVector);
  94563. }
  94564. // Update rotation sphere locations
  94565. var rotateSpheres = this._rotateSpheresParent.getChildMeshes();
  94566. for (var i = 0; i < 3; i++) {
  94567. for (var j = 0; j < 2; j++) {
  94568. for (var k = 0; k < 2; k++) {
  94569. var index = ((i * 4) + (j * 2)) + k;
  94570. if (i == 0) {
  94571. rotateSpheres[index].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  94572. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  94573. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Right(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  94574. }
  94575. if (i == 1) {
  94576. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y / 2, this._boundingDimensions.z * k);
  94577. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  94578. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Up(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  94579. }
  94580. if (i == 2) {
  94581. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y * k, this._boundingDimensions.z / 2);
  94582. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  94583. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Forward(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  94584. }
  94585. if (this.fixedDragMeshScreenSize) {
  94586. this._rootMesh.computeWorldMatrix();
  94587. this._rotateSpheresParent.computeWorldMatrix();
  94588. rotateSpheres[index].computeWorldMatrix();
  94589. rotateSpheres[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  94590. var distanceFromCamera = this.rotationSphereSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  94591. rotateSpheres[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  94592. }
  94593. else {
  94594. rotateSpheres[index].scaling.set(this.rotationSphereSize, this.rotationSphereSize, this.rotationSphereSize);
  94595. }
  94596. }
  94597. }
  94598. }
  94599. // Update scale box locations
  94600. var scaleBoxes = this._scaleBoxesParent.getChildMeshes();
  94601. for (var i = 0; i < 2; i++) {
  94602. for (var j = 0; j < 2; j++) {
  94603. for (var k = 0; k < 2; k++) {
  94604. var index = ((i * 4) + (j * 2)) + k;
  94605. if (scaleBoxes[index]) {
  94606. scaleBoxes[index].position.set(this._boundingDimensions.x * i, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  94607. scaleBoxes[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  94608. if (this.fixedDragMeshScreenSize) {
  94609. this._rootMesh.computeWorldMatrix();
  94610. this._scaleBoxesParent.computeWorldMatrix();
  94611. scaleBoxes[index].computeWorldMatrix();
  94612. scaleBoxes[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  94613. var distanceFromCamera = this.scaleBoxSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  94614. scaleBoxes[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  94615. }
  94616. else {
  94617. scaleBoxes[index].scaling.set(this.scaleBoxSize, this.scaleBoxSize, this.scaleBoxSize);
  94618. }
  94619. }
  94620. }
  94621. }
  94622. }
  94623. if (this.attachedMesh) {
  94624. this._existingMeshScale.copyFrom(this.attachedMesh.scaling);
  94625. BoundingBoxGizmo._RestorePivotPoint(this.attachedMesh);
  94626. }
  94627. };
  94628. /**
  94629. * Enables rotation on the specified axis and disables rotation on the others
  94630. * @param axis The list of axis that should be enabled (eg. "xy" or "xyz")
  94631. */
  94632. BoundingBoxGizmo.prototype.setEnabledRotationAxis = function (axis) {
  94633. this._rotateSpheresParent.getChildMeshes().forEach(function (m, i) {
  94634. if (i < 4) {
  94635. m.setEnabled(axis.indexOf("x") != -1);
  94636. }
  94637. else if (i < 8) {
  94638. m.setEnabled(axis.indexOf("y") != -1);
  94639. }
  94640. else {
  94641. m.setEnabled(axis.indexOf("z") != -1);
  94642. }
  94643. });
  94644. };
  94645. /**
  94646. * Disposes of the gizmo
  94647. */
  94648. BoundingBoxGizmo.prototype.dispose = function () {
  94649. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  94650. this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver);
  94651. this._lineBoundingBox.dispose();
  94652. this._rotateSpheresParent.dispose();
  94653. this._scaleBoxesParent.dispose();
  94654. _super.prototype.dispose.call(this);
  94655. };
  94656. /**
  94657. * 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)
  94658. * @param mesh the mesh to wrap in the bounding box mesh and make not pickable
  94659. * @returns the bounding box mesh with the passed in mesh as a child
  94660. */
  94661. BoundingBoxGizmo.MakeNotPickableAndWrapInBoundingBox = function (mesh) {
  94662. var makeNotPickable = function (root) {
  94663. root.isPickable = false;
  94664. root.getChildMeshes().forEach(function (c) {
  94665. makeNotPickable(c);
  94666. });
  94667. };
  94668. makeNotPickable(mesh);
  94669. // Reset position to get boudning box from origin with no rotation
  94670. if (!mesh.rotationQuaternion) {
  94671. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  94672. }
  94673. var oldPos = mesh.position.clone();
  94674. var oldRot = mesh.rotationQuaternion.clone();
  94675. mesh.rotationQuaternion.set(0, 0, 0, 1);
  94676. mesh.position.set(0, 0, 0);
  94677. // Update bounding dimensions/positions
  94678. var box = BABYLON.MeshBuilder.CreateBox("box", { size: 1 }, mesh.getScene());
  94679. var boundingMinMax = mesh.getHierarchyBoundingVectors();
  94680. boundingMinMax.max.subtractToRef(boundingMinMax.min, box.scaling);
  94681. box.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2);
  94682. // Restore original positions
  94683. mesh.addChild(box);
  94684. mesh.rotationQuaternion.copyFrom(oldRot);
  94685. mesh.position.copyFrom(oldPos);
  94686. // Reverse parenting
  94687. mesh.removeChild(box);
  94688. box.addChild(mesh);
  94689. box.visibility = 0;
  94690. return box;
  94691. };
  94692. /**
  94693. * CustomMeshes are not supported by this gizmo
  94694. * @param mesh The mesh to replace the default mesh of the gizmo
  94695. */
  94696. BoundingBoxGizmo.prototype.setCustomMesh = function (mesh) {
  94697. BABYLON.Tools.Error("Custom meshes are not supported on this gizmo");
  94698. };
  94699. // Stores the state of the pivot cache (_oldPivotPoint, _pivotTranslation)
  94700. // store/remove pivot point should only be applied during their outermost calls
  94701. BoundingBoxGizmo._PivotCached = 0;
  94702. BoundingBoxGizmo._OldPivotPoint = new BABYLON.Vector3();
  94703. BoundingBoxGizmo._PivotTranslation = new BABYLON.Vector3();
  94704. BoundingBoxGizmo._PivotTmpVector = new BABYLON.Vector3();
  94705. return BoundingBoxGizmo;
  94706. }(BABYLON.Gizmo));
  94707. BABYLON.BoundingBoxGizmo = BoundingBoxGizmo;
  94708. })(BABYLON || (BABYLON = {}));
  94709. //# sourceMappingURL=babylon.boundingBoxGizmo.js.map
  94710. var BABYLON;
  94711. (function (BABYLON) {
  94712. /**
  94713. * Helps setup gizmo's in the scene to rotate/scale/position meshes
  94714. */
  94715. var GizmoManager = /** @class */ (function () {
  94716. /**
  94717. * Instatiates a gizmo manager
  94718. * @param scene the scene to overlay the gizmos on top of
  94719. */
  94720. function GizmoManager(scene) {
  94721. var _this = this;
  94722. this.scene = scene;
  94723. this._gizmosEnabled = { positionGizmo: false, rotationGizmo: false, scaleGizmo: false, boundingBoxGizmo: false };
  94724. this._pointerObserver = null;
  94725. this._attachedMesh = null;
  94726. this._boundingBoxColor = BABYLON.Color3.FromHexString("#0984e3");
  94727. this._dragBehavior = new BABYLON.SixDofDragBehavior();
  94728. /**
  94729. * Array of meshes which will have the gizmo attached when a pointer selected them. If null, all meshes are attachable. (Default: null)
  94730. */
  94731. this.attachableMeshes = null;
  94732. /**
  94733. * If pointer events should perform attaching/detaching a gizmo, if false this can be done manually via attachToMesh. (Default: true)
  94734. */
  94735. this.usePointerToAttachGizmos = true;
  94736. this.gizmos = { positionGizmo: null, rotationGizmo: null, scaleGizmo: null, boundingBoxGizmo: null };
  94737. // Instatiate/dispose gizmos based on pointer actions
  94738. this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo, state) {
  94739. if (!_this.usePointerToAttachGizmos) {
  94740. return;
  94741. }
  94742. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  94743. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {
  94744. var node = pointerInfo.pickInfo.pickedMesh;
  94745. if (_this.attachableMeshes == null) {
  94746. // Attach to the most parent node
  94747. while (node && node.parent != null) {
  94748. node = node.parent;
  94749. }
  94750. }
  94751. else {
  94752. // Attach to the parent node that is an attachableMesh
  94753. var found = false;
  94754. _this.attachableMeshes.forEach(function (mesh) {
  94755. if (node && (node == mesh || node.isDescendantOf(mesh))) {
  94756. node = mesh;
  94757. found = true;
  94758. }
  94759. });
  94760. if (!found) {
  94761. node = null;
  94762. }
  94763. }
  94764. if (node instanceof BABYLON.AbstractMesh) {
  94765. _this.attachToMesh(node);
  94766. }
  94767. else {
  94768. _this.attachToMesh(null);
  94769. }
  94770. }
  94771. else {
  94772. _this.attachToMesh(null);
  94773. }
  94774. }
  94775. });
  94776. }
  94777. /**
  94778. * Attaches a set of gizmos to the specified mesh
  94779. * @param mesh The mesh the gizmo's should be attached to
  94780. */
  94781. GizmoManager.prototype.attachToMesh = function (mesh) {
  94782. if (this._attachedMesh) {
  94783. this._attachedMesh.removeBehavior(this._dragBehavior);
  94784. }
  94785. this._attachedMesh = mesh;
  94786. for (var key in this.gizmos) {
  94787. var gizmo = (this.gizmos[key]);
  94788. if (gizmo && this._gizmosEnabled[key]) {
  94789. gizmo.attachedMesh = mesh;
  94790. }
  94791. }
  94792. if (this.boundingBoxGizmoEnabled && this._attachedMesh) {
  94793. this._attachedMesh.addBehavior(this._dragBehavior);
  94794. }
  94795. };
  94796. Object.defineProperty(GizmoManager.prototype, "positionGizmoEnabled", {
  94797. get: function () {
  94798. return this._gizmosEnabled.positionGizmo;
  94799. },
  94800. /**
  94801. * If the position gizmo is enabled
  94802. */
  94803. set: function (value) {
  94804. if (value) {
  94805. if (!this.gizmos.positionGizmo) {
  94806. this.gizmos.positionGizmo = new BABYLON.PositionGizmo();
  94807. this.gizmos.positionGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  94808. }
  94809. this.gizmos.positionGizmo.attachedMesh = this._attachedMesh;
  94810. }
  94811. else if (this.gizmos.positionGizmo) {
  94812. this.gizmos.positionGizmo.attachedMesh = null;
  94813. }
  94814. this._gizmosEnabled.positionGizmo = value;
  94815. },
  94816. enumerable: true,
  94817. configurable: true
  94818. });
  94819. Object.defineProperty(GizmoManager.prototype, "rotationGizmoEnabled", {
  94820. get: function () {
  94821. return this._gizmosEnabled.rotationGizmo;
  94822. },
  94823. /**
  94824. * If the rotation gizmo is enabled
  94825. */
  94826. set: function (value) {
  94827. if (value) {
  94828. if (!this.gizmos.rotationGizmo) {
  94829. this.gizmos.rotationGizmo = new BABYLON.RotationGizmo();
  94830. this.gizmos.rotationGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  94831. }
  94832. this.gizmos.rotationGizmo.attachedMesh = this._attachedMesh;
  94833. }
  94834. else if (this.gizmos.rotationGizmo) {
  94835. this.gizmos.rotationGizmo.attachedMesh = null;
  94836. }
  94837. this._gizmosEnabled.rotationGizmo = value;
  94838. },
  94839. enumerable: true,
  94840. configurable: true
  94841. });
  94842. Object.defineProperty(GizmoManager.prototype, "scaleGizmoEnabled", {
  94843. get: function () {
  94844. return this._gizmosEnabled.scaleGizmo;
  94845. },
  94846. /**
  94847. * If the scale gizmo is enabled
  94848. */
  94849. set: function (value) {
  94850. if (value) {
  94851. this.gizmos.scaleGizmo = this.gizmos.scaleGizmo || new BABYLON.ScaleGizmo();
  94852. this.gizmos.scaleGizmo.attachedMesh = this._attachedMesh;
  94853. }
  94854. else if (this.gizmos.scaleGizmo) {
  94855. this.gizmos.scaleGizmo.attachedMesh = null;
  94856. }
  94857. this._gizmosEnabled.scaleGizmo = value;
  94858. },
  94859. enumerable: true,
  94860. configurable: true
  94861. });
  94862. Object.defineProperty(GizmoManager.prototype, "boundingBoxGizmoEnabled", {
  94863. get: function () {
  94864. return this._gizmosEnabled.boundingBoxGizmo;
  94865. },
  94866. /**
  94867. * If the boundingBox gizmo is enabled
  94868. */
  94869. set: function (value) {
  94870. if (value) {
  94871. this.gizmos.boundingBoxGizmo = this.gizmos.boundingBoxGizmo || new BABYLON.BoundingBoxGizmo(this._boundingBoxColor);
  94872. this.gizmos.boundingBoxGizmo.attachedMesh = this._attachedMesh;
  94873. if (this._attachedMesh) {
  94874. this._attachedMesh.removeBehavior(this._dragBehavior);
  94875. this._attachedMesh.addBehavior(this._dragBehavior);
  94876. }
  94877. }
  94878. else if (this.gizmos.boundingBoxGizmo) {
  94879. this.gizmos.boundingBoxGizmo.attachedMesh = null;
  94880. }
  94881. this._gizmosEnabled.boundingBoxGizmo = value;
  94882. },
  94883. enumerable: true,
  94884. configurable: true
  94885. });
  94886. /**
  94887. * Disposes of the gizmo manager
  94888. */
  94889. GizmoManager.prototype.dispose = function () {
  94890. this.scene.onPointerObservable.remove(this._pointerObserver);
  94891. for (var key in this.gizmos) {
  94892. var gizmo = (this.gizmos[key]);
  94893. if (gizmo) {
  94894. gizmo.dispose();
  94895. }
  94896. }
  94897. this._dragBehavior.detach();
  94898. };
  94899. return GizmoManager;
  94900. }());
  94901. BABYLON.GizmoManager = GizmoManager;
  94902. })(BABYLON || (BABYLON = {}));
  94903. //# sourceMappingURL=babylon.gizmoManager.js.map
  94904. var BABYLON;
  94905. (function (BABYLON) {
  94906. /**
  94907. * Defines a target to use with MorphTargetManager
  94908. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  94909. */
  94910. var MorphTarget = /** @class */ (function () {
  94911. /**
  94912. * Creates a new MorphTarget
  94913. * @param name defines the name of the target
  94914. * @param influence defines the influence to use
  94915. */
  94916. function MorphTarget(
  94917. /** defines the name of the target */
  94918. name, influence, scene) {
  94919. if (influence === void 0) { influence = 0; }
  94920. if (scene === void 0) { scene = null; }
  94921. this.name = name;
  94922. /**
  94923. * Gets or sets the list of animations
  94924. */
  94925. this.animations = new Array();
  94926. this._positions = null;
  94927. this._normals = null;
  94928. this._tangents = null;
  94929. /**
  94930. * Observable raised when the influence changes
  94931. */
  94932. this.onInfluenceChanged = new BABYLON.Observable();
  94933. this._animationPropertiesOverride = null;
  94934. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  94935. this.influence = influence;
  94936. }
  94937. Object.defineProperty(MorphTarget.prototype, "influence", {
  94938. /**
  94939. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  94940. */
  94941. get: function () {
  94942. return this._influence;
  94943. },
  94944. set: function (influence) {
  94945. if (this._influence === influence) {
  94946. return;
  94947. }
  94948. var previous = this._influence;
  94949. this._influence = influence;
  94950. if (this.onInfluenceChanged.hasObservers) {
  94951. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  94952. }
  94953. },
  94954. enumerable: true,
  94955. configurable: true
  94956. });
  94957. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  94958. /**
  94959. * Gets or sets the animation properties override
  94960. */
  94961. get: function () {
  94962. if (!this._animationPropertiesOverride && this._scene) {
  94963. return this._scene.animationPropertiesOverride;
  94964. }
  94965. return this._animationPropertiesOverride;
  94966. },
  94967. set: function (value) {
  94968. this._animationPropertiesOverride = value;
  94969. },
  94970. enumerable: true,
  94971. configurable: true
  94972. });
  94973. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  94974. /**
  94975. * Gets a boolean defining if the target contains position data
  94976. */
  94977. get: function () {
  94978. return !!this._positions;
  94979. },
  94980. enumerable: true,
  94981. configurable: true
  94982. });
  94983. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  94984. /**
  94985. * Gets a boolean defining if the target contains normal data
  94986. */
  94987. get: function () {
  94988. return !!this._normals;
  94989. },
  94990. enumerable: true,
  94991. configurable: true
  94992. });
  94993. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  94994. /**
  94995. * Gets a boolean defining if the target contains tangent data
  94996. */
  94997. get: function () {
  94998. return !!this._tangents;
  94999. },
  95000. enumerable: true,
  95001. configurable: true
  95002. });
  95003. /**
  95004. * Affects position data to this target
  95005. * @param data defines the position data to use
  95006. */
  95007. MorphTarget.prototype.setPositions = function (data) {
  95008. this._positions = data;
  95009. };
  95010. /**
  95011. * Gets the position data stored in this target
  95012. * @returns a FloatArray containing the position data (or null if not present)
  95013. */
  95014. MorphTarget.prototype.getPositions = function () {
  95015. return this._positions;
  95016. };
  95017. /**
  95018. * Affects normal data to this target
  95019. * @param data defines the normal data to use
  95020. */
  95021. MorphTarget.prototype.setNormals = function (data) {
  95022. this._normals = data;
  95023. };
  95024. /**
  95025. * Gets the normal data stored in this target
  95026. * @returns a FloatArray containing the normal data (or null if not present)
  95027. */
  95028. MorphTarget.prototype.getNormals = function () {
  95029. return this._normals;
  95030. };
  95031. /**
  95032. * Affects tangent data to this target
  95033. * @param data defines the tangent data to use
  95034. */
  95035. MorphTarget.prototype.setTangents = function (data) {
  95036. this._tangents = data;
  95037. };
  95038. /**
  95039. * Gets the tangent data stored in this target
  95040. * @returns a FloatArray containing the tangent data (or null if not present)
  95041. */
  95042. MorphTarget.prototype.getTangents = function () {
  95043. return this._tangents;
  95044. };
  95045. /**
  95046. * Serializes the current target into a Serialization object
  95047. * @returns the serialized object
  95048. */
  95049. MorphTarget.prototype.serialize = function () {
  95050. var serializationObject = {};
  95051. serializationObject.name = this.name;
  95052. serializationObject.influence = this.influence;
  95053. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  95054. if (this.hasNormals) {
  95055. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  95056. }
  95057. if (this.hasTangents) {
  95058. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  95059. }
  95060. // Animations
  95061. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  95062. return serializationObject;
  95063. };
  95064. // Statics
  95065. /**
  95066. * Creates a new target from serialized data
  95067. * @param serializationObject defines the serialized data to use
  95068. * @returns a new MorphTarget
  95069. */
  95070. MorphTarget.Parse = function (serializationObject) {
  95071. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  95072. result.setPositions(serializationObject.positions);
  95073. if (serializationObject.normals) {
  95074. result.setNormals(serializationObject.normals);
  95075. }
  95076. if (serializationObject.tangents) {
  95077. result.setTangents(serializationObject.tangents);
  95078. }
  95079. // Animations
  95080. if (serializationObject.animations) {
  95081. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  95082. var parsedAnimation = serializationObject.animations[animationIndex];
  95083. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  95084. }
  95085. }
  95086. return result;
  95087. };
  95088. /**
  95089. * Creates a MorphTarget from mesh data
  95090. * @param mesh defines the source mesh
  95091. * @param name defines the name to use for the new target
  95092. * @param influence defines the influence to attach to the target
  95093. * @returns a new MorphTarget
  95094. */
  95095. MorphTarget.FromMesh = function (mesh, name, influence) {
  95096. if (!name) {
  95097. name = mesh.name;
  95098. }
  95099. var result = new MorphTarget(name, influence, mesh.getScene());
  95100. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  95101. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  95102. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  95103. }
  95104. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  95105. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  95106. }
  95107. return result;
  95108. };
  95109. return MorphTarget;
  95110. }());
  95111. BABYLON.MorphTarget = MorphTarget;
  95112. })(BABYLON || (BABYLON = {}));
  95113. //# sourceMappingURL=babylon.morphTarget.js.map
  95114. var BABYLON;
  95115. (function (BABYLON) {
  95116. /**
  95117. * This class is used to deform meshes using morphing between different targets
  95118. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  95119. */
  95120. var MorphTargetManager = /** @class */ (function () {
  95121. /**
  95122. * Creates a new MorphTargetManager
  95123. * @param scene defines the current scene
  95124. */
  95125. function MorphTargetManager(scene) {
  95126. if (scene === void 0) { scene = null; }
  95127. this._targets = new Array();
  95128. this._targetObservable = new Array();
  95129. this._activeTargets = new BABYLON.SmartArray(16);
  95130. this._supportsNormals = false;
  95131. this._supportsTangents = false;
  95132. this._vertexCount = 0;
  95133. this._uniqueId = 0;
  95134. this._tempInfluences = new Array();
  95135. if (!scene) {
  95136. scene = BABYLON.Engine.LastCreatedScene;
  95137. }
  95138. this._scene = scene;
  95139. if (this._scene) {
  95140. this._scene.morphTargetManagers.push(this);
  95141. this._uniqueId = this._scene.getUniqueId();
  95142. }
  95143. }
  95144. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  95145. /**
  95146. * Gets the unique ID of this manager
  95147. */
  95148. get: function () {
  95149. return this._uniqueId;
  95150. },
  95151. enumerable: true,
  95152. configurable: true
  95153. });
  95154. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  95155. /**
  95156. * Gets the number of vertices handled by this manager
  95157. */
  95158. get: function () {
  95159. return this._vertexCount;
  95160. },
  95161. enumerable: true,
  95162. configurable: true
  95163. });
  95164. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  95165. /**
  95166. * Gets a boolean indicating if this manager supports morphing of normals
  95167. */
  95168. get: function () {
  95169. return this._supportsNormals;
  95170. },
  95171. enumerable: true,
  95172. configurable: true
  95173. });
  95174. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  95175. /**
  95176. * Gets a boolean indicating if this manager supports morphing of tangents
  95177. */
  95178. get: function () {
  95179. return this._supportsTangents;
  95180. },
  95181. enumerable: true,
  95182. configurable: true
  95183. });
  95184. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  95185. /**
  95186. * Gets the number of targets stored in this manager
  95187. */
  95188. get: function () {
  95189. return this._targets.length;
  95190. },
  95191. enumerable: true,
  95192. configurable: true
  95193. });
  95194. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  95195. /**
  95196. * Gets the number of influencers (ie. the number of targets with influences > 0)
  95197. */
  95198. get: function () {
  95199. return this._activeTargets.length;
  95200. },
  95201. enumerable: true,
  95202. configurable: true
  95203. });
  95204. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  95205. /**
  95206. * Gets the list of influences (one per target)
  95207. */
  95208. get: function () {
  95209. return this._influences;
  95210. },
  95211. enumerable: true,
  95212. configurable: true
  95213. });
  95214. /**
  95215. * Gets the active target at specified index. An active target is a target with an influence > 0
  95216. * @param index defines the index to check
  95217. * @returns the requested target
  95218. */
  95219. MorphTargetManager.prototype.getActiveTarget = function (index) {
  95220. return this._activeTargets.data[index];
  95221. };
  95222. /**
  95223. * Gets the target at specified index
  95224. * @param index defines the index to check
  95225. * @returns the requested target
  95226. */
  95227. MorphTargetManager.prototype.getTarget = function (index) {
  95228. return this._targets[index];
  95229. };
  95230. /**
  95231. * Add a new target to this manager
  95232. * @param target defines the target to add
  95233. */
  95234. MorphTargetManager.prototype.addTarget = function (target) {
  95235. var _this = this;
  95236. this._targets.push(target);
  95237. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  95238. _this._syncActiveTargets(needUpdate);
  95239. }));
  95240. this._syncActiveTargets(true);
  95241. };
  95242. /**
  95243. * Removes a target from the manager
  95244. * @param target defines the target to remove
  95245. */
  95246. MorphTargetManager.prototype.removeTarget = function (target) {
  95247. var index = this._targets.indexOf(target);
  95248. if (index >= 0) {
  95249. this._targets.splice(index, 1);
  95250. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  95251. this._syncActiveTargets(true);
  95252. }
  95253. };
  95254. /**
  95255. * Serializes the current manager into a Serialization object
  95256. * @returns the serialized object
  95257. */
  95258. MorphTargetManager.prototype.serialize = function () {
  95259. var serializationObject = {};
  95260. serializationObject.id = this.uniqueId;
  95261. serializationObject.targets = [];
  95262. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  95263. var target = _a[_i];
  95264. serializationObject.targets.push(target.serialize());
  95265. }
  95266. return serializationObject;
  95267. };
  95268. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  95269. var influenceCount = 0;
  95270. this._activeTargets.reset();
  95271. this._supportsNormals = true;
  95272. this._supportsTangents = true;
  95273. this._vertexCount = 0;
  95274. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  95275. var target = _a[_i];
  95276. this._activeTargets.push(target);
  95277. this._tempInfluences[influenceCount++] = target.influence;
  95278. var positions = target.getPositions();
  95279. if (positions) {
  95280. this._supportsNormals = this._supportsNormals && target.hasNormals;
  95281. this._supportsTangents = this._supportsTangents && target.hasTangents;
  95282. var vertexCount = positions.length / 3;
  95283. if (this._vertexCount === 0) {
  95284. this._vertexCount = vertexCount;
  95285. }
  95286. else if (this._vertexCount !== vertexCount) {
  95287. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  95288. return;
  95289. }
  95290. }
  95291. }
  95292. if (!this._influences || this._influences.length !== influenceCount) {
  95293. this._influences = new Float32Array(influenceCount);
  95294. }
  95295. for (var index = 0; index < influenceCount; index++) {
  95296. this._influences[index] = this._tempInfluences[index];
  95297. }
  95298. if (needUpdate) {
  95299. this.synchronize();
  95300. }
  95301. };
  95302. /**
  95303. * Syncrhonize the targets with all the meshes using this morph target manager
  95304. */
  95305. MorphTargetManager.prototype.synchronize = function () {
  95306. if (!this._scene) {
  95307. return;
  95308. }
  95309. // Flag meshes as dirty to resync with the active targets
  95310. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  95311. var mesh = _a[_i];
  95312. if (mesh.morphTargetManager === this) {
  95313. mesh._syncGeometryWithMorphTargetManager();
  95314. }
  95315. }
  95316. };
  95317. // Statics
  95318. /**
  95319. * Creates a new MorphTargetManager from serialized data
  95320. * @param serializationObject defines the serialized data
  95321. * @param scene defines the hosting scene
  95322. * @returns the new MorphTargetManager
  95323. */
  95324. MorphTargetManager.Parse = function (serializationObject, scene) {
  95325. var result = new MorphTargetManager(scene);
  95326. result._uniqueId = serializationObject.id;
  95327. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  95328. var targetData = _a[_i];
  95329. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  95330. }
  95331. return result;
  95332. };
  95333. return MorphTargetManager;
  95334. }());
  95335. BABYLON.MorphTargetManager = MorphTargetManager;
  95336. })(BABYLON || (BABYLON = {}));
  95337. //# sourceMappingURL=babylon.morphTargetManager.js.map
  95338. var BABYLON;
  95339. (function (BABYLON) {
  95340. var Octree = /** @class */ (function () {
  95341. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  95342. if (maxDepth === void 0) { maxDepth = 2; }
  95343. this.maxDepth = maxDepth;
  95344. this.dynamicContent = new Array();
  95345. this._maxBlockCapacity = maxBlockCapacity || 64;
  95346. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  95347. this._creationFunc = creationFunc;
  95348. }
  95349. // Methods
  95350. Octree.prototype.update = function (worldMin, worldMax, entries) {
  95351. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  95352. };
  95353. Octree.prototype.addMesh = function (entry) {
  95354. for (var index = 0; index < this.blocks.length; index++) {
  95355. var block = this.blocks[index];
  95356. block.addEntry(entry);
  95357. }
  95358. };
  95359. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  95360. this._selectionContent.reset();
  95361. for (var index = 0; index < this.blocks.length; index++) {
  95362. var block = this.blocks[index];
  95363. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  95364. }
  95365. if (allowDuplicate) {
  95366. this._selectionContent.concat(this.dynamicContent);
  95367. }
  95368. else {
  95369. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  95370. }
  95371. return this._selectionContent;
  95372. };
  95373. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  95374. this._selectionContent.reset();
  95375. for (var index = 0; index < this.blocks.length; index++) {
  95376. var block = this.blocks[index];
  95377. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  95378. }
  95379. if (allowDuplicate) {
  95380. this._selectionContent.concat(this.dynamicContent);
  95381. }
  95382. else {
  95383. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  95384. }
  95385. return this._selectionContent;
  95386. };
  95387. Octree.prototype.intersectsRay = function (ray) {
  95388. this._selectionContent.reset();
  95389. for (var index = 0; index < this.blocks.length; index++) {
  95390. var block = this.blocks[index];
  95391. block.intersectsRay(ray, this._selectionContent);
  95392. }
  95393. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  95394. return this._selectionContent;
  95395. };
  95396. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  95397. target.blocks = new Array();
  95398. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  95399. // Segmenting space
  95400. for (var x = 0; x < 2; x++) {
  95401. for (var y = 0; y < 2; y++) {
  95402. for (var z = 0; z < 2; z++) {
  95403. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  95404. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  95405. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  95406. block.addEntries(entries);
  95407. target.blocks.push(block);
  95408. }
  95409. }
  95410. }
  95411. };
  95412. Octree.CreationFuncForMeshes = function (entry, block) {
  95413. var boundingInfo = entry.getBoundingInfo();
  95414. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  95415. block.entries.push(entry);
  95416. }
  95417. };
  95418. Octree.CreationFuncForSubMeshes = function (entry, block) {
  95419. var boundingInfo = entry.getBoundingInfo();
  95420. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  95421. block.entries.push(entry);
  95422. }
  95423. };
  95424. return Octree;
  95425. }());
  95426. BABYLON.Octree = Octree;
  95427. })(BABYLON || (BABYLON = {}));
  95428. //# sourceMappingURL=babylon.octree.js.map
  95429. var BABYLON;
  95430. (function (BABYLON) {
  95431. var OctreeBlock = /** @class */ (function () {
  95432. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  95433. this.entries = new Array();
  95434. this._boundingVectors = new Array();
  95435. this._capacity = capacity;
  95436. this._depth = depth;
  95437. this._maxDepth = maxDepth;
  95438. this._creationFunc = creationFunc;
  95439. this._minPoint = minPoint;
  95440. this._maxPoint = maxPoint;
  95441. this._boundingVectors.push(minPoint.clone());
  95442. this._boundingVectors.push(maxPoint.clone());
  95443. this._boundingVectors.push(minPoint.clone());
  95444. this._boundingVectors[2].x = maxPoint.x;
  95445. this._boundingVectors.push(minPoint.clone());
  95446. this._boundingVectors[3].y = maxPoint.y;
  95447. this._boundingVectors.push(minPoint.clone());
  95448. this._boundingVectors[4].z = maxPoint.z;
  95449. this._boundingVectors.push(maxPoint.clone());
  95450. this._boundingVectors[5].z = minPoint.z;
  95451. this._boundingVectors.push(maxPoint.clone());
  95452. this._boundingVectors[6].x = minPoint.x;
  95453. this._boundingVectors.push(maxPoint.clone());
  95454. this._boundingVectors[7].y = minPoint.y;
  95455. }
  95456. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  95457. // Property
  95458. get: function () {
  95459. return this._capacity;
  95460. },
  95461. enumerable: true,
  95462. configurable: true
  95463. });
  95464. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  95465. get: function () {
  95466. return this._minPoint;
  95467. },
  95468. enumerable: true,
  95469. configurable: true
  95470. });
  95471. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  95472. get: function () {
  95473. return this._maxPoint;
  95474. },
  95475. enumerable: true,
  95476. configurable: true
  95477. });
  95478. // Methods
  95479. OctreeBlock.prototype.addEntry = function (entry) {
  95480. if (this.blocks) {
  95481. for (var index = 0; index < this.blocks.length; index++) {
  95482. var block = this.blocks[index];
  95483. block.addEntry(entry);
  95484. }
  95485. return;
  95486. }
  95487. this._creationFunc(entry, this);
  95488. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  95489. this.createInnerBlocks();
  95490. }
  95491. };
  95492. OctreeBlock.prototype.addEntries = function (entries) {
  95493. for (var index = 0; index < entries.length; index++) {
  95494. var mesh = entries[index];
  95495. this.addEntry(mesh);
  95496. }
  95497. };
  95498. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  95499. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  95500. if (this.blocks) {
  95501. for (var index = 0; index < this.blocks.length; index++) {
  95502. var block = this.blocks[index];
  95503. block.select(frustumPlanes, selection, allowDuplicate);
  95504. }
  95505. return;
  95506. }
  95507. if (allowDuplicate) {
  95508. selection.concat(this.entries);
  95509. }
  95510. else {
  95511. selection.concatWithNoDuplicate(this.entries);
  95512. }
  95513. }
  95514. };
  95515. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  95516. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  95517. if (this.blocks) {
  95518. for (var index = 0; index < this.blocks.length; index++) {
  95519. var block = this.blocks[index];
  95520. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  95521. }
  95522. return;
  95523. }
  95524. if (allowDuplicate) {
  95525. selection.concat(this.entries);
  95526. }
  95527. else {
  95528. selection.concatWithNoDuplicate(this.entries);
  95529. }
  95530. }
  95531. };
  95532. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  95533. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  95534. if (this.blocks) {
  95535. for (var index = 0; index < this.blocks.length; index++) {
  95536. var block = this.blocks[index];
  95537. block.intersectsRay(ray, selection);
  95538. }
  95539. return;
  95540. }
  95541. selection.concatWithNoDuplicate(this.entries);
  95542. }
  95543. };
  95544. OctreeBlock.prototype.createInnerBlocks = function () {
  95545. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  95546. };
  95547. return OctreeBlock;
  95548. }());
  95549. BABYLON.OctreeBlock = OctreeBlock;
  95550. })(BABYLON || (BABYLON = {}));
  95551. //# sourceMappingURL=babylon.octreeBlock.js.map
  95552. var BABYLON;
  95553. (function (BABYLON) {
  95554. BABYLON.Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  95555. if (maxCapacity === void 0) { maxCapacity = 64; }
  95556. if (maxDepth === void 0) { maxDepth = 2; }
  95557. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_OCTREE);
  95558. if (!component) {
  95559. component = new OctreeSceneComponent(this);
  95560. this._addComponent(component);
  95561. }
  95562. if (!this._selectionOctree) {
  95563. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  95564. }
  95565. var worldExtends = this.getWorldExtends();
  95566. // Update octree
  95567. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  95568. return this._selectionOctree;
  95569. };
  95570. Object.defineProperty(BABYLON.Scene.prototype, "selectionOctree", {
  95571. get: function () {
  95572. return this._selectionOctree;
  95573. },
  95574. enumerable: true,
  95575. configurable: true
  95576. });
  95577. /**
  95578. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  95579. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  95580. * @param maxCapacity defines the maximum size of each block (64 by default)
  95581. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  95582. * @returns the new octree
  95583. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  95584. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  95585. */
  95586. BABYLON.AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  95587. if (maxCapacity === void 0) { maxCapacity = 64; }
  95588. if (maxDepth === void 0) { maxDepth = 2; }
  95589. var scene = this.getScene();
  95590. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_OCTREE);
  95591. if (!component) {
  95592. component = new OctreeSceneComponent(scene);
  95593. scene._addComponent(component);
  95594. }
  95595. if (!this._submeshesOctree) {
  95596. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  95597. }
  95598. this.computeWorldMatrix(true);
  95599. var boundingInfo = this.getBoundingInfo();
  95600. // Update octree
  95601. var bbox = boundingInfo.boundingBox;
  95602. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  95603. return this._submeshesOctree;
  95604. };
  95605. /**
  95606. * Defines the octree scene component responsible to manage any octrees
  95607. * in a given scene.
  95608. */
  95609. var OctreeSceneComponent = /** @class */ (function () {
  95610. /**
  95611. * Creates a new instance of the component for the given scene
  95612. * @param scene Defines the scene to register the component in
  95613. */
  95614. function OctreeSceneComponent(scene) {
  95615. /**
  95616. * The component name helpfull to identify the component in the list of scene components.
  95617. */
  95618. this.name = BABYLON.SceneComponentConstants.NAME_OCTREE;
  95619. /**
  95620. * Indicates if the meshes have been checked to make sure they are isEnabled()
  95621. */
  95622. this.checksIsEnabled = true;
  95623. this._tempRay = new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(1, 1, 1));
  95624. this.scene = scene;
  95625. this.scene.getActiveMeshCandidates = this.getActiveMeshCandidates.bind(this);
  95626. this.scene.getActiveSubMeshCandidates = this.getActiveSubMeshCandidates.bind(this);
  95627. this.scene.getCollidingSubMeshCandidates = this.getCollidingSubMeshCandidates.bind(this);
  95628. this.scene.getIntersectingSubMeshCandidates = this.getIntersectingSubMeshCandidates.bind(this);
  95629. }
  95630. /**
  95631. * Registers the component in a given scene
  95632. */
  95633. OctreeSceneComponent.prototype.register = function () {
  95634. var _this = this;
  95635. this.scene.onMeshRemovedObservable.add(function (mesh) {
  95636. var sceneOctree = _this.scene.selectionOctree;
  95637. if (sceneOctree !== undefined && sceneOctree !== null) {
  95638. var index = sceneOctree.dynamicContent.indexOf(mesh);
  95639. if (index !== -1) {
  95640. sceneOctree.dynamicContent.splice(index, 1);
  95641. }
  95642. }
  95643. });
  95644. this.scene.onMeshImportedObservable.add(function (mesh) {
  95645. var sceneOctree = _this.scene.selectionOctree;
  95646. if (sceneOctree !== undefined && sceneOctree !== null) {
  95647. sceneOctree.addMesh(mesh);
  95648. }
  95649. });
  95650. };
  95651. /**
  95652. * Return the list of active meshes
  95653. * @returns the list of active meshes
  95654. */
  95655. OctreeSceneComponent.prototype.getActiveMeshCandidates = function () {
  95656. if (this.scene._selectionOctree) {
  95657. var selection = this.scene._selectionOctree.select(this.scene.frustumPlanes);
  95658. return selection;
  95659. }
  95660. return this.scene._getDefaultMeshCandidates();
  95661. };
  95662. /**
  95663. * Return the list of active sub meshes
  95664. * @param mesh The mesh to get the candidates sub meshes from
  95665. * @returns the list of active sub meshes
  95666. */
  95667. OctreeSceneComponent.prototype.getActiveSubMeshCandidates = function (mesh) {
  95668. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  95669. var intersections = mesh._submeshesOctree.select(this.scene.frustumPlanes);
  95670. return intersections;
  95671. }
  95672. return this.scene._getDefaultSubMeshCandidates(mesh);
  95673. };
  95674. /**
  95675. * Return the list of sub meshes intersecting with a given local ray
  95676. * @param mesh defines the mesh to find the submesh for
  95677. * @param localRay defines the ray in local space
  95678. * @returns the list of intersecting sub meshes
  95679. */
  95680. OctreeSceneComponent.prototype.getIntersectingSubMeshCandidates = function (mesh, localRay) {
  95681. if (mesh._submeshesOctree && mesh.useOctreeForPicking) {
  95682. BABYLON.Ray.TransformToRef(localRay, mesh.getWorldMatrix(), this._tempRay);
  95683. var intersections = mesh._submeshesOctree.intersectsRay(this._tempRay);
  95684. return intersections;
  95685. }
  95686. return this.scene._getDefaultSubMeshCandidates(mesh);
  95687. };
  95688. /**
  95689. * Return the list of sub meshes colliding with a collider
  95690. * @param mesh defines the mesh to find the submesh for
  95691. * @param collider defines the collider to evaluate the collision against
  95692. * @returns the list of colliding sub meshes
  95693. */
  95694. OctreeSceneComponent.prototype.getCollidingSubMeshCandidates = function (mesh, collider) {
  95695. if (mesh._submeshesOctree && mesh.useOctreeForCollisions) {
  95696. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  95697. var intersections = mesh._submeshesOctree.intersects(collider._basePointWorld, radius);
  95698. return intersections;
  95699. }
  95700. return this.scene._getDefaultSubMeshCandidates(mesh);
  95701. };
  95702. /**
  95703. * Rebuilds the elements related to this component in case of
  95704. * context lost for instance.
  95705. */
  95706. OctreeSceneComponent.prototype.rebuild = function () {
  95707. // Nothing to do here.
  95708. };
  95709. /**
  95710. * Disposes the component and the associated ressources.
  95711. */
  95712. OctreeSceneComponent.prototype.dispose = function () {
  95713. // Nothing to do here.
  95714. };
  95715. return OctreeSceneComponent;
  95716. }());
  95717. BABYLON.OctreeSceneComponent = OctreeSceneComponent;
  95718. })(BABYLON || (BABYLON = {}));
  95719. //# sourceMappingURL=babylon.octreeSceneComponent.js.map
  95720. var BABYLON;
  95721. (function (BABYLON) {
  95722. /**
  95723. * Postprocess used to generate anaglyphic rendering
  95724. */
  95725. var AnaglyphPostProcess = /** @class */ (function (_super) {
  95726. __extends(AnaglyphPostProcess, _super);
  95727. /**
  95728. * Creates a new AnaglyphPostProcess
  95729. * @param name defines postprocess name
  95730. * @param options defines creation options or target ratio scale
  95731. * @param rigCameras defines cameras using this postprocess
  95732. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  95733. * @param engine defines hosting engine
  95734. * @param reusable defines if the postprocess will be reused multiple times per frame
  95735. */
  95736. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  95737. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  95738. _this._passedProcess = rigCameras[0]._rigPostProcess;
  95739. _this.onApplyObservable.add(function (effect) {
  95740. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  95741. });
  95742. return _this;
  95743. }
  95744. return AnaglyphPostProcess;
  95745. }(BABYLON.PostProcess));
  95746. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  95747. })(BABYLON || (BABYLON = {}));
  95748. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  95749. var BABYLON;
  95750. (function (BABYLON) {
  95751. BABYLON.Node.AddNodeConstructor("AnaglyphArcRotateCamera", function (name, scene, options) {
  95752. return function () { return new AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  95753. });
  95754. /**
  95755. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  95756. */
  95757. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  95758. __extends(AnaglyphArcRotateCamera, _super);
  95759. /**
  95760. * Creates a new AnaglyphArcRotateCamera
  95761. * @param name defines camera name
  95762. * @param alpha defines alpha angle (in radians)
  95763. * @param beta defines beta angle (in radians)
  95764. * @param radius defines radius
  95765. * @param target defines camera target
  95766. * @param interaxialDistance defines distance between each color axis
  95767. * @param scene defines the hosting scene
  95768. */
  95769. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  95770. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  95771. _this.interaxialDistance = interaxialDistance;
  95772. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  95773. return _this;
  95774. }
  95775. /**
  95776. * Gets camera class name
  95777. * @returns AnaglyphArcRotateCamera
  95778. */
  95779. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  95780. return "AnaglyphArcRotateCamera";
  95781. };
  95782. return AnaglyphArcRotateCamera;
  95783. }(BABYLON.ArcRotateCamera));
  95784. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  95785. })(BABYLON || (BABYLON = {}));
  95786. //# sourceMappingURL=babylon.anaglyphArcRotateCamera.js.map
  95787. var BABYLON;
  95788. (function (BABYLON) {
  95789. BABYLON.Node.AddNodeConstructor("AnaglyphFreeCamera", function (name, scene, options) {
  95790. return function () { return new AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  95791. });
  95792. /**
  95793. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  95794. */
  95795. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  95796. __extends(AnaglyphFreeCamera, _super);
  95797. /**
  95798. * Creates a new AnaglyphFreeCamera
  95799. * @param name defines camera name
  95800. * @param position defines initial position
  95801. * @param interaxialDistance defines distance between each color axis
  95802. * @param scene defines the hosting scene
  95803. */
  95804. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  95805. var _this = _super.call(this, name, position, scene) || this;
  95806. _this.interaxialDistance = interaxialDistance;
  95807. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  95808. return _this;
  95809. }
  95810. /**
  95811. * Gets camera class name
  95812. * @returns AnaglyphFreeCamera
  95813. */
  95814. AnaglyphFreeCamera.prototype.getClassName = function () {
  95815. return "AnaglyphFreeCamera";
  95816. };
  95817. return AnaglyphFreeCamera;
  95818. }(BABYLON.FreeCamera));
  95819. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  95820. })(BABYLON || (BABYLON = {}));
  95821. //# sourceMappingURL=babylon.anaglyphFreeCamera.js.map
  95822. var BABYLON;
  95823. (function (BABYLON) {
  95824. BABYLON.Node.AddNodeConstructor("AnaglyphGamepadCamera", function (name, scene, options) {
  95825. return function () { return new AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  95826. });
  95827. /**
  95828. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  95829. */
  95830. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  95831. __extends(AnaglyphGamepadCamera, _super);
  95832. /**
  95833. * Creates a new AnaglyphGamepadCamera
  95834. * @param name defines camera name
  95835. * @param position defines initial position
  95836. * @param interaxialDistance defines distance between each color axis
  95837. * @param scene defines the hosting scene
  95838. */
  95839. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  95840. var _this = _super.call(this, name, position, scene) || this;
  95841. _this.interaxialDistance = interaxialDistance;
  95842. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  95843. return _this;
  95844. }
  95845. /**
  95846. * Gets camera class name
  95847. * @returns AnaglyphGamepadCamera
  95848. */
  95849. AnaglyphGamepadCamera.prototype.getClassName = function () {
  95850. return "AnaglyphGamepadCamera";
  95851. };
  95852. return AnaglyphGamepadCamera;
  95853. }(BABYLON.GamepadCamera));
  95854. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  95855. })(BABYLON || (BABYLON = {}));
  95856. //# sourceMappingURL=babylon.anaglyphGamepadCamera.js.map
  95857. var BABYLON;
  95858. (function (BABYLON) {
  95859. BABYLON.Node.AddNodeConstructor("AnaglyphUniversalCamera", function (name, scene, options) {
  95860. return function () { return new AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  95861. });
  95862. /**
  95863. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  95864. */
  95865. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  95866. __extends(AnaglyphUniversalCamera, _super);
  95867. /**
  95868. * Creates a new AnaglyphUniversalCamera
  95869. * @param name defines camera name
  95870. * @param position defines initial position
  95871. * @param interaxialDistance defines distance between each color axis
  95872. * @param scene defines the hosting scene
  95873. */
  95874. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  95875. var _this = _super.call(this, name, position, scene) || this;
  95876. _this.interaxialDistance = interaxialDistance;
  95877. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  95878. return _this;
  95879. }
  95880. /**
  95881. * Gets camera class name
  95882. * @returns AnaglyphUniversalCamera
  95883. */
  95884. AnaglyphUniversalCamera.prototype.getClassName = function () {
  95885. return "AnaglyphUniversalCamera";
  95886. };
  95887. return AnaglyphUniversalCamera;
  95888. }(BABYLON.UniversalCamera));
  95889. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  95890. })(BABYLON || (BABYLON = {}));
  95891. //# sourceMappingURL=babylon.anaglyphUniversalCamera.js.map
  95892. var BABYLON;
  95893. (function (BABYLON) {
  95894. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  95895. __extends(StereoscopicInterlacePostProcess, _super);
  95896. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  95897. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  95898. _this._passedProcess = rigCameras[0]._rigPostProcess;
  95899. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  95900. _this.onSizeChangedObservable.add(function () {
  95901. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  95902. });
  95903. _this.onApplyObservable.add(function (effect) {
  95904. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  95905. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  95906. });
  95907. return _this;
  95908. }
  95909. return StereoscopicInterlacePostProcess;
  95910. }(BABYLON.PostProcess));
  95911. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  95912. })(BABYLON || (BABYLON = {}));
  95913. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  95914. var BABYLON;
  95915. (function (BABYLON) {
  95916. BABYLON.Node.AddNodeConstructor("StereoscopicArcRotateCamera", function (name, scene, options) {
  95917. return function () { return new StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  95918. });
  95919. /**
  95920. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  95921. */
  95922. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  95923. __extends(StereoscopicArcRotateCamera, _super);
  95924. /**
  95925. * Creates a new StereoscopicArcRotateCamera
  95926. * @param name defines camera name
  95927. * @param alpha defines alpha angle (in radians)
  95928. * @param beta defines beta angle (in radians)
  95929. * @param radius defines radius
  95930. * @param target defines camera target
  95931. * @param interaxialDistance defines distance between each color axis
  95932. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  95933. * @param scene defines the hosting scene
  95934. */
  95935. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  95936. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  95937. _this.interaxialDistance = interaxialDistance;
  95938. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  95939. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  95940. return _this;
  95941. }
  95942. /**
  95943. * Gets camera class name
  95944. * @returns StereoscopicArcRotateCamera
  95945. */
  95946. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  95947. return "StereoscopicArcRotateCamera";
  95948. };
  95949. return StereoscopicArcRotateCamera;
  95950. }(BABYLON.ArcRotateCamera));
  95951. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  95952. })(BABYLON || (BABYLON = {}));
  95953. //# sourceMappingURL=babylon.stereoscopicArcRotateCamera.js.map
  95954. var BABYLON;
  95955. (function (BABYLON) {
  95956. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  95957. return function () { return new StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  95958. });
  95959. /**
  95960. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  95961. */
  95962. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  95963. __extends(StereoscopicFreeCamera, _super);
  95964. /**
  95965. * Creates a new StereoscopicFreeCamera
  95966. * @param name defines camera name
  95967. * @param position defines initial position
  95968. * @param interaxialDistance defines distance between each color axis
  95969. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  95970. * @param scene defines the hosting scene
  95971. */
  95972. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  95973. var _this = _super.call(this, name, position, scene) || this;
  95974. _this.interaxialDistance = interaxialDistance;
  95975. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  95976. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  95977. return _this;
  95978. }
  95979. /**
  95980. * Gets camera class name
  95981. * @returns StereoscopicFreeCamera
  95982. */
  95983. StereoscopicFreeCamera.prototype.getClassName = function () {
  95984. return "StereoscopicFreeCamera";
  95985. };
  95986. return StereoscopicFreeCamera;
  95987. }(BABYLON.FreeCamera));
  95988. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  95989. })(BABYLON || (BABYLON = {}));
  95990. //# sourceMappingURL=babylon.stereoscopicFreeCamera.js.map
  95991. var BABYLON;
  95992. (function (BABYLON) {
  95993. BABYLON.Node.AddNodeConstructor("StereoscopicGamepadCamera", function (name, scene, options) {
  95994. return function () { return new StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  95995. });
  95996. /**
  95997. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  95998. */
  95999. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  96000. __extends(StereoscopicGamepadCamera, _super);
  96001. /**
  96002. * Creates a new StereoscopicGamepadCamera
  96003. * @param name defines camera name
  96004. * @param position defines initial position
  96005. * @param interaxialDistance defines distance between each color axis
  96006. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  96007. * @param scene defines the hosting scene
  96008. */
  96009. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  96010. var _this = _super.call(this, name, position, scene) || this;
  96011. _this.interaxialDistance = interaxialDistance;
  96012. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  96013. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  96014. return _this;
  96015. }
  96016. /**
  96017. * Gets camera class name
  96018. * @returns StereoscopicGamepadCamera
  96019. */
  96020. StereoscopicGamepadCamera.prototype.getClassName = function () {
  96021. return "StereoscopicGamepadCamera";
  96022. };
  96023. return StereoscopicGamepadCamera;
  96024. }(BABYLON.GamepadCamera));
  96025. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  96026. })(BABYLON || (BABYLON = {}));
  96027. //# sourceMappingURL=babylon.stereoscopicGamepadCamera.js.map
  96028. var BABYLON;
  96029. (function (BABYLON) {
  96030. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  96031. return function () { return new StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  96032. });
  96033. /**
  96034. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  96035. */
  96036. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  96037. __extends(StereoscopicUniversalCamera, _super);
  96038. /**
  96039. * Creates a new StereoscopicUniversalCamera
  96040. * @param name defines camera name
  96041. * @param position defines initial position
  96042. * @param interaxialDistance defines distance between each color axis
  96043. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  96044. * @param scene defines the hosting scene
  96045. */
  96046. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  96047. var _this = _super.call(this, name, position, scene) || this;
  96048. _this.interaxialDistance = interaxialDistance;
  96049. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  96050. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  96051. return _this;
  96052. }
  96053. /**
  96054. * Gets camera class name
  96055. * @returns StereoscopicUniversalCamera
  96056. */
  96057. StereoscopicUniversalCamera.prototype.getClassName = function () {
  96058. return "StereoscopicUniversalCamera";
  96059. };
  96060. return StereoscopicUniversalCamera;
  96061. }(BABYLON.UniversalCamera));
  96062. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  96063. })(BABYLON || (BABYLON = {}));
  96064. //# sourceMappingURL=babylon.stereoscopicUniversalCamera.js.map
  96065. var BABYLON;
  96066. (function (BABYLON) {
  96067. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  96068. __extends(VRDistortionCorrectionPostProcess, _super);
  96069. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  96070. var _this = _super.call(this, name, "vrDistortionCorrection", [
  96071. 'LensCenter',
  96072. 'Scale',
  96073. 'ScaleIn',
  96074. 'HmdWarpParam'
  96075. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  96076. _this._isRightEye = isRightEye;
  96077. _this._distortionFactors = vrMetrics.distortionK;
  96078. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  96079. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  96080. _this.adaptScaleToCurrentViewport = true;
  96081. _this.onSizeChangedObservable.add(function () {
  96082. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  96083. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  96084. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  96085. });
  96086. _this.onApplyObservable.add(function (effect) {
  96087. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  96088. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  96089. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  96090. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  96091. });
  96092. return _this;
  96093. }
  96094. return VRDistortionCorrectionPostProcess;
  96095. }(BABYLON.PostProcess));
  96096. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  96097. })(BABYLON || (BABYLON = {}));
  96098. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  96099. var BABYLON;
  96100. (function (BABYLON) {
  96101. /**
  96102. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  96103. * Screen rotation is taken into account.
  96104. */
  96105. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  96106. function FreeCameraDeviceOrientationInput() {
  96107. var _this = this;
  96108. this._screenOrientationAngle = 0;
  96109. this._screenQuaternion = new BABYLON.Quaternion();
  96110. this._alpha = 0;
  96111. this._beta = 0;
  96112. this._gamma = 0;
  96113. this._orientationChanged = function () {
  96114. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  96115. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  96116. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  96117. };
  96118. this._deviceOrientation = function (evt) {
  96119. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  96120. _this._beta = evt.beta !== null ? evt.beta : 0;
  96121. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  96122. };
  96123. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  96124. this._orientationChanged();
  96125. }
  96126. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  96127. get: function () {
  96128. return this._camera;
  96129. },
  96130. set: function (camera) {
  96131. this._camera = camera;
  96132. if (this._camera != null && !this._camera.rotationQuaternion) {
  96133. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  96134. }
  96135. },
  96136. enumerable: true,
  96137. configurable: true
  96138. });
  96139. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  96140. window.addEventListener("orientationchange", this._orientationChanged);
  96141. window.addEventListener("deviceorientation", this._deviceOrientation);
  96142. //In certain cases, the attach control is called AFTER orientation was changed,
  96143. //So this is needed.
  96144. this._orientationChanged();
  96145. };
  96146. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  96147. window.removeEventListener("orientationchange", this._orientationChanged);
  96148. window.removeEventListener("deviceorientation", this._deviceOrientation);
  96149. };
  96150. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  96151. //if no device orientation provided, don't update the rotation.
  96152. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  96153. if (!this._alpha)
  96154. return;
  96155. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  96156. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  96157. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  96158. //Mirror on XY Plane
  96159. this._camera.rotationQuaternion.z *= -1;
  96160. this._camera.rotationQuaternion.w *= -1;
  96161. };
  96162. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  96163. return "FreeCameraDeviceOrientationInput";
  96164. };
  96165. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  96166. return "deviceOrientation";
  96167. };
  96168. return FreeCameraDeviceOrientationInput;
  96169. }());
  96170. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  96171. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  96172. })(BABYLON || (BABYLON = {}));
  96173. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  96174. var BABYLON;
  96175. (function (BABYLON) {
  96176. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  96177. function ArcRotateCameraVRDeviceOrientationInput() {
  96178. this.alphaCorrection = 1;
  96179. this.betaCorrection = 1;
  96180. this.gammaCorrection = 1;
  96181. this._alpha = 0;
  96182. this._gamma = 0;
  96183. this._dirty = false;
  96184. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  96185. }
  96186. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  96187. this.camera.attachControl(element, noPreventDefault);
  96188. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  96189. };
  96190. /** @hidden */
  96191. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  96192. if (evt.alpha !== null) {
  96193. this._alpha = +evt.alpha | 0;
  96194. }
  96195. if (evt.gamma !== null) {
  96196. this._gamma = +evt.gamma | 0;
  96197. }
  96198. this._dirty = true;
  96199. };
  96200. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  96201. if (this._dirty) {
  96202. this._dirty = false;
  96203. if (this._gamma < 0) {
  96204. this._gamma = 180 + this._gamma;
  96205. }
  96206. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  96207. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  96208. }
  96209. };
  96210. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  96211. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  96212. };
  96213. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  96214. return "ArcRotateCameraVRDeviceOrientationInput";
  96215. };
  96216. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  96217. return "VRDeviceOrientation";
  96218. };
  96219. return ArcRotateCameraVRDeviceOrientationInput;
  96220. }());
  96221. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  96222. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  96223. })(BABYLON || (BABYLON = {}));
  96224. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  96225. var BABYLON;
  96226. (function (BABYLON) {
  96227. var VRCameraMetrics = /** @class */ (function () {
  96228. function VRCameraMetrics() {
  96229. this.compensateDistortion = true;
  96230. }
  96231. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  96232. get: function () {
  96233. return this.hResolution / (2 * this.vResolution);
  96234. },
  96235. enumerable: true,
  96236. configurable: true
  96237. });
  96238. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  96239. get: function () {
  96240. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  96241. },
  96242. enumerable: true,
  96243. configurable: true
  96244. });
  96245. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  96246. get: function () {
  96247. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  96248. var h = (4 * meters) / this.hScreenSize;
  96249. return BABYLON.Matrix.Translation(h, 0, 0);
  96250. },
  96251. enumerable: true,
  96252. configurable: true
  96253. });
  96254. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  96255. get: function () {
  96256. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  96257. var h = (4 * meters) / this.hScreenSize;
  96258. return BABYLON.Matrix.Translation(-h, 0, 0);
  96259. },
  96260. enumerable: true,
  96261. configurable: true
  96262. });
  96263. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  96264. get: function () {
  96265. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  96266. },
  96267. enumerable: true,
  96268. configurable: true
  96269. });
  96270. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  96271. get: function () {
  96272. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  96273. },
  96274. enumerable: true,
  96275. configurable: true
  96276. });
  96277. VRCameraMetrics.GetDefault = function () {
  96278. var result = new VRCameraMetrics();
  96279. result.hResolution = 1280;
  96280. result.vResolution = 800;
  96281. result.hScreenSize = 0.149759993;
  96282. result.vScreenSize = 0.0935999975;
  96283. result.vScreenCenter = 0.0467999987;
  96284. result.eyeToScreenDistance = 0.0410000011;
  96285. result.lensSeparationDistance = 0.0635000020;
  96286. result.interpupillaryDistance = 0.0640000030;
  96287. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  96288. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  96289. result.postProcessScaleFactor = 1.714605507808412;
  96290. result.lensCenterOffset = 0.151976421;
  96291. return result;
  96292. };
  96293. return VRCameraMetrics;
  96294. }());
  96295. BABYLON.VRCameraMetrics = VRCameraMetrics;
  96296. })(BABYLON || (BABYLON = {}));
  96297. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  96298. var BABYLON;
  96299. (function (BABYLON) {
  96300. BABYLON.Node.AddNodeConstructor("WebVRFreeCamera", function (name, scene) {
  96301. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  96302. });
  96303. BABYLON.Node.AddNodeConstructor("WebVRGamepadCamera", function (name, scene) {
  96304. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  96305. });
  96306. /**
  96307. * This represents a WebVR camera.
  96308. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  96309. * @example http://doc.babylonjs.com/how_to/webvr_camera
  96310. */
  96311. var WebVRFreeCamera = /** @class */ (function (_super) {
  96312. __extends(WebVRFreeCamera, _super);
  96313. /**
  96314. * Instantiates a WebVRFreeCamera.
  96315. * @param name The name of the WebVRFreeCamera
  96316. * @param position The starting anchor position for the camera
  96317. * @param scene The scene the camera belongs to
  96318. * @param webVROptions a set of customizable options for the webVRCamera
  96319. */
  96320. function WebVRFreeCamera(name, position, scene, webVROptions) {
  96321. if (webVROptions === void 0) { webVROptions = {}; }
  96322. var _this = _super.call(this, name, position, scene) || this;
  96323. _this.webVROptions = webVROptions;
  96324. /**
  96325. * @hidden
  96326. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  96327. */
  96328. _this._vrDevice = null;
  96329. /**
  96330. * The rawPose of the vrDevice.
  96331. */
  96332. _this.rawPose = null;
  96333. _this._specsVersion = "1.1";
  96334. _this._attached = false;
  96335. _this._descendants = [];
  96336. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  96337. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  96338. /** @hidden */
  96339. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  96340. _this._standingMatrix = null;
  96341. /**
  96342. * Represents device position in babylon space.
  96343. */
  96344. _this.devicePosition = BABYLON.Vector3.Zero();
  96345. /**
  96346. * Represents device rotation in babylon space.
  96347. */
  96348. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  96349. /**
  96350. * The scale of the device to be used when translating from device space to babylon space.
  96351. */
  96352. _this.deviceScaleFactor = 1;
  96353. _this._deviceToWorld = BABYLON.Matrix.Identity();
  96354. _this._worldToDevice = BABYLON.Matrix.Identity();
  96355. /**
  96356. * References to the webVR controllers for the vrDevice.
  96357. */
  96358. _this.controllers = [];
  96359. /**
  96360. * Emits an event when a controller is attached.
  96361. */
  96362. _this.onControllersAttachedObservable = new BABYLON.Observable();
  96363. /**
  96364. * Emits an event when a controller's mesh has been loaded;
  96365. */
  96366. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  96367. /**
  96368. * Emits an event when the HMD's pose has been updated.
  96369. */
  96370. _this.onPoseUpdatedFromDeviceObservable = new BABYLON.Observable();
  96371. _this._poseSet = false;
  96372. /**
  96373. * If the rig cameras be used as parent instead of this camera.
  96374. */
  96375. _this.rigParenting = true;
  96376. _this._defaultHeight = undefined;
  96377. _this._htmlElementAttached = null;
  96378. _this._detachIfAttached = function () {
  96379. var vrDisplay = _this.getEngine().getVRDevice();
  96380. if (vrDisplay && !vrDisplay.isPresenting && _this._htmlElementAttached) {
  96381. _this.detachControl(_this._htmlElementAttached);
  96382. }
  96383. };
  96384. _this._workingVector = BABYLON.Vector3.Zero();
  96385. _this._oneVector = BABYLON.Vector3.One();
  96386. _this._workingMatrix = BABYLON.Matrix.Identity();
  96387. _this._tmpMatrix = new BABYLON.Matrix();
  96388. _this._cache.position = BABYLON.Vector3.Zero();
  96389. if (webVROptions.defaultHeight) {
  96390. _this._defaultHeight = webVROptions.defaultHeight;
  96391. _this.position.y = _this._defaultHeight;
  96392. }
  96393. _this.minZ = 0.1;
  96394. //legacy support - the compensation boolean was removed.
  96395. if (arguments.length === 5) {
  96396. _this.webVROptions = arguments[4];
  96397. }
  96398. // default webVR options
  96399. if (_this.webVROptions.trackPosition == undefined) {
  96400. _this.webVROptions.trackPosition = true;
  96401. }
  96402. if (_this.webVROptions.controllerMeshes == undefined) {
  96403. _this.webVROptions.controllerMeshes = true;
  96404. }
  96405. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  96406. _this.webVROptions.defaultLightingOnControllers = true;
  96407. }
  96408. _this.rotationQuaternion = new BABYLON.Quaternion();
  96409. if (_this.webVROptions && _this.webVROptions.positionScale) {
  96410. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  96411. }
  96412. //enable VR
  96413. var engine = _this.getEngine();
  96414. _this._onVREnabled = function (success) { if (success) {
  96415. _this.initControllers();
  96416. } };
  96417. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  96418. engine.initWebVR().add(function (event) {
  96419. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  96420. return;
  96421. }
  96422. _this._vrDevice = event.vrDisplay;
  96423. //reset the rig parameters.
  96424. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  96425. if (_this._attached) {
  96426. _this.getEngine().enableVR();
  96427. }
  96428. });
  96429. if (typeof (VRFrameData) !== "undefined")
  96430. _this._frameData = new VRFrameData();
  96431. /**
  96432. * The idea behind the following lines:
  96433. * objects that have the camera as parent should actually have the rig cameras as a parent.
  96434. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  96435. * the second will not show it correctly.
  96436. *
  96437. * To solve this - each object that has the camera as parent will be added to a protected array.
  96438. * When the rig camera renders, it will take this array and set all of those to be its children.
  96439. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  96440. * Amazing!
  96441. */
  96442. scene.onBeforeCameraRenderObservable.add(function (camera) {
  96443. if (camera.parent === _this && _this.rigParenting) {
  96444. _this._descendants = _this.getDescendants(true, function (n) {
  96445. // don't take the cameras or the controllers!
  96446. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  96447. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  96448. return !isController && !isRigCamera;
  96449. });
  96450. _this._descendants.forEach(function (node) {
  96451. node.parent = camera;
  96452. });
  96453. }
  96454. });
  96455. scene.onAfterCameraRenderObservable.add(function (camera) {
  96456. if (camera.parent === _this && _this.rigParenting) {
  96457. _this._descendants.forEach(function (node) {
  96458. node.parent = _this;
  96459. });
  96460. }
  96461. });
  96462. return _this;
  96463. }
  96464. /**
  96465. * Gets the device distance from the ground in meters.
  96466. * @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.
  96467. */
  96468. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  96469. if (this._standingMatrix) {
  96470. // Add standing matrix offset to get real offset from ground in room
  96471. this._standingMatrix.getTranslationToRef(this._workingVector);
  96472. return this._deviceRoomPosition.y + this._workingVector.y;
  96473. }
  96474. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  96475. return this._defaultHeight || 0;
  96476. };
  96477. /**
  96478. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  96479. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  96480. */
  96481. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  96482. var _this = this;
  96483. if (callback === void 0) { callback = function (bool) { }; }
  96484. // Use standing matrix if available
  96485. this.getEngine().initWebVRAsync().then(function (result) {
  96486. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  96487. callback(false);
  96488. }
  96489. else {
  96490. _this._standingMatrix = new BABYLON.Matrix();
  96491. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  96492. if (!_this.getScene().useRightHandedSystem) {
  96493. [2, 6, 8, 9, 14].forEach(function (num) {
  96494. if (_this._standingMatrix) {
  96495. _this._standingMatrix.m[num] *= -1;
  96496. }
  96497. });
  96498. }
  96499. callback(true);
  96500. }
  96501. });
  96502. };
  96503. /**
  96504. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  96505. * @returns A promise with a boolean set to if the standing matrix is supported.
  96506. */
  96507. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  96508. var _this = this;
  96509. return new Promise(function (res, rej) {
  96510. _this.useStandingMatrix(function (supported) {
  96511. res(supported);
  96512. });
  96513. });
  96514. };
  96515. /**
  96516. * Disposes the camera
  96517. */
  96518. WebVRFreeCamera.prototype.dispose = function () {
  96519. this._detachIfAttached();
  96520. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  96521. _super.prototype.dispose.call(this);
  96522. };
  96523. /**
  96524. * Gets a vrController by name.
  96525. * @param name The name of the controller to retreive
  96526. * @returns the controller matching the name specified or null if not found
  96527. */
  96528. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  96529. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  96530. var gp = _a[_i];
  96531. if (gp.hand === name) {
  96532. return gp;
  96533. }
  96534. }
  96535. return null;
  96536. };
  96537. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  96538. /**
  96539. * The controller corrisponding to the users left hand.
  96540. */
  96541. get: function () {
  96542. if (!this._leftController) {
  96543. this._leftController = this.getControllerByName("left");
  96544. }
  96545. return this._leftController;
  96546. },
  96547. enumerable: true,
  96548. configurable: true
  96549. });
  96550. ;
  96551. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  96552. /**
  96553. * The controller corrisponding to the users right hand.
  96554. */
  96555. get: function () {
  96556. if (!this._rightController) {
  96557. this._rightController = this.getControllerByName("right");
  96558. }
  96559. return this._rightController;
  96560. },
  96561. enumerable: true,
  96562. configurable: true
  96563. });
  96564. ;
  96565. /**
  96566. * Casts a ray forward from the vrCamera's gaze.
  96567. * @param length Length of the ray (default: 100)
  96568. * @returns the ray corrisponding to the gaze
  96569. */
  96570. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  96571. if (length === void 0) { length = 100; }
  96572. if (this.leftCamera) {
  96573. // Use left eye to avoid computation to compute center on every call
  96574. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  96575. }
  96576. else {
  96577. return _super.prototype.getForwardRay.call(this, length);
  96578. }
  96579. };
  96580. /**
  96581. * @hidden
  96582. * Updates the camera based on device's frame data
  96583. */
  96584. WebVRFreeCamera.prototype._checkInputs = function () {
  96585. if (this._vrDevice && this._vrDevice.isPresenting) {
  96586. this._vrDevice.getFrameData(this._frameData);
  96587. this.updateFromDevice(this._frameData.pose);
  96588. }
  96589. _super.prototype._checkInputs.call(this);
  96590. };
  96591. /**
  96592. * Updates the poseControlled values based on the input device pose.
  96593. * @param poseData Pose coming from the device
  96594. */
  96595. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  96596. if (poseData && poseData.orientation) {
  96597. this.rawPose = poseData;
  96598. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  96599. if (this.getScene().useRightHandedSystem) {
  96600. this._deviceRoomRotationQuaternion.z *= -1;
  96601. this._deviceRoomRotationQuaternion.w *= -1;
  96602. }
  96603. if (this.webVROptions.trackPosition && this.rawPose.position) {
  96604. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  96605. if (this.getScene().useRightHandedSystem) {
  96606. this._deviceRoomPosition.z *= -1;
  96607. }
  96608. }
  96609. this._poseSet = true;
  96610. }
  96611. };
  96612. /**
  96613. * WebVR's attach control will start broadcasting frames to the device.
  96614. * Note that in certain browsers (chrome for example) this function must be called
  96615. * within a user-interaction callback. Example:
  96616. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  96617. *
  96618. * @param element html element to attach the vrDevice to
  96619. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  96620. */
  96621. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  96622. _super.prototype.attachControl.call(this, element, noPreventDefault);
  96623. this._attached = true;
  96624. this._htmlElementAttached = element;
  96625. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  96626. if (this._vrDevice) {
  96627. this.getEngine().enableVR();
  96628. }
  96629. window.addEventListener('vrdisplaypresentchange', this._detachIfAttached);
  96630. };
  96631. /**
  96632. * Detaches the camera from the html element and disables VR
  96633. *
  96634. * @param element html element to detach from
  96635. */
  96636. WebVRFreeCamera.prototype.detachControl = function (element) {
  96637. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  96638. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  96639. _super.prototype.detachControl.call(this, element);
  96640. this._attached = false;
  96641. this.getEngine().disableVR();
  96642. window.removeEventListener('vrdisplaypresentchange', this._detachIfAttached);
  96643. };
  96644. /**
  96645. * @returns the name of this class
  96646. */
  96647. WebVRFreeCamera.prototype.getClassName = function () {
  96648. return "WebVRFreeCamera";
  96649. };
  96650. /**
  96651. * Calls resetPose on the vrDisplay
  96652. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  96653. */
  96654. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  96655. //uses the vrDisplay's "resetPose()".
  96656. //pitch and roll won't be affected.
  96657. this._vrDevice.resetPose();
  96658. };
  96659. /**
  96660. * @hidden
  96661. * Updates the rig cameras (left and right eye)
  96662. */
  96663. WebVRFreeCamera.prototype._updateRigCameras = function () {
  96664. var camLeft = this._rigCameras[0];
  96665. var camRight = this._rigCameras[1];
  96666. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  96667. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  96668. camLeft.position.copyFrom(this._deviceRoomPosition);
  96669. camRight.position.copyFrom(this._deviceRoomPosition);
  96670. };
  96671. // Remove translation from 6dof headset if trackposition is set to false
  96672. WebVRFreeCamera.prototype._correctPositionIfNotTrackPosition = function (matrix, isViewMatrix) {
  96673. if (isViewMatrix === void 0) { isViewMatrix = false; }
  96674. if (this.rawPose && this.rawPose.position && !this.webVROptions.trackPosition) {
  96675. BABYLON.Matrix.TranslationToRef(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2], this._tmpMatrix);
  96676. if (!isViewMatrix) {
  96677. this._tmpMatrix.invert();
  96678. }
  96679. this._tmpMatrix.multiplyToRef(matrix, matrix);
  96680. }
  96681. };
  96682. /**
  96683. * @hidden
  96684. * Updates the cached values of the camera
  96685. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  96686. */
  96687. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  96688. var _this = this;
  96689. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  96690. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  96691. if (!this.updateCacheCalled) {
  96692. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  96693. this.updateCacheCalled = true;
  96694. this.update();
  96695. }
  96696. // Set working vector to the device position in room space rotated by the new rotation
  96697. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  96698. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  96699. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  96700. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  96701. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  96702. // Add translation from anchor position
  96703. this._deviceToWorld.getTranslationToRef(this._workingVector);
  96704. this._workingVector.addInPlace(this.position);
  96705. this._workingVector.subtractInPlace(this._cache.position);
  96706. this._deviceToWorld.setTranslation(this._workingVector);
  96707. // Set an inverted matrix to be used when updating the camera
  96708. this._deviceToWorld.invertToRef(this._worldToDevice);
  96709. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  96710. this.controllers.forEach(function (controller) {
  96711. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  96712. _this._correctPositionIfNotTrackPosition(controller._deviceToWorld);
  96713. controller.update();
  96714. });
  96715. }
  96716. if (!ignoreParentClass) {
  96717. _super.prototype._updateCache.call(this);
  96718. }
  96719. this.updateCacheCalled = false;
  96720. };
  96721. /**
  96722. * Updates the current device position and rotation in the babylon world
  96723. */
  96724. WebVRFreeCamera.prototype.update = function () {
  96725. // Get current device position in babylon world
  96726. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  96727. // Get current device rotation in babylon world
  96728. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  96729. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  96730. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  96731. if (this._poseSet) {
  96732. this.onPoseUpdatedFromDeviceObservable.notifyObservers(null);
  96733. }
  96734. _super.prototype.update.call(this);
  96735. };
  96736. /**
  96737. * @hidden
  96738. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  96739. * @returns an identity matrix
  96740. */
  96741. WebVRFreeCamera.prototype._getViewMatrix = function () {
  96742. return BABYLON.Matrix.Identity();
  96743. };
  96744. /**
  96745. * This function is called by the two RIG cameras.
  96746. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  96747. */
  96748. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  96749. var _this = this;
  96750. // Update the parent camera prior to using a child camera to avoid desynchronization
  96751. var parentCamera = this._cameraRigParams["parentCamera"];
  96752. parentCamera._updateCache();
  96753. //WebVR 1.1
  96754. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  96755. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  96756. if (!this.getScene().useRightHandedSystem) {
  96757. [2, 6, 8, 9, 14].forEach(function (num) {
  96758. _this._webvrViewMatrix.m[num] *= -1;
  96759. });
  96760. }
  96761. // update the camera rotation matrix
  96762. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  96763. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  96764. // Computing target and final matrix
  96765. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  96766. // should the view matrix be updated with scale and position offset?
  96767. if (parentCamera.deviceScaleFactor !== 1) {
  96768. this._webvrViewMatrix.invert();
  96769. // scale the position, if set
  96770. if (parentCamera.deviceScaleFactor) {
  96771. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  96772. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  96773. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  96774. }
  96775. this._webvrViewMatrix.invert();
  96776. }
  96777. // Remove translation from 6dof headset if trackposition is set to false
  96778. parentCamera._correctPositionIfNotTrackPosition(this._webvrViewMatrix, true);
  96779. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  96780. // Compute global position
  96781. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  96782. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  96783. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  96784. this._workingMatrix.getTranslationToRef(this._globalPosition);
  96785. this._markSyncedWithParent();
  96786. return this._webvrViewMatrix;
  96787. };
  96788. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  96789. var _this = this;
  96790. var parentCamera = this.parent;
  96791. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  96792. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  96793. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  96794. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  96795. //babylon compatible matrix
  96796. if (!this.getScene().useRightHandedSystem) {
  96797. [8, 9, 10, 11].forEach(function (num) {
  96798. _this._projectionMatrix.m[num] *= -1;
  96799. });
  96800. }
  96801. return this._projectionMatrix;
  96802. };
  96803. /**
  96804. * Initializes the controllers and their meshes
  96805. */
  96806. WebVRFreeCamera.prototype.initControllers = function () {
  96807. var _this = this;
  96808. this.controllers = [];
  96809. var manager = this.getScene().gamepadManager;
  96810. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  96811. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  96812. var webVrController = gamepad;
  96813. if (webVrController.defaultModel) {
  96814. webVrController.defaultModel.setEnabled(false);
  96815. }
  96816. if (webVrController.hand === "right") {
  96817. _this._rightController = null;
  96818. }
  96819. if (webVrController.hand === "left") {
  96820. _this._leftController = null;
  96821. }
  96822. var controllerIndex = _this.controllers.indexOf(webVrController);
  96823. if (controllerIndex !== -1) {
  96824. _this.controllers.splice(controllerIndex, 1);
  96825. }
  96826. }
  96827. });
  96828. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  96829. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  96830. var webVrController_1 = gamepad;
  96831. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  96832. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  96833. _this._correctPositionIfNotTrackPosition(webVrController_1._deviceToWorld);
  96834. if (_this.webVROptions.controllerMeshes) {
  96835. if (webVrController_1.defaultModel) {
  96836. webVrController_1.defaultModel.setEnabled(true);
  96837. }
  96838. else {
  96839. // Load the meshes
  96840. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  96841. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  96842. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  96843. if (_this.webVROptions.defaultLightingOnControllers) {
  96844. if (!_this._lightOnControllers) {
  96845. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  96846. }
  96847. var activateLightOnSubMeshes_1 = function (mesh, light) {
  96848. var children = mesh.getChildren();
  96849. if (children && children.length !== 0) {
  96850. children.forEach(function (mesh) {
  96851. light.includedOnlyMeshes.push(mesh);
  96852. activateLightOnSubMeshes_1(mesh, light);
  96853. });
  96854. }
  96855. };
  96856. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  96857. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  96858. }
  96859. });
  96860. }
  96861. }
  96862. webVrController_1.attachToPoseControlledCamera(_this);
  96863. // since this is async - sanity check. Is the controller already stored?
  96864. if (_this.controllers.indexOf(webVrController_1) === -1) {
  96865. //add to the controllers array
  96866. _this.controllers.push(webVrController_1);
  96867. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  96868. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  96869. // So we're overriding setting left & right manually to be sure
  96870. var firstViveWandDetected = false;
  96871. for (var i = 0; i < _this.controllers.length; i++) {
  96872. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  96873. if (!firstViveWandDetected) {
  96874. firstViveWandDetected = true;
  96875. _this.controllers[i].hand = "left";
  96876. }
  96877. else {
  96878. _this.controllers[i].hand = "right";
  96879. }
  96880. }
  96881. }
  96882. //did we find enough controllers? Great! let the developer know.
  96883. if (_this.controllers.length >= 2) {
  96884. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  96885. }
  96886. }
  96887. }
  96888. });
  96889. };
  96890. return WebVRFreeCamera;
  96891. }(BABYLON.FreeCamera));
  96892. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  96893. })(BABYLON || (BABYLON = {}));
  96894. //# sourceMappingURL=babylon.webVRCamera.js.map
  96895. var BABYLON;
  96896. (function (BABYLON) {
  96897. BABYLON.Node.AddNodeConstructor("DeviceOrientationCamera", function (name, scene) {
  96898. return function () { return new DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  96899. });
  96900. // We're mainly based on the logic defined into the FreeCamera code
  96901. /**
  96902. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  96903. * being tilted forward or back and left or right.
  96904. */
  96905. var DeviceOrientationCamera = /** @class */ (function (_super) {
  96906. __extends(DeviceOrientationCamera, _super);
  96907. /**
  96908. * Creates a new device orientation camera
  96909. * @param name The name of the camera
  96910. * @param position The start position camera
  96911. * @param scene The scene the camera belongs to
  96912. */
  96913. function DeviceOrientationCamera(name, position, scene) {
  96914. var _this = _super.call(this, name, position, scene) || this;
  96915. _this._quaternionCache = new BABYLON.Quaternion();
  96916. _this.inputs.addDeviceOrientation();
  96917. return _this;
  96918. }
  96919. /**
  96920. * Gets the current instance class name ("DeviceOrientationCamera").
  96921. * This helps avoiding instanceof at run time.
  96922. * @returns the class name
  96923. */
  96924. DeviceOrientationCamera.prototype.getClassName = function () {
  96925. return "DeviceOrientationCamera";
  96926. };
  96927. /**
  96928. * @hidden
  96929. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  96930. */
  96931. DeviceOrientationCamera.prototype._checkInputs = function () {
  96932. _super.prototype._checkInputs.call(this);
  96933. this._quaternionCache.copyFrom(this.rotationQuaternion);
  96934. if (this._initialQuaternion) {
  96935. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  96936. }
  96937. };
  96938. /**
  96939. * Reset the camera to its default orientation on the specified axis only.
  96940. * @param axis The axis to reset
  96941. */
  96942. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  96943. var _this = this;
  96944. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  96945. //can only work if this camera has a rotation quaternion already.
  96946. if (!this.rotationQuaternion)
  96947. return;
  96948. if (!this._initialQuaternion) {
  96949. this._initialQuaternion = new BABYLON.Quaternion();
  96950. }
  96951. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  96952. ['x', 'y', 'z'].forEach(function (axisName) {
  96953. if (!axis[axisName]) {
  96954. _this._initialQuaternion[axisName] = 0;
  96955. }
  96956. else {
  96957. _this._initialQuaternion[axisName] *= -1;
  96958. }
  96959. });
  96960. this._initialQuaternion.normalize();
  96961. //force rotation update
  96962. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  96963. };
  96964. return DeviceOrientationCamera;
  96965. }(BABYLON.FreeCamera));
  96966. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  96967. })(BABYLON || (BABYLON = {}));
  96968. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  96969. var BABYLON;
  96970. (function (BABYLON) {
  96971. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  96972. return function () { return new VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  96973. });
  96974. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  96975. __extends(VRDeviceOrientationFreeCamera, _super);
  96976. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  96977. if (compensateDistortion === void 0) { compensateDistortion = true; }
  96978. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  96979. var _this = _super.call(this, name, position, scene) || this;
  96980. vrCameraMetrics.compensateDistortion = compensateDistortion;
  96981. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  96982. return _this;
  96983. }
  96984. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  96985. return "VRDeviceOrientationFreeCamera";
  96986. };
  96987. return VRDeviceOrientationFreeCamera;
  96988. }(BABYLON.DeviceOrientationCamera));
  96989. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  96990. })(BABYLON || (BABYLON = {}));
  96991. //# sourceMappingURL=babylon.vrDeviceOrientationFreeCamera.js.map
  96992. var BABYLON;
  96993. (function (BABYLON) {
  96994. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  96995. return function () { return new VRDeviceOrientationArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  96996. });
  96997. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  96998. __extends(VRDeviceOrientationArcRotateCamera, _super);
  96999. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  97000. if (compensateDistortion === void 0) { compensateDistortion = true; }
  97001. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  97002. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  97003. vrCameraMetrics.compensateDistortion = compensateDistortion;
  97004. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  97005. _this.inputs.addVRDeviceOrientation();
  97006. return _this;
  97007. }
  97008. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  97009. return "VRDeviceOrientationArcRotateCamera";
  97010. };
  97011. return VRDeviceOrientationArcRotateCamera;
  97012. }(BABYLON.ArcRotateCamera));
  97013. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  97014. })(BABYLON || (BABYLON = {}));
  97015. //# sourceMappingURL=babylon.vrDeviceOrientationArcRotateCamera.js.map
  97016. var BABYLON;
  97017. (function (BABYLON) {
  97018. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationGamepadCamera", function (name, scene) {
  97019. return function () { return new VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  97020. });
  97021. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  97022. __extends(VRDeviceOrientationGamepadCamera, _super);
  97023. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  97024. if (compensateDistortion === void 0) { compensateDistortion = true; }
  97025. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  97026. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  97027. _this.inputs.addGamepad();
  97028. return _this;
  97029. }
  97030. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  97031. return "VRDeviceOrientationGamepadCamera";
  97032. };
  97033. return VRDeviceOrientationGamepadCamera;
  97034. }(BABYLON.VRDeviceOrientationFreeCamera));
  97035. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  97036. })(BABYLON || (BABYLON = {}));
  97037. //# sourceMappingURL=babylon.vrDeviceOrientationGamepadCamera.js.map
  97038. var BABYLON;
  97039. (function (BABYLON) {
  97040. var VRExperienceHelperGazer = /** @class */ (function () {
  97041. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  97042. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  97043. this.scene = scene;
  97044. /** @hidden */
  97045. this._pointerDownOnMeshAsked = false;
  97046. /** @hidden */
  97047. this._isActionableMesh = false;
  97048. /** @hidden */
  97049. this._teleportationRequestInitiated = false;
  97050. /** @hidden */
  97051. this._teleportationBackRequestInitiated = false;
  97052. /** @hidden */
  97053. this._rotationRightAsked = false;
  97054. /** @hidden */
  97055. this._rotationLeftAsked = false;
  97056. /** @hidden */
  97057. this._dpadPressed = true;
  97058. /** @hidden */
  97059. this._activePointer = false;
  97060. this._id = VRExperienceHelperGazer._idCounter++;
  97061. // Gaze tracker
  97062. if (!gazeTrackerToClone) {
  97063. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  97064. this._gazeTracker.bakeCurrentTransformIntoVertices();
  97065. this._gazeTracker.isPickable = false;
  97066. this._gazeTracker.isVisible = false;
  97067. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  97068. targetMat.specularColor = BABYLON.Color3.Black();
  97069. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  97070. targetMat.backFaceCulling = false;
  97071. this._gazeTracker.material = targetMat;
  97072. }
  97073. else {
  97074. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  97075. }
  97076. }
  97077. /** @hidden */
  97078. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  97079. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  97080. };
  97081. /** @hidden */
  97082. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  97083. this._pointerDownOnMeshAsked = true;
  97084. if (this._currentHit) {
  97085. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  97086. }
  97087. };
  97088. /** @hidden */
  97089. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  97090. if (this._currentHit) {
  97091. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  97092. }
  97093. this._pointerDownOnMeshAsked = false;
  97094. };
  97095. /** @hidden */
  97096. VRExperienceHelperGazer.prototype._activatePointer = function () {
  97097. this._activePointer = true;
  97098. };
  97099. /** @hidden */
  97100. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  97101. this._activePointer = false;
  97102. };
  97103. /** @hidden */
  97104. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  97105. if (distance === void 0) { distance = 100; }
  97106. };
  97107. VRExperienceHelperGazer.prototype.dispose = function () {
  97108. this._interactionsEnabled = false;
  97109. this._teleportationEnabled = false;
  97110. if (this._gazeTracker) {
  97111. this._gazeTracker.dispose();
  97112. }
  97113. };
  97114. VRExperienceHelperGazer._idCounter = 0;
  97115. return VRExperienceHelperGazer;
  97116. }());
  97117. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  97118. __extends(VRExperienceHelperControllerGazer, _super);
  97119. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  97120. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  97121. _this.webVRController = webVRController;
  97122. // Laser pointer
  97123. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  97124. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  97125. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  97126. laserPointerMaterial.alpha = 0.6;
  97127. _this._laserPointer.material = laserPointerMaterial;
  97128. _this._laserPointer.rotation.x = Math.PI / 2;
  97129. _this._laserPointer.position.z = -0.5;
  97130. _this._laserPointer.isVisible = false;
  97131. _this._laserPointer.isPickable = false;
  97132. if (!webVRController.mesh) {
  97133. // Create an empty mesh that is used prior to loading the high quality model
  97134. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  97135. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  97136. preloadPointerPose.rotation.x = -0.7;
  97137. preloadMesh.addChild(preloadPointerPose);
  97138. webVRController.attachToMesh(preloadMesh);
  97139. }
  97140. _this._setLaserPointerParent(webVRController.mesh);
  97141. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  97142. _this._setLaserPointerParent(mesh);
  97143. });
  97144. return _this;
  97145. }
  97146. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  97147. return this.webVRController.getForwardRay(length);
  97148. };
  97149. /** @hidden */
  97150. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  97151. _super.prototype._activatePointer.call(this);
  97152. this._laserPointer.isVisible = true;
  97153. };
  97154. /** @hidden */
  97155. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  97156. _super.prototype._deactivatePointer.call(this);
  97157. this._laserPointer.isVisible = false;
  97158. };
  97159. /** @hidden */
  97160. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  97161. this._laserPointer.material.emissiveColor = color;
  97162. };
  97163. /** @hidden */
  97164. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  97165. var makeNotPick = function (root) {
  97166. root.isPickable = false;
  97167. root.getChildMeshes().forEach(function (c) {
  97168. makeNotPick(c);
  97169. });
  97170. };
  97171. makeNotPick(mesh);
  97172. var childMeshes = mesh.getChildMeshes();
  97173. this.webVRController._pointingPoseNode = null;
  97174. for (var i = 0; i < childMeshes.length; i++) {
  97175. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  97176. mesh = childMeshes[i];
  97177. this.webVRController._pointingPoseNode = mesh;
  97178. break;
  97179. }
  97180. }
  97181. this._laserPointer.parent = mesh;
  97182. };
  97183. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  97184. if (distance === void 0) { distance = 100; }
  97185. this._laserPointer.scaling.y = distance;
  97186. this._laserPointer.position.z = -distance / 2;
  97187. };
  97188. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  97189. _super.prototype.dispose.call(this);
  97190. this._laserPointer.dispose();
  97191. if (this._meshAttachedObserver) {
  97192. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  97193. }
  97194. };
  97195. return VRExperienceHelperControllerGazer;
  97196. }(VRExperienceHelperGazer));
  97197. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  97198. __extends(VRExperienceHelperCameraGazer, _super);
  97199. function VRExperienceHelperCameraGazer(getCamera, scene) {
  97200. var _this = _super.call(this, scene) || this;
  97201. _this.getCamera = getCamera;
  97202. return _this;
  97203. }
  97204. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  97205. var camera = this.getCamera();
  97206. if (camera) {
  97207. return camera.getForwardRay(length);
  97208. }
  97209. else {
  97210. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  97211. }
  97212. };
  97213. return VRExperienceHelperCameraGazer;
  97214. }(VRExperienceHelperGazer));
  97215. /**
  97216. * Helps to quickly add VR support to an existing scene.
  97217. * See http://doc.babylonjs.com/how_to/webvr_helper
  97218. */
  97219. var VRExperienceHelper = /** @class */ (function () {
  97220. /**
  97221. * Instantiates a VRExperienceHelper.
  97222. * Helps to quickly add VR support to an existing scene.
  97223. * @param scene The scene the VRExperienceHelper belongs to.
  97224. * @param webVROptions Options to modify the vr experience helper's behavior.
  97225. */
  97226. function VRExperienceHelper(scene,
  97227. /** Options to modify the vr experience helper's behavior. */
  97228. webVROptions) {
  97229. if (webVROptions === void 0) { webVROptions = {}; }
  97230. var _this = this;
  97231. this.webVROptions = webVROptions;
  97232. // Can the system support WebVR, even if a headset isn't plugged in?
  97233. this._webVRsupported = false;
  97234. // If WebVR is supported, is a headset plugged in and are we ready to present?
  97235. this._webVRready = false;
  97236. // Are we waiting for the requestPresent callback to complete?
  97237. this._webVRrequesting = false;
  97238. // Are we presenting to the headset right now? (this is the vrDevice state)
  97239. this._webVRpresenting = false;
  97240. // Are we presenting in the fullscreen fallback?
  97241. this._fullscreenVRpresenting = false;
  97242. /**
  97243. * Observable raised when entering VR.
  97244. */
  97245. this.onEnteringVRObservable = new BABYLON.Observable();
  97246. /**
  97247. * Observable raised when exiting VR.
  97248. */
  97249. this.onExitingVRObservable = new BABYLON.Observable();
  97250. /**
  97251. * Observable raised when controller mesh is loaded.
  97252. */
  97253. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  97254. this._useCustomVRButton = false;
  97255. this._teleportationRequested = false;
  97256. this._teleportActive = false;
  97257. this._floorMeshesCollection = [];
  97258. this._rotationAllowed = true;
  97259. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  97260. this._isDefaultTeleportationTarget = true;
  97261. this._teleportationFillColor = "#444444";
  97262. this._teleportationBorderColor = "#FFFFFF";
  97263. this._rotationAngle = 0;
  97264. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  97265. this._padSensibilityUp = 0.65;
  97266. this._padSensibilityDown = 0.35;
  97267. this._leftController = null;
  97268. this._rightController = null;
  97269. /**
  97270. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  97271. */
  97272. this.onNewMeshSelected = new BABYLON.Observable();
  97273. /**
  97274. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  97275. */
  97276. this.onNewMeshPicked = new BABYLON.Observable();
  97277. /**
  97278. * Observable raised before camera teleportation
  97279. */
  97280. this.onBeforeCameraTeleport = new BABYLON.Observable();
  97281. /**
  97282. * Observable raised after camera teleportation
  97283. */
  97284. this.onAfterCameraTeleport = new BABYLON.Observable();
  97285. /**
  97286. * Observable raised when current selected mesh gets unselected
  97287. */
  97288. this.onSelectedMeshUnselected = new BABYLON.Observable();
  97289. /**
  97290. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  97291. */
  97292. this.teleportationEnabled = true;
  97293. this._teleportationInitialized = false;
  97294. this._interactionsEnabled = false;
  97295. this._interactionsRequested = false;
  97296. this._displayGaze = true;
  97297. this._displayLaserPointer = true;
  97298. /**
  97299. * If the gaze trackers scale should be updated to be constant size when pointing at near/far meshes
  97300. */
  97301. this.updateGazeTrackerScale = true;
  97302. this._onResize = function () {
  97303. _this.moveButtonToBottomRight();
  97304. if (_this._fullscreenVRpresenting && _this._webVRready) {
  97305. _this.exitVR();
  97306. }
  97307. };
  97308. this._onFullscreenChange = function () {
  97309. if (document.fullscreen !== undefined) {
  97310. _this._fullscreenVRpresenting = document.fullscreen;
  97311. }
  97312. else if (document.mozFullScreen !== undefined) {
  97313. _this._fullscreenVRpresenting = document.mozFullScreen;
  97314. }
  97315. else if (document.webkitIsFullScreen !== undefined) {
  97316. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  97317. }
  97318. else if (document.msIsFullScreen !== undefined) {
  97319. _this._fullscreenVRpresenting = document.msIsFullScreen;
  97320. }
  97321. else if (document.msFullscreenElement !== undefined) {
  97322. _this._fullscreenVRpresenting = document.msFullscreenElement;
  97323. }
  97324. if (!_this._fullscreenVRpresenting && _this._canvas) {
  97325. _this.exitVR();
  97326. if (!_this._useCustomVRButton) {
  97327. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  97328. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  97329. }
  97330. }
  97331. };
  97332. this.beforeRender = function () {
  97333. if (_this._leftController && _this._leftController._activePointer) {
  97334. _this._castRayAndSelectObject(_this._leftController);
  97335. }
  97336. if (_this._rightController && _this._rightController._activePointer) {
  97337. _this._castRayAndSelectObject(_this._rightController);
  97338. }
  97339. if (_this._noControllerIsActive) {
  97340. _this._castRayAndSelectObject(_this._cameraGazer);
  97341. }
  97342. else {
  97343. _this._cameraGazer._gazeTracker.isVisible = false;
  97344. }
  97345. };
  97346. this._onNewGamepadConnected = function (gamepad) {
  97347. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  97348. if (gamepad.leftStick) {
  97349. gamepad.onleftstickchanged(function (stickValues) {
  97350. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  97351. // Listening to classic/xbox gamepad only if no VR controller is active
  97352. if ((!_this._leftController && !_this._rightController) ||
  97353. ((_this._leftController && !_this._leftController._activePointer) &&
  97354. (_this._rightController && !_this._rightController._activePointer))) {
  97355. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  97356. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  97357. }
  97358. }
  97359. });
  97360. }
  97361. if (gamepad.rightStick) {
  97362. gamepad.onrightstickchanged(function (stickValues) {
  97363. if (_this._teleportationInitialized) {
  97364. _this._checkRotate(stickValues, _this._cameraGazer);
  97365. }
  97366. });
  97367. }
  97368. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  97369. gamepad.onbuttondown(function (buttonPressed) {
  97370. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  97371. _this._cameraGazer._selectionPointerDown();
  97372. }
  97373. });
  97374. gamepad.onbuttonup(function (buttonPressed) {
  97375. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  97376. _this._cameraGazer._selectionPointerUp();
  97377. }
  97378. });
  97379. }
  97380. }
  97381. else {
  97382. var webVRController = gamepad;
  97383. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  97384. if (webVRController.hand === "right" || (_this._leftController && _this._leftController.webVRController != webVRController)) {
  97385. _this._rightController = controller;
  97386. }
  97387. else {
  97388. _this._leftController = controller;
  97389. }
  97390. _this._tryEnableInteractionOnController(controller);
  97391. }
  97392. };
  97393. // 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
  97394. this._tryEnableInteractionOnController = function (controller) {
  97395. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  97396. _this._enableInteractionOnController(controller);
  97397. }
  97398. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  97399. _this._enableTeleportationOnController(controller);
  97400. }
  97401. };
  97402. this._onNewGamepadDisconnected = function (gamepad) {
  97403. if (gamepad instanceof BABYLON.WebVRController) {
  97404. if (gamepad.hand === "left" && _this._leftController != null) {
  97405. _this._leftController.dispose();
  97406. _this._leftController = null;
  97407. }
  97408. if (gamepad.hand === "right" && _this._rightController != null) {
  97409. _this._rightController.dispose();
  97410. _this._rightController = null;
  97411. }
  97412. }
  97413. };
  97414. this._workingVector = BABYLON.Vector3.Zero();
  97415. this._workingQuaternion = BABYLON.Quaternion.Identity();
  97416. this._workingMatrix = BABYLON.Matrix.Identity();
  97417. this._scene = scene;
  97418. this._canvas = scene.getEngine().getRenderingCanvas();
  97419. // Parse options
  97420. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  97421. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  97422. }
  97423. if (webVROptions.createDeviceOrientationCamera === undefined) {
  97424. webVROptions.createDeviceOrientationCamera = true;
  97425. }
  97426. if (webVROptions.laserToggle === undefined) {
  97427. webVROptions.laserToggle = true;
  97428. }
  97429. if (webVROptions.defaultHeight === undefined) {
  97430. webVROptions.defaultHeight = 1.7;
  97431. }
  97432. if (webVROptions.useCustomVRButton) {
  97433. this._useCustomVRButton = true;
  97434. if (webVROptions.customVRButton) {
  97435. this._btnVR = webVROptions.customVRButton;
  97436. }
  97437. }
  97438. if (webVROptions.rayLength) {
  97439. this._rayLength = webVROptions.rayLength;
  97440. }
  97441. this._defaultHeight = webVROptions.defaultHeight;
  97442. if (webVROptions.positionScale) {
  97443. this._rayLength *= webVROptions.positionScale;
  97444. this._defaultHeight *= webVROptions.positionScale;
  97445. }
  97446. this._hasEnteredVR = false;
  97447. // Set position
  97448. if (this._scene.activeCamera) {
  97449. this._position = this._scene.activeCamera.position.clone();
  97450. }
  97451. else {
  97452. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  97453. }
  97454. // Set non-vr camera
  97455. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  97456. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  97457. // Copy data from existing camera
  97458. if (this._scene.activeCamera) {
  97459. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  97460. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  97461. // Set rotation from previous camera
  97462. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  97463. var targetCamera = this._scene.activeCamera;
  97464. if (targetCamera.rotationQuaternion) {
  97465. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  97466. }
  97467. else {
  97468. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  97469. }
  97470. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  97471. }
  97472. }
  97473. this._scene.activeCamera = this._deviceOrientationCamera;
  97474. if (this._canvas) {
  97475. this._scene.activeCamera.attachControl(this._canvas);
  97476. }
  97477. }
  97478. else {
  97479. this._existingCamera = this._scene.activeCamera;
  97480. }
  97481. // Create VR cameras
  97482. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  97483. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  97484. }
  97485. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  97486. this._webVRCamera.useStandingMatrix();
  97487. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  97488. // Create default button
  97489. if (!this._useCustomVRButton) {
  97490. this._btnVR = document.createElement("BUTTON");
  97491. this._btnVR.className = "babylonVRicon";
  97492. this._btnVR.id = "babylonVRiconbtn";
  97493. this._btnVR.title = "Click to switch to VR";
  97494. 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) }";
  97495. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  97496. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  97497. // css += ".babylonVRicon.vrdisplaysupported { }";
  97498. // css += ".babylonVRicon.vrdisplayready { }";
  97499. // css += ".babylonVRicon.vrdisplayrequesting { }";
  97500. var style = document.createElement('style');
  97501. style.appendChild(document.createTextNode(css));
  97502. document.getElementsByTagName('head')[0].appendChild(style);
  97503. this.moveButtonToBottomRight();
  97504. }
  97505. // VR button click event
  97506. if (this._btnVR) {
  97507. this._btnVR.addEventListener("click", function () {
  97508. if (!_this.isInVRMode) {
  97509. _this.enterVR();
  97510. }
  97511. else {
  97512. _this.exitVR();
  97513. }
  97514. });
  97515. }
  97516. // Window events
  97517. window.addEventListener("resize", this._onResize);
  97518. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  97519. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  97520. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  97521. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  97522. document.onmsfullscreenchange = this._onFullscreenChange;
  97523. // Display vr button when headset is connected
  97524. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  97525. this.displayVRButton();
  97526. }
  97527. else {
  97528. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  97529. if (e.vrDisplay) {
  97530. _this.displayVRButton();
  97531. }
  97532. });
  97533. }
  97534. // Exiting VR mode using 'ESC' key on desktop
  97535. this._onKeyDown = function (event) {
  97536. if (event.keyCode === 27 && _this.isInVRMode) {
  97537. _this.exitVR();
  97538. }
  97539. };
  97540. document.addEventListener("keydown", this._onKeyDown);
  97541. // Exiting VR mode double tapping the touch screen
  97542. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  97543. if (_this.isInVRMode) {
  97544. _this.exitVR();
  97545. if (_this._fullscreenVRpresenting) {
  97546. _this._scene.getEngine().switchFullscreen(true);
  97547. }
  97548. }
  97549. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  97550. // Listen for WebVR display changes
  97551. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  97552. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  97553. this._onVRRequestPresentStart = function () {
  97554. _this._webVRrequesting = true;
  97555. _this.updateButtonVisibility();
  97556. };
  97557. this._onVRRequestPresentComplete = function (success) {
  97558. _this._webVRrequesting = false;
  97559. _this.updateButtonVisibility();
  97560. };
  97561. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  97562. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  97563. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  97564. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  97565. scene.onDisposeObservable.add(function () {
  97566. _this.dispose();
  97567. });
  97568. // Gamepad connection events
  97569. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  97570. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  97571. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  97572. this.updateButtonVisibility();
  97573. //create easing functions
  97574. this._circleEase = new BABYLON.CircleEase();
  97575. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  97576. if (this.webVROptions.floorMeshes) {
  97577. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  97578. }
  97579. }
  97580. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  97581. /** Return this.onEnteringVRObservable
  97582. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  97583. */
  97584. get: function () {
  97585. return this.onEnteringVRObservable;
  97586. },
  97587. enumerable: true,
  97588. configurable: true
  97589. });
  97590. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  97591. /** Return this.onExitingVRObservable
  97592. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  97593. */
  97594. get: function () {
  97595. return this.onExitingVRObservable;
  97596. },
  97597. enumerable: true,
  97598. configurable: true
  97599. });
  97600. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  97601. /** Return this.onControllerMeshLoadedObservable
  97602. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  97603. */
  97604. get: function () {
  97605. return this.onControllerMeshLoadedObservable;
  97606. },
  97607. enumerable: true,
  97608. configurable: true
  97609. });
  97610. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  97611. /**
  97612. * The mesh used to display where the user is going to teleport.
  97613. */
  97614. get: function () {
  97615. return this._teleportationTarget;
  97616. },
  97617. /**
  97618. * Sets the mesh to be used to display where the user is going to teleport.
  97619. */
  97620. set: function (value) {
  97621. if (value) {
  97622. value.name = "teleportationTarget";
  97623. this._isDefaultTeleportationTarget = false;
  97624. this._teleportationTarget = value;
  97625. }
  97626. },
  97627. enumerable: true,
  97628. configurable: true
  97629. });
  97630. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  97631. /**
  97632. * 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
  97633. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  97634. * See http://doc.babylonjs.com/resources/baking_transformations
  97635. */
  97636. get: function () {
  97637. return this._cameraGazer._gazeTracker;
  97638. },
  97639. set: function (value) {
  97640. if (value) {
  97641. // Dispose of existing meshes
  97642. if (this._cameraGazer._gazeTracker) {
  97643. this._cameraGazer._gazeTracker.dispose();
  97644. }
  97645. if (this._leftController && this._leftController._gazeTracker) {
  97646. this._leftController._gazeTracker.dispose();
  97647. }
  97648. if (this._rightController && this._rightController._gazeTracker) {
  97649. this._rightController._gazeTracker.dispose();
  97650. }
  97651. // Set and create gaze trackers on head and controllers
  97652. this._cameraGazer._gazeTracker = value;
  97653. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  97654. this._cameraGazer._gazeTracker.isPickable = false;
  97655. this._cameraGazer._gazeTracker.isVisible = false;
  97656. this._cameraGazer._gazeTracker.name = "gazeTracker";
  97657. if (this._leftController) {
  97658. this._leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  97659. }
  97660. if (this._rightController) {
  97661. this._rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  97662. }
  97663. }
  97664. },
  97665. enumerable: true,
  97666. configurable: true
  97667. });
  97668. Object.defineProperty(VRExperienceHelper.prototype, "leftControllerGazeTrackerMesh", {
  97669. /**
  97670. * The gaze tracking mesh corresponding to the left controller
  97671. */
  97672. get: function () {
  97673. if (this._leftController) {
  97674. return this._leftController._gazeTracker;
  97675. }
  97676. return null;
  97677. },
  97678. enumerable: true,
  97679. configurable: true
  97680. });
  97681. Object.defineProperty(VRExperienceHelper.prototype, "rightControllerGazeTrackerMesh", {
  97682. /**
  97683. * The gaze tracking mesh corresponding to the right controller
  97684. */
  97685. get: function () {
  97686. if (this._rightController) {
  97687. return this._rightController._gazeTracker;
  97688. }
  97689. return null;
  97690. },
  97691. enumerable: true,
  97692. configurable: true
  97693. });
  97694. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  97695. /**
  97696. * If the ray of the gaze should be displayed.
  97697. */
  97698. get: function () {
  97699. return this._displayGaze;
  97700. },
  97701. /**
  97702. * Sets if the ray of the gaze should be displayed.
  97703. */
  97704. set: function (value) {
  97705. this._displayGaze = value;
  97706. if (!value) {
  97707. this._cameraGazer._gazeTracker.isVisible = false;
  97708. if (this._leftController) {
  97709. this._leftController._gazeTracker.isVisible = false;
  97710. }
  97711. if (this._rightController) {
  97712. this._rightController._gazeTracker.isVisible = false;
  97713. }
  97714. }
  97715. },
  97716. enumerable: true,
  97717. configurable: true
  97718. });
  97719. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  97720. /**
  97721. * If the ray of the LaserPointer should be displayed.
  97722. */
  97723. get: function () {
  97724. return this._displayLaserPointer;
  97725. },
  97726. /**
  97727. * Sets if the ray of the LaserPointer should be displayed.
  97728. */
  97729. set: function (value) {
  97730. this._displayLaserPointer = value;
  97731. if (!value) {
  97732. if (this._rightController) {
  97733. this._rightController._deactivatePointer();
  97734. this._rightController._gazeTracker.isVisible = false;
  97735. }
  97736. if (this._leftController) {
  97737. this._leftController._deactivatePointer();
  97738. this._leftController._gazeTracker.isVisible = false;
  97739. }
  97740. }
  97741. else {
  97742. if (this._rightController) {
  97743. this._rightController._activatePointer();
  97744. }
  97745. if (this._leftController) {
  97746. this._leftController._activatePointer();
  97747. }
  97748. }
  97749. },
  97750. enumerable: true,
  97751. configurable: true
  97752. });
  97753. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  97754. /**
  97755. * The deviceOrientationCamera used as the camera when not in VR.
  97756. */
  97757. get: function () {
  97758. return this._deviceOrientationCamera;
  97759. },
  97760. enumerable: true,
  97761. configurable: true
  97762. });
  97763. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  97764. /**
  97765. * Based on the current WebVR support, returns the current VR camera used.
  97766. */
  97767. get: function () {
  97768. if (this._webVRready) {
  97769. return this._webVRCamera;
  97770. }
  97771. else {
  97772. return this._scene.activeCamera;
  97773. }
  97774. },
  97775. enumerable: true,
  97776. configurable: true
  97777. });
  97778. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  97779. /**
  97780. * The webVRCamera which is used when in VR.
  97781. */
  97782. get: function () {
  97783. return this._webVRCamera;
  97784. },
  97785. enumerable: true,
  97786. configurable: true
  97787. });
  97788. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  97789. /**
  97790. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  97791. */
  97792. get: function () {
  97793. return this._vrDeviceOrientationCamera;
  97794. },
  97795. enumerable: true,
  97796. configurable: true
  97797. });
  97798. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  97799. get: function () {
  97800. var result = this._cameraGazer._teleportationRequestInitiated
  97801. || (this._leftController !== null && this._leftController._teleportationRequestInitiated)
  97802. || (this._rightController !== null && this._rightController._teleportationRequestInitiated);
  97803. return result;
  97804. },
  97805. enumerable: true,
  97806. configurable: true
  97807. });
  97808. // Raised when one of the controller has loaded successfully its associated default mesh
  97809. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  97810. if (this._leftController && this._leftController.webVRController == webVRController) {
  97811. if (webVRController.mesh) {
  97812. this._leftController._setLaserPointerParent(webVRController.mesh);
  97813. }
  97814. }
  97815. if (this._rightController && this._rightController.webVRController == webVRController) {
  97816. if (webVRController.mesh) {
  97817. this._rightController._setLaserPointerParent(webVRController.mesh);
  97818. }
  97819. }
  97820. try {
  97821. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  97822. }
  97823. catch (err) {
  97824. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  97825. }
  97826. };
  97827. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  97828. /**
  97829. * Gets a value indicating if we are currently in VR mode.
  97830. */
  97831. get: function () {
  97832. return this._webVRpresenting || this._fullscreenVRpresenting;
  97833. },
  97834. enumerable: true,
  97835. configurable: true
  97836. });
  97837. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  97838. var vrDisplay = this._scene.getEngine().getVRDevice();
  97839. if (vrDisplay) {
  97840. var wasPresenting = this._webVRpresenting;
  97841. this._webVRpresenting = vrDisplay.isPresenting;
  97842. if (wasPresenting && !this._webVRpresenting)
  97843. this.exitVR();
  97844. }
  97845. else {
  97846. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  97847. }
  97848. this.updateButtonVisibility();
  97849. };
  97850. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  97851. this._webVRsupported = eventArgs.vrSupported;
  97852. this._webVRready = !!eventArgs.vrDisplay;
  97853. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  97854. this.updateButtonVisibility();
  97855. };
  97856. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  97857. if (this._canvas && !this._useCustomVRButton) {
  97858. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  97859. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  97860. }
  97861. };
  97862. VRExperienceHelper.prototype.displayVRButton = function () {
  97863. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  97864. document.body.appendChild(this._btnVR);
  97865. this._btnVRDisplayed = true;
  97866. }
  97867. };
  97868. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  97869. if (!this._btnVR || this._useCustomVRButton) {
  97870. return;
  97871. }
  97872. this._btnVR.className = "babylonVRicon";
  97873. if (this.isInVRMode) {
  97874. this._btnVR.className += " vrdisplaypresenting";
  97875. }
  97876. else {
  97877. if (this._webVRready)
  97878. this._btnVR.className += " vrdisplayready";
  97879. if (this._webVRsupported)
  97880. this._btnVR.className += " vrdisplaysupported";
  97881. if (this._webVRrequesting)
  97882. this._btnVR.className += " vrdisplayrequesting";
  97883. }
  97884. };
  97885. /**
  97886. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  97887. * Otherwise, will use the fullscreen API.
  97888. */
  97889. VRExperienceHelper.prototype.enterVR = function () {
  97890. if (this.onEnteringVRObservable) {
  97891. try {
  97892. this.onEnteringVRObservable.notifyObservers(this);
  97893. }
  97894. catch (err) {
  97895. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  97896. }
  97897. }
  97898. if (this._scene.activeCamera) {
  97899. this._position = this._scene.activeCamera.position.clone();
  97900. // make sure that we return to the last active camera
  97901. this._existingCamera = this._scene.activeCamera;
  97902. }
  97903. if (this._webVRrequesting)
  97904. return;
  97905. // If WebVR is supported and a headset is connected
  97906. if (this._webVRready) {
  97907. if (!this._webVRpresenting) {
  97908. this._webVRCamera.position = this._position;
  97909. this._scene.activeCamera = this._webVRCamera;
  97910. }
  97911. }
  97912. else if (this._vrDeviceOrientationCamera) {
  97913. this._vrDeviceOrientationCamera.position = this._position;
  97914. if (this._scene.activeCamera) {
  97915. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  97916. }
  97917. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  97918. this._scene.getEngine().switchFullscreen(true);
  97919. this.updateButtonVisibility();
  97920. }
  97921. if (this._scene.activeCamera && this._canvas) {
  97922. this._scene.activeCamera.attachControl(this._canvas);
  97923. }
  97924. if (this._interactionsEnabled) {
  97925. this._scene.registerBeforeRender(this.beforeRender);
  97926. }
  97927. this._hasEnteredVR = true;
  97928. };
  97929. /**
  97930. * Attempt to exit VR, or fullscreen.
  97931. */
  97932. VRExperienceHelper.prototype.exitVR = function () {
  97933. if (this._hasEnteredVR) {
  97934. if (this.onExitingVRObservable) {
  97935. try {
  97936. this.onExitingVRObservable.notifyObservers(this);
  97937. }
  97938. catch (err) {
  97939. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  97940. }
  97941. }
  97942. if (this._webVRpresenting) {
  97943. this._scene.getEngine().disableVR();
  97944. }
  97945. if (this._scene.activeCamera) {
  97946. this._position = this._scene.activeCamera.position.clone();
  97947. }
  97948. if (this._deviceOrientationCamera) {
  97949. this._deviceOrientationCamera.position = this._position;
  97950. this._scene.activeCamera = this._deviceOrientationCamera;
  97951. if (this._canvas) {
  97952. this._scene.activeCamera.attachControl(this._canvas);
  97953. }
  97954. }
  97955. else if (this._existingCamera) {
  97956. this._existingCamera.position = this._position;
  97957. this._scene.activeCamera = this._existingCamera;
  97958. }
  97959. this.updateButtonVisibility();
  97960. if (this._interactionsEnabled) {
  97961. this._scene.unregisterBeforeRender(this.beforeRender);
  97962. this._cameraGazer._gazeTracker.isVisible = false;
  97963. if (this._leftController) {
  97964. this._leftController._gazeTracker.isVisible = false;
  97965. }
  97966. if (this._rightController) {
  97967. this._rightController._gazeTracker.isVisible = false;
  97968. }
  97969. }
  97970. // resize to update width and height when exiting vr exits fullscreen
  97971. this._scene.getEngine().resize();
  97972. this._hasEnteredVR = false;
  97973. }
  97974. };
  97975. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  97976. /**
  97977. * The position of the vr experience helper.
  97978. */
  97979. get: function () {
  97980. return this._position;
  97981. },
  97982. /**
  97983. * Sets the position of the vr experience helper.
  97984. */
  97985. set: function (value) {
  97986. this._position = value;
  97987. if (this._scene.activeCamera) {
  97988. this._scene.activeCamera.position = value;
  97989. }
  97990. },
  97991. enumerable: true,
  97992. configurable: true
  97993. });
  97994. /**
  97995. * Enables controllers and user interactions such as selecting and object or clicking on an object.
  97996. */
  97997. VRExperienceHelper.prototype.enableInteractions = function () {
  97998. var _this = this;
  97999. if (!this._interactionsEnabled) {
  98000. this._interactionsRequested = true;
  98001. if (this._leftController) {
  98002. this._enableInteractionOnController(this._leftController);
  98003. }
  98004. if (this._rightController) {
  98005. this._enableInteractionOnController(this._rightController);
  98006. }
  98007. this.raySelectionPredicate = function (mesh) {
  98008. return mesh.isVisible && (mesh.isPickable || mesh.name === _this._floorMeshName);
  98009. };
  98010. this.meshSelectionPredicate = function (mesh) {
  98011. return true;
  98012. };
  98013. this._raySelectionPredicate = function (mesh) {
  98014. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  98015. && mesh.name.indexOf("teleportationTarget") === -1
  98016. && mesh.name.indexOf("torusTeleportation") === -1)) {
  98017. return _this.raySelectionPredicate(mesh);
  98018. }
  98019. return false;
  98020. };
  98021. this._interactionsEnabled = true;
  98022. }
  98023. };
  98024. Object.defineProperty(VRExperienceHelper.prototype, "_noControllerIsActive", {
  98025. get: function () {
  98026. return !(this._leftController && this._leftController._activePointer) && !(this._rightController && this._rightController._activePointer);
  98027. },
  98028. enumerable: true,
  98029. configurable: true
  98030. });
  98031. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  98032. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  98033. if (this._floorMeshesCollection[i].id === mesh.id) {
  98034. return true;
  98035. }
  98036. }
  98037. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  98038. return true;
  98039. }
  98040. return false;
  98041. };
  98042. /**
  98043. * Adds a floor mesh to be used for teleportation.
  98044. * @param floorMesh the mesh to be used for teleportation.
  98045. */
  98046. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  98047. if (!this._floorMeshesCollection) {
  98048. return;
  98049. }
  98050. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  98051. return;
  98052. }
  98053. this._floorMeshesCollection.push(floorMesh);
  98054. };
  98055. /**
  98056. * Removes a floor mesh from being used for teleportation.
  98057. * @param floorMesh the mesh to be removed.
  98058. */
  98059. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  98060. if (!this._floorMeshesCollection) {
  98061. return;
  98062. }
  98063. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  98064. if (meshIndex !== -1) {
  98065. this._floorMeshesCollection.splice(meshIndex, 1);
  98066. }
  98067. };
  98068. /**
  98069. * Enables interactions and teleportation using the VR controllers and gaze.
  98070. * @param vrTeleportationOptions options to modify teleportation behavior.
  98071. */
  98072. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  98073. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  98074. if (!this._teleportationInitialized) {
  98075. this._teleportationRequested = true;
  98076. this.enableInteractions();
  98077. if (vrTeleportationOptions.floorMeshName) {
  98078. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  98079. }
  98080. if (vrTeleportationOptions.floorMeshes) {
  98081. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  98082. }
  98083. if (this._leftController != null) {
  98084. this._enableTeleportationOnController(this._leftController);
  98085. }
  98086. if (this._rightController != null) {
  98087. this._enableTeleportationOnController(this._rightController);
  98088. }
  98089. // Creates an image processing post process for the vignette not relying
  98090. // on the main scene configuration for image processing to reduce setup and spaces
  98091. // (gamma/linear) conflicts.
  98092. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  98093. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  98094. imageProcessingConfiguration.vignetteEnabled = true;
  98095. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  98096. this._webVRCamera.detachPostProcess(this._postProcessMove);
  98097. this._teleportationInitialized = true;
  98098. if (this._isDefaultTeleportationTarget) {
  98099. this._createTeleportationCircles();
  98100. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  98101. }
  98102. }
  98103. };
  98104. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  98105. var _this = this;
  98106. var controllerMesh = controller.webVRController.mesh;
  98107. if (controllerMesh) {
  98108. controller._interactionsEnabled = true;
  98109. controller._activatePointer();
  98110. if (this.webVROptions.laserToggle) {
  98111. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  98112. // Enabling / disabling laserPointer
  98113. if (_this._displayLaserPointer && stateObject.value === 1) {
  98114. if (controller._activePointer) {
  98115. controller._deactivatePointer();
  98116. }
  98117. else {
  98118. controller._activatePointer();
  98119. }
  98120. if (_this.displayGaze) {
  98121. controller._gazeTracker.isVisible = controller._activePointer;
  98122. }
  98123. }
  98124. });
  98125. }
  98126. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  98127. var gazer = controller;
  98128. if (_this._noControllerIsActive) {
  98129. gazer = _this._cameraGazer;
  98130. }
  98131. if (!gazer._pointerDownOnMeshAsked) {
  98132. if (stateObject.value > _this._padSensibilityUp) {
  98133. gazer._selectionPointerDown();
  98134. }
  98135. }
  98136. else if (stateObject.value < _this._padSensibilityDown) {
  98137. gazer._selectionPointerUp();
  98138. }
  98139. });
  98140. }
  98141. };
  98142. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  98143. // Dont teleport if another gaze already requested teleportation
  98144. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  98145. return;
  98146. }
  98147. if (!gazer._teleportationRequestInitiated) {
  98148. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  98149. gazer._activatePointer();
  98150. gazer._teleportationRequestInitiated = true;
  98151. }
  98152. }
  98153. else {
  98154. // Listening to the proper controller values changes to confirm teleportation
  98155. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  98156. if (this._teleportActive) {
  98157. this.teleportCamera(this._haloCenter);
  98158. }
  98159. gazer._teleportationRequestInitiated = false;
  98160. }
  98161. }
  98162. };
  98163. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  98164. // Only rotate when user is not currently selecting a teleportation location
  98165. if (gazer._teleportationRequestInitiated) {
  98166. return;
  98167. }
  98168. if (!gazer._rotationLeftAsked) {
  98169. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  98170. gazer._rotationLeftAsked = true;
  98171. if (this._rotationAllowed) {
  98172. this._rotateCamera(false);
  98173. }
  98174. }
  98175. }
  98176. else {
  98177. if (stateObject.x > -this._padSensibilityDown) {
  98178. gazer._rotationLeftAsked = false;
  98179. }
  98180. }
  98181. if (!gazer._rotationRightAsked) {
  98182. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  98183. gazer._rotationRightAsked = true;
  98184. if (this._rotationAllowed) {
  98185. this._rotateCamera(true);
  98186. }
  98187. }
  98188. }
  98189. else {
  98190. if (stateObject.x < this._padSensibilityDown) {
  98191. gazer._rotationRightAsked = false;
  98192. }
  98193. }
  98194. };
  98195. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  98196. // Only teleport backwards when user is not currently selecting a teleportation location
  98197. if (gazer._teleportationRequestInitiated) {
  98198. return;
  98199. }
  98200. // Teleport backwards
  98201. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  98202. if (!gazer._teleportationBackRequestInitiated) {
  98203. if (!this.currentVRCamera) {
  98204. return;
  98205. }
  98206. // Get rotation and position of the current camera
  98207. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  98208. var position = this.currentVRCamera.position;
  98209. // If the camera has device position, use that instead
  98210. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  98211. rotation = this.currentVRCamera.deviceRotationQuaternion;
  98212. position = this.currentVRCamera.devicePosition;
  98213. }
  98214. // Get matrix with only the y rotation of the device rotation
  98215. rotation.toEulerAnglesToRef(this._workingVector);
  98216. this._workingVector.z = 0;
  98217. this._workingVector.x = 0;
  98218. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  98219. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  98220. // Rotate backwards ray by device rotation to cast at the ground behind the user
  98221. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  98222. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  98223. var ray = new BABYLON.Ray(position, this._workingVector);
  98224. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  98225. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  98226. this.teleportCamera(hit.pickedPoint);
  98227. }
  98228. gazer._teleportationBackRequestInitiated = true;
  98229. }
  98230. }
  98231. else {
  98232. gazer._teleportationBackRequestInitiated = false;
  98233. }
  98234. };
  98235. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  98236. var _this = this;
  98237. var controllerMesh = controller.webVRController.mesh;
  98238. if (controllerMesh) {
  98239. if (!controller._interactionsEnabled) {
  98240. this._enableInteractionOnController(controller);
  98241. }
  98242. controller._interactionsEnabled = true;
  98243. controller._teleportationEnabled = true;
  98244. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  98245. controller._dpadPressed = false;
  98246. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  98247. controller._dpadPressed = stateObject.pressed;
  98248. if (!controller._dpadPressed) {
  98249. controller._rotationLeftAsked = false;
  98250. controller._rotationRightAsked = false;
  98251. controller._teleportationBackRequestInitiated = false;
  98252. }
  98253. });
  98254. }
  98255. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  98256. if (_this.teleportationEnabled) {
  98257. _this._checkTeleportBackwards(stateObject, controller);
  98258. _this._checkTeleportWithRay(stateObject, controller);
  98259. }
  98260. _this._checkRotate(stateObject, controller);
  98261. });
  98262. }
  98263. };
  98264. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  98265. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  98266. this._teleportationTarget.isPickable = false;
  98267. var length = 512;
  98268. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  98269. dynamicTexture.hasAlpha = true;
  98270. var context = dynamicTexture.getContext();
  98271. var centerX = length / 2;
  98272. var centerY = length / 2;
  98273. var radius = 200;
  98274. context.beginPath();
  98275. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  98276. context.fillStyle = this._teleportationFillColor;
  98277. context.fill();
  98278. context.lineWidth = 10;
  98279. context.strokeStyle = this._teleportationBorderColor;
  98280. context.stroke();
  98281. context.closePath();
  98282. dynamicTexture.update();
  98283. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  98284. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  98285. this._teleportationTarget.material = teleportationCircleMaterial;
  98286. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  98287. torus.isPickable = false;
  98288. torus.parent = this._teleportationTarget;
  98289. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  98290. var keys = [];
  98291. keys.push({
  98292. frame: 0,
  98293. value: 0
  98294. });
  98295. keys.push({
  98296. frame: 30,
  98297. value: 0.4
  98298. });
  98299. keys.push({
  98300. frame: 60,
  98301. value: 0
  98302. });
  98303. animationInnerCircle.setKeys(keys);
  98304. var easingFunction = new BABYLON.SineEase();
  98305. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  98306. animationInnerCircle.setEasingFunction(easingFunction);
  98307. torus.animations = [];
  98308. torus.animations.push(animationInnerCircle);
  98309. this._scene.beginAnimation(torus, 0, 60, true);
  98310. this._hideTeleportationTarget();
  98311. };
  98312. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  98313. this._teleportActive = true;
  98314. if (this._teleportationInitialized) {
  98315. this._teleportationTarget.isVisible = true;
  98316. if (this._isDefaultTeleportationTarget) {
  98317. this._teleportationTarget.getChildren()[0].isVisible = true;
  98318. }
  98319. }
  98320. };
  98321. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  98322. this._teleportActive = false;
  98323. if (this._teleportationInitialized) {
  98324. this._teleportationTarget.isVisible = false;
  98325. if (this._isDefaultTeleportationTarget) {
  98326. this._teleportationTarget.getChildren()[0].isVisible = false;
  98327. }
  98328. }
  98329. };
  98330. VRExperienceHelper.prototype._rotateCamera = function (right) {
  98331. var _this = this;
  98332. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  98333. return;
  98334. }
  98335. if (right) {
  98336. this._rotationAngle++;
  98337. }
  98338. else {
  98339. this._rotationAngle--;
  98340. }
  98341. this.currentVRCamera.animations = [];
  98342. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  98343. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  98344. var animationRotationKeys = [];
  98345. animationRotationKeys.push({
  98346. frame: 0,
  98347. value: this.currentVRCamera.rotationQuaternion
  98348. });
  98349. animationRotationKeys.push({
  98350. frame: 6,
  98351. value: target
  98352. });
  98353. animationRotation.setKeys(animationRotationKeys);
  98354. animationRotation.setEasingFunction(this._circleEase);
  98355. this.currentVRCamera.animations.push(animationRotation);
  98356. this._postProcessMove.animations = [];
  98357. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  98358. var vignetteWeightKeys = [];
  98359. vignetteWeightKeys.push({
  98360. frame: 0,
  98361. value: 0
  98362. });
  98363. vignetteWeightKeys.push({
  98364. frame: 3,
  98365. value: 4
  98366. });
  98367. vignetteWeightKeys.push({
  98368. frame: 6,
  98369. value: 0
  98370. });
  98371. animationPP.setKeys(vignetteWeightKeys);
  98372. animationPP.setEasingFunction(this._circleEase);
  98373. this._postProcessMove.animations.push(animationPP);
  98374. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  98375. var vignetteStretchKeys = [];
  98376. vignetteStretchKeys.push({
  98377. frame: 0,
  98378. value: 0
  98379. });
  98380. vignetteStretchKeys.push({
  98381. frame: 3,
  98382. value: 10
  98383. });
  98384. vignetteStretchKeys.push({
  98385. frame: 6,
  98386. value: 0
  98387. });
  98388. animationPP2.setKeys(vignetteStretchKeys);
  98389. animationPP2.setEasingFunction(this._circleEase);
  98390. this._postProcessMove.animations.push(animationPP2);
  98391. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  98392. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  98393. this._postProcessMove.samples = 4;
  98394. this._webVRCamera.attachPostProcess(this._postProcessMove);
  98395. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  98396. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  98397. });
  98398. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  98399. };
  98400. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  98401. if (hit.pickedPoint) {
  98402. if (gazer._teleportationRequestInitiated) {
  98403. this._displayTeleportationTarget();
  98404. this._haloCenter.copyFrom(hit.pickedPoint);
  98405. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  98406. }
  98407. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  98408. if (pickNormal) {
  98409. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  98410. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  98411. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  98412. }
  98413. this._teleportationTarget.position.y += 0.1;
  98414. }
  98415. };
  98416. /**
  98417. * Teleports the users feet to the desired location
  98418. * @param location The location where the user's feet should be placed
  98419. */
  98420. VRExperienceHelper.prototype.teleportCamera = function (location) {
  98421. var _this = this;
  98422. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  98423. return;
  98424. }
  98425. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  98426. // offset of the headset from the anchor.
  98427. if (this.webVRCamera.leftCamera) {
  98428. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  98429. this._workingVector.subtractInPlace(this.webVRCamera.position);
  98430. location.subtractToRef(this._workingVector, this._workingVector);
  98431. }
  98432. else {
  98433. this._workingVector.copyFrom(location);
  98434. }
  98435. // Add height to account for user's height offset
  98436. if (this.isInVRMode) {
  98437. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  98438. }
  98439. else {
  98440. this._workingVector.y += this._defaultHeight;
  98441. }
  98442. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  98443. // Create animation from the camera's position to the new location
  98444. this.currentVRCamera.animations = [];
  98445. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  98446. var animationCameraTeleportationKeys = [{
  98447. frame: 0,
  98448. value: this.currentVRCamera.position
  98449. },
  98450. {
  98451. frame: 11,
  98452. value: this._workingVector
  98453. }
  98454. ];
  98455. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  98456. animationCameraTeleportation.setEasingFunction(this._circleEase);
  98457. this.currentVRCamera.animations.push(animationCameraTeleportation);
  98458. this._postProcessMove.animations = [];
  98459. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  98460. var vignetteWeightKeys = [];
  98461. vignetteWeightKeys.push({
  98462. frame: 0,
  98463. value: 0
  98464. });
  98465. vignetteWeightKeys.push({
  98466. frame: 5,
  98467. value: 8
  98468. });
  98469. vignetteWeightKeys.push({
  98470. frame: 11,
  98471. value: 0
  98472. });
  98473. animationPP.setKeys(vignetteWeightKeys);
  98474. this._postProcessMove.animations.push(animationPP);
  98475. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  98476. var vignetteStretchKeys = [];
  98477. vignetteStretchKeys.push({
  98478. frame: 0,
  98479. value: 0
  98480. });
  98481. vignetteStretchKeys.push({
  98482. frame: 5,
  98483. value: 10
  98484. });
  98485. vignetteStretchKeys.push({
  98486. frame: 11,
  98487. value: 0
  98488. });
  98489. animationPP2.setKeys(vignetteStretchKeys);
  98490. this._postProcessMove.animations.push(animationPP2);
  98491. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  98492. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  98493. this._webVRCamera.attachPostProcess(this._postProcessMove);
  98494. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  98495. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  98496. });
  98497. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  98498. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  98499. });
  98500. this._hideTeleportationTarget();
  98501. };
  98502. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  98503. if (normal) {
  98504. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  98505. if (angle < Math.PI / 2) {
  98506. normal.scaleInPlace(-1);
  98507. }
  98508. }
  98509. return normal;
  98510. };
  98511. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  98512. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  98513. return;
  98514. }
  98515. var ray = gazer._getForwardRay(this._rayLength);
  98516. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  98517. if (hit) {
  98518. // Populate the contrllers mesh that can be used for drag/drop
  98519. if (gazer._laserPointer) {
  98520. hit.originMesh = gazer._laserPointer.parent;
  98521. }
  98522. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  98523. }
  98524. gazer._currentHit = hit;
  98525. // Moving the gazeTracker on the mesh face targetted
  98526. if (hit && hit.pickedPoint) {
  98527. if (this._displayGaze) {
  98528. var multiplier = 1;
  98529. gazer._gazeTracker.isVisible = true;
  98530. if (gazer._isActionableMesh) {
  98531. multiplier = 3;
  98532. }
  98533. if (this.updateGazeTrackerScale) {
  98534. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  98535. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  98536. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  98537. }
  98538. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  98539. // To avoid z-fighting
  98540. var deltaFighting = 0.002;
  98541. if (pickNormal) {
  98542. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  98543. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  98544. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  98545. }
  98546. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  98547. if (gazer._gazeTracker.position.x < 0) {
  98548. gazer._gazeTracker.position.x += deltaFighting;
  98549. }
  98550. else {
  98551. gazer._gazeTracker.position.x -= deltaFighting;
  98552. }
  98553. if (gazer._gazeTracker.position.y < 0) {
  98554. gazer._gazeTracker.position.y += deltaFighting;
  98555. }
  98556. else {
  98557. gazer._gazeTracker.position.y -= deltaFighting;
  98558. }
  98559. if (gazer._gazeTracker.position.z < 0) {
  98560. gazer._gazeTracker.position.z += deltaFighting;
  98561. }
  98562. else {
  98563. gazer._gazeTracker.position.z -= deltaFighting;
  98564. }
  98565. }
  98566. // Changing the size of the laser pointer based on the distance from the targetted point
  98567. gazer._updatePointerDistance(hit.distance);
  98568. }
  98569. else {
  98570. gazer._updatePointerDistance();
  98571. gazer._gazeTracker.isVisible = false;
  98572. }
  98573. if (hit && hit.pickedMesh) {
  98574. // The object selected is the floor, we're in a teleportation scenario
  98575. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  98576. // Moving the teleportation area to this targetted point
  98577. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  98578. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  98579. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  98580. }
  98581. gazer._currentMeshSelected = null;
  98582. if (gazer._teleportationRequestInitiated) {
  98583. this._moveTeleportationSelectorTo(hit, gazer, ray);
  98584. }
  98585. return;
  98586. }
  98587. // If not, we're in a selection scenario
  98588. //this._teleportationAllowed = false;
  98589. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  98590. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  98591. this.onNewMeshPicked.notifyObservers(hit);
  98592. gazer._currentMeshSelected = hit.pickedMesh;
  98593. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  98594. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  98595. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  98596. gazer._isActionableMesh = true;
  98597. }
  98598. else {
  98599. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  98600. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  98601. gazer._isActionableMesh = false;
  98602. }
  98603. try {
  98604. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  98605. }
  98606. catch (err) {
  98607. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  98608. }
  98609. }
  98610. else {
  98611. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  98612. gazer._currentMeshSelected = null;
  98613. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  98614. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  98615. }
  98616. }
  98617. }
  98618. else {
  98619. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  98620. gazer._currentMeshSelected = null;
  98621. //this._teleportationAllowed = false;
  98622. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  98623. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  98624. }
  98625. };
  98626. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  98627. if (mesh) {
  98628. this.onSelectedMeshUnselected.notifyObservers(mesh);
  98629. }
  98630. };
  98631. /**
  98632. * Sets the color of the laser ray from the vr controllers.
  98633. * @param color new color for the ray.
  98634. */
  98635. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  98636. if (this._leftController) {
  98637. this._leftController._setLaserPointerColor(color);
  98638. }
  98639. if (this._rightController) {
  98640. this._rightController._setLaserPointerColor(color);
  98641. }
  98642. };
  98643. /**
  98644. * Sets the color of the ray from the vr headsets gaze.
  98645. * @param color new color for the ray.
  98646. */
  98647. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  98648. if (!this._cameraGazer._gazeTracker.material) {
  98649. return;
  98650. }
  98651. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  98652. if (this._leftController) {
  98653. this._leftController._gazeTracker.material.emissiveColor = color;
  98654. }
  98655. if (this._rightController) {
  98656. this._rightController._gazeTracker.material.emissiveColor = color;
  98657. }
  98658. };
  98659. /**
  98660. * Exits VR and disposes of the vr experience helper
  98661. */
  98662. VRExperienceHelper.prototype.dispose = function () {
  98663. if (this.isInVRMode) {
  98664. this.exitVR();
  98665. }
  98666. if (this._postProcessMove) {
  98667. this._postProcessMove.dispose();
  98668. }
  98669. if (this._webVRCamera) {
  98670. this._webVRCamera.dispose();
  98671. }
  98672. if (this._vrDeviceOrientationCamera) {
  98673. this._vrDeviceOrientationCamera.dispose();
  98674. }
  98675. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  98676. document.body.removeChild(this._btnVR);
  98677. }
  98678. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  98679. this._deviceOrientationCamera.dispose();
  98680. }
  98681. if (this._cameraGazer) {
  98682. this._cameraGazer.dispose();
  98683. }
  98684. if (this._leftController) {
  98685. this._leftController.dispose();
  98686. }
  98687. if (this._rightController) {
  98688. this._rightController.dispose();
  98689. }
  98690. if (this._teleportationTarget) {
  98691. this._teleportationTarget.dispose();
  98692. }
  98693. this._floorMeshesCollection = [];
  98694. document.removeEventListener("keydown", this._onKeyDown);
  98695. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  98696. window.removeEventListener("resize", this._onResize);
  98697. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  98698. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  98699. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  98700. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  98701. document.onmsfullscreenchange = null;
  98702. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  98703. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  98704. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  98705. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  98706. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  98707. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  98708. this._scene.unregisterBeforeRender(this.beforeRender);
  98709. };
  98710. /**
  98711. * Gets the name of the VRExperienceHelper class
  98712. * @returns "VRExperienceHelper"
  98713. */
  98714. VRExperienceHelper.prototype.getClassName = function () {
  98715. return "VRExperienceHelper";
  98716. };
  98717. return VRExperienceHelper;
  98718. }());
  98719. BABYLON.VRExperienceHelper = VRExperienceHelper;
  98720. })(BABYLON || (BABYLON = {}));
  98721. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  98722. // Mainly based on these 2 articles :
  98723. // 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
  98724. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  98725. var BABYLON;
  98726. (function (BABYLON) {
  98727. /**
  98728. * Defines the potential axis of a Joystick
  98729. */
  98730. var JoystickAxis;
  98731. (function (JoystickAxis) {
  98732. /** X axis */
  98733. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  98734. /** Y axis */
  98735. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  98736. /** Z axis */
  98737. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  98738. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  98739. /**
  98740. * Class used to define virtual joystick (used in touch mode)
  98741. */
  98742. var VirtualJoystick = /** @class */ (function () {
  98743. /**
  98744. * Creates a new virtual joystick
  98745. * @param leftJoystick defines that the joystick is for left hand (false by default)
  98746. */
  98747. function VirtualJoystick(leftJoystick) {
  98748. var _this = this;
  98749. if (leftJoystick) {
  98750. this._leftJoystick = true;
  98751. }
  98752. else {
  98753. this._leftJoystick = false;
  98754. }
  98755. VirtualJoystick._globalJoystickIndex++;
  98756. // By default left & right arrow keys are moving the X
  98757. // and up & down keys are moving the Y
  98758. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  98759. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  98760. this.reverseLeftRight = false;
  98761. this.reverseUpDown = false;
  98762. // collections of pointers
  98763. this._touches = new BABYLON.StringDictionary();
  98764. this.deltaPosition = BABYLON.Vector3.Zero();
  98765. this._joystickSensibility = 25;
  98766. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  98767. this._onResize = function (evt) {
  98768. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  98769. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  98770. if (VirtualJoystick.vjCanvas) {
  98771. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  98772. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  98773. }
  98774. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  98775. };
  98776. // injecting a canvas element on top of the canvas 3D game
  98777. if (!VirtualJoystick.vjCanvas) {
  98778. window.addEventListener("resize", this._onResize, false);
  98779. VirtualJoystick.vjCanvas = document.createElement("canvas");
  98780. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  98781. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  98782. VirtualJoystick.vjCanvas.width = window.innerWidth;
  98783. VirtualJoystick.vjCanvas.height = window.innerHeight;
  98784. VirtualJoystick.vjCanvas.style.width = "100%";
  98785. VirtualJoystick.vjCanvas.style.height = "100%";
  98786. VirtualJoystick.vjCanvas.style.position = "absolute";
  98787. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  98788. VirtualJoystick.vjCanvas.style.top = "0px";
  98789. VirtualJoystick.vjCanvas.style.left = "0px";
  98790. VirtualJoystick.vjCanvas.style.zIndex = "5";
  98791. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  98792. // Support for jQuery PEP polyfill
  98793. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  98794. var context = VirtualJoystick.vjCanvas.getContext('2d');
  98795. if (!context) {
  98796. throw new Error("Unable to create canvas for virtual joystick");
  98797. }
  98798. VirtualJoystick.vjCanvasContext = context;
  98799. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  98800. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  98801. document.body.appendChild(VirtualJoystick.vjCanvas);
  98802. }
  98803. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  98804. this.pressed = false;
  98805. // default joystick color
  98806. this._joystickColor = "cyan";
  98807. this._joystickPointerID = -1;
  98808. // current joystick position
  98809. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  98810. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  98811. // origin joystick position
  98812. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  98813. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  98814. this._onPointerDownHandlerRef = function (evt) {
  98815. _this._onPointerDown(evt);
  98816. };
  98817. this._onPointerMoveHandlerRef = function (evt) {
  98818. _this._onPointerMove(evt);
  98819. };
  98820. this._onPointerUpHandlerRef = function (evt) {
  98821. _this._onPointerUp(evt);
  98822. };
  98823. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  98824. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  98825. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  98826. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  98827. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  98828. evt.preventDefault(); // Disables system menu
  98829. }, false);
  98830. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  98831. }
  98832. /**
  98833. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  98834. * @param newJoystickSensibility defines the new sensibility
  98835. */
  98836. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  98837. this._joystickSensibility = newJoystickSensibility;
  98838. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  98839. };
  98840. VirtualJoystick.prototype._onPointerDown = function (e) {
  98841. var positionOnScreenCondition;
  98842. e.preventDefault();
  98843. if (this._leftJoystick === true) {
  98844. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  98845. }
  98846. else {
  98847. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  98848. }
  98849. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  98850. // First contact will be dedicated to the virtual joystick
  98851. this._joystickPointerID = e.pointerId;
  98852. this._joystickPointerStartPos.x = e.clientX;
  98853. this._joystickPointerStartPos.y = e.clientY;
  98854. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  98855. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  98856. this._deltaJoystickVector.x = 0;
  98857. this._deltaJoystickVector.y = 0;
  98858. this.pressed = true;
  98859. this._touches.add(e.pointerId.toString(), e);
  98860. }
  98861. else {
  98862. // You can only trigger the action buttons with a joystick declared
  98863. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  98864. this._action();
  98865. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  98866. }
  98867. }
  98868. };
  98869. VirtualJoystick.prototype._onPointerMove = function (e) {
  98870. // If the current pointer is the one associated to the joystick (first touch contact)
  98871. if (this._joystickPointerID == e.pointerId) {
  98872. this._joystickPointerPos.x = e.clientX;
  98873. this._joystickPointerPos.y = e.clientY;
  98874. this._deltaJoystickVector = this._joystickPointerPos.clone();
  98875. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  98876. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  98877. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  98878. switch (this._axisTargetedByLeftAndRight) {
  98879. case JoystickAxis.X:
  98880. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  98881. break;
  98882. case JoystickAxis.Y:
  98883. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  98884. break;
  98885. case JoystickAxis.Z:
  98886. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  98887. break;
  98888. }
  98889. var directionUpDown = this.reverseUpDown ? 1 : -1;
  98890. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  98891. switch (this._axisTargetedByUpAndDown) {
  98892. case JoystickAxis.X:
  98893. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  98894. break;
  98895. case JoystickAxis.Y:
  98896. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  98897. break;
  98898. case JoystickAxis.Z:
  98899. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  98900. break;
  98901. }
  98902. }
  98903. else {
  98904. var data = this._touches.get(e.pointerId.toString());
  98905. if (data) {
  98906. data.x = e.clientX;
  98907. data.y = e.clientY;
  98908. }
  98909. }
  98910. };
  98911. VirtualJoystick.prototype._onPointerUp = function (e) {
  98912. if (this._joystickPointerID == e.pointerId) {
  98913. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  98914. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  98915. this._joystickPointerID = -1;
  98916. this.pressed = false;
  98917. }
  98918. else {
  98919. var touch = this._touches.get(e.pointerId.toString());
  98920. if (touch) {
  98921. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  98922. }
  98923. }
  98924. this._deltaJoystickVector.x = 0;
  98925. this._deltaJoystickVector.y = 0;
  98926. this._touches.remove(e.pointerId.toString());
  98927. };
  98928. /**
  98929. * Change the color of the virtual joystick
  98930. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  98931. */
  98932. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  98933. this._joystickColor = newColor;
  98934. };
  98935. /**
  98936. * Defines a callback to call when the joystick is touched
  98937. * @param action defines the callback
  98938. */
  98939. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  98940. this._action = action;
  98941. };
  98942. /**
  98943. * Defines which axis you'd like to control for left & right
  98944. * @param axis defines the axis to use
  98945. */
  98946. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  98947. switch (axis) {
  98948. case JoystickAxis.X:
  98949. case JoystickAxis.Y:
  98950. case JoystickAxis.Z:
  98951. this._axisTargetedByLeftAndRight = axis;
  98952. break;
  98953. default:
  98954. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  98955. break;
  98956. }
  98957. };
  98958. /**
  98959. * Defines which axis you'd like to control for up & down
  98960. * @param axis defines the axis to use
  98961. */
  98962. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  98963. switch (axis) {
  98964. case JoystickAxis.X:
  98965. case JoystickAxis.Y:
  98966. case JoystickAxis.Z:
  98967. this._axisTargetedByUpAndDown = axis;
  98968. break;
  98969. default:
  98970. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  98971. break;
  98972. }
  98973. };
  98974. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  98975. var _this = this;
  98976. if (this.pressed) {
  98977. this._touches.forEach(function (key, touch) {
  98978. if (touch.pointerId === _this._joystickPointerID) {
  98979. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  98980. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  98981. VirtualJoystick.vjCanvasContext.beginPath();
  98982. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  98983. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  98984. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  98985. VirtualJoystick.vjCanvasContext.stroke();
  98986. VirtualJoystick.vjCanvasContext.closePath();
  98987. VirtualJoystick.vjCanvasContext.beginPath();
  98988. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  98989. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  98990. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  98991. VirtualJoystick.vjCanvasContext.stroke();
  98992. VirtualJoystick.vjCanvasContext.closePath();
  98993. VirtualJoystick.vjCanvasContext.beginPath();
  98994. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  98995. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  98996. VirtualJoystick.vjCanvasContext.stroke();
  98997. VirtualJoystick.vjCanvasContext.closePath();
  98998. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  98999. }
  99000. else {
  99001. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  99002. VirtualJoystick.vjCanvasContext.beginPath();
  99003. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  99004. VirtualJoystick.vjCanvasContext.beginPath();
  99005. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  99006. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  99007. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  99008. VirtualJoystick.vjCanvasContext.stroke();
  99009. VirtualJoystick.vjCanvasContext.closePath();
  99010. touch.prevX = touch.x;
  99011. touch.prevY = touch.y;
  99012. }
  99013. ;
  99014. });
  99015. }
  99016. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  99017. };
  99018. /**
  99019. * Release internal HTML canvas
  99020. */
  99021. VirtualJoystick.prototype.releaseCanvas = function () {
  99022. if (VirtualJoystick.vjCanvas) {
  99023. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  99024. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  99025. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  99026. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  99027. window.removeEventListener("resize", this._onResize);
  99028. document.body.removeChild(VirtualJoystick.vjCanvas);
  99029. VirtualJoystick.vjCanvas = null;
  99030. }
  99031. };
  99032. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  99033. VirtualJoystick._globalJoystickIndex = 0;
  99034. return VirtualJoystick;
  99035. }());
  99036. BABYLON.VirtualJoystick = VirtualJoystick;
  99037. })(BABYLON || (BABYLON = {}));
  99038. //# sourceMappingURL=babylon.virtualJoystick.js.map
  99039. var BABYLON;
  99040. (function (BABYLON) {
  99041. BABYLON.Node.AddNodeConstructor("VirtualJoysticksCamera", function (name, scene) {
  99042. return function () { return new VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  99043. });
  99044. // We're mainly based on the logic defined into the FreeCamera code
  99045. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  99046. __extends(VirtualJoysticksCamera, _super);
  99047. function VirtualJoysticksCamera(name, position, scene) {
  99048. var _this = _super.call(this, name, position, scene) || this;
  99049. _this.inputs.addVirtualJoystick();
  99050. return _this;
  99051. }
  99052. VirtualJoysticksCamera.prototype.getClassName = function () {
  99053. return "VirtualJoysticksCamera";
  99054. };
  99055. return VirtualJoysticksCamera;
  99056. }(BABYLON.FreeCamera));
  99057. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  99058. })(BABYLON || (BABYLON = {}));
  99059. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  99060. var BABYLON;
  99061. (function (BABYLON) {
  99062. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  99063. function FreeCameraVirtualJoystickInput() {
  99064. }
  99065. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  99066. return this._leftjoystick;
  99067. };
  99068. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  99069. return this._rightjoystick;
  99070. };
  99071. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  99072. if (this._leftjoystick) {
  99073. var camera = this.camera;
  99074. var speed = camera._computeLocalCameraSpeed() * 50;
  99075. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  99076. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  99077. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  99078. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  99079. if (!this._leftjoystick.pressed) {
  99080. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  99081. }
  99082. if (!this._rightjoystick.pressed) {
  99083. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  99084. }
  99085. }
  99086. };
  99087. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  99088. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  99089. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  99090. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  99091. this._leftjoystick.setJoystickSensibility(0.15);
  99092. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  99093. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  99094. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  99095. this._rightjoystick.reverseUpDown = true;
  99096. this._rightjoystick.setJoystickSensibility(0.05);
  99097. this._rightjoystick.setJoystickColor("yellow");
  99098. };
  99099. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  99100. this._leftjoystick.releaseCanvas();
  99101. this._rightjoystick.releaseCanvas();
  99102. };
  99103. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  99104. return "FreeCameraVirtualJoystickInput";
  99105. };
  99106. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  99107. return "virtualJoystick";
  99108. };
  99109. return FreeCameraVirtualJoystickInput;
  99110. }());
  99111. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  99112. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  99113. })(BABYLON || (BABYLON = {}));
  99114. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  99115. var BABYLON;
  99116. (function (BABYLON) {
  99117. var SimplificationSettings = /** @class */ (function () {
  99118. function SimplificationSettings(quality, distance, optimizeMesh) {
  99119. this.quality = quality;
  99120. this.distance = distance;
  99121. this.optimizeMesh = optimizeMesh;
  99122. }
  99123. return SimplificationSettings;
  99124. }());
  99125. BABYLON.SimplificationSettings = SimplificationSettings;
  99126. var SimplificationQueue = /** @class */ (function () {
  99127. function SimplificationQueue() {
  99128. this.running = false;
  99129. this._simplificationArray = [];
  99130. }
  99131. SimplificationQueue.prototype.addTask = function (task) {
  99132. this._simplificationArray.push(task);
  99133. };
  99134. SimplificationQueue.prototype.executeNext = function () {
  99135. var task = this._simplificationArray.pop();
  99136. if (task) {
  99137. this.running = true;
  99138. this.runSimplification(task);
  99139. }
  99140. else {
  99141. this.running = false;
  99142. }
  99143. };
  99144. SimplificationQueue.prototype.runSimplification = function (task) {
  99145. var _this = this;
  99146. if (task.parallelProcessing) {
  99147. //parallel simplifier
  99148. task.settings.forEach(function (setting) {
  99149. var simplifier = _this.getSimplifier(task);
  99150. simplifier.simplify(setting, function (newMesh) {
  99151. task.mesh.addLODLevel(setting.distance, newMesh);
  99152. newMesh.isVisible = true;
  99153. //check if it is the last
  99154. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  99155. //all done, run the success callback.
  99156. task.successCallback();
  99157. }
  99158. _this.executeNext();
  99159. });
  99160. });
  99161. }
  99162. else {
  99163. //single simplifier.
  99164. var simplifier = this.getSimplifier(task);
  99165. var runDecimation = function (setting, callback) {
  99166. simplifier.simplify(setting, function (newMesh) {
  99167. task.mesh.addLODLevel(setting.distance, newMesh);
  99168. newMesh.isVisible = true;
  99169. //run the next quality level
  99170. callback();
  99171. });
  99172. };
  99173. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  99174. runDecimation(task.settings[loop.index], function () {
  99175. loop.executeNext();
  99176. });
  99177. }, function () {
  99178. //execution ended, run the success callback.
  99179. if (task.successCallback) {
  99180. task.successCallback();
  99181. }
  99182. _this.executeNext();
  99183. });
  99184. }
  99185. };
  99186. SimplificationQueue.prototype.getSimplifier = function (task) {
  99187. switch (task.simplificationType) {
  99188. case SimplificationType.QUADRATIC:
  99189. default:
  99190. return new QuadraticErrorSimplification(task.mesh);
  99191. }
  99192. };
  99193. return SimplificationQueue;
  99194. }());
  99195. BABYLON.SimplificationQueue = SimplificationQueue;
  99196. /**
  99197. * The implemented types of simplification
  99198. * At the moment only Quadratic Error Decimation is implemented
  99199. */
  99200. var SimplificationType;
  99201. (function (SimplificationType) {
  99202. /** Quadratic error decimation */
  99203. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  99204. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  99205. var DecimationTriangle = /** @class */ (function () {
  99206. function DecimationTriangle(vertices) {
  99207. this.vertices = vertices;
  99208. this.error = new Array(4);
  99209. this.deleted = false;
  99210. this.isDirty = false;
  99211. this.deletePending = false;
  99212. this.borderFactor = 0;
  99213. }
  99214. return DecimationTriangle;
  99215. }());
  99216. BABYLON.DecimationTriangle = DecimationTriangle;
  99217. var DecimationVertex = /** @class */ (function () {
  99218. function DecimationVertex(position, id) {
  99219. this.position = position;
  99220. this.id = id;
  99221. this.isBorder = true;
  99222. this.q = new QuadraticMatrix();
  99223. this.triangleCount = 0;
  99224. this.triangleStart = 0;
  99225. this.originalOffsets = [];
  99226. }
  99227. DecimationVertex.prototype.updatePosition = function (newPosition) {
  99228. this.position.copyFrom(newPosition);
  99229. };
  99230. return DecimationVertex;
  99231. }());
  99232. BABYLON.DecimationVertex = DecimationVertex;
  99233. var QuadraticMatrix = /** @class */ (function () {
  99234. function QuadraticMatrix(data) {
  99235. this.data = new Array(10);
  99236. for (var i = 0; i < 10; ++i) {
  99237. if (data && data[i]) {
  99238. this.data[i] = data[i];
  99239. }
  99240. else {
  99241. this.data[i] = 0;
  99242. }
  99243. }
  99244. }
  99245. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  99246. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  99247. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  99248. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  99249. return det;
  99250. };
  99251. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  99252. for (var i = 0; i < 10; ++i) {
  99253. this.data[i] += matrix.data[i];
  99254. }
  99255. };
  99256. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  99257. for (var i = 0; i < 10; ++i) {
  99258. this.data[i] += data[i];
  99259. }
  99260. };
  99261. QuadraticMatrix.prototype.add = function (matrix) {
  99262. var m = new QuadraticMatrix();
  99263. for (var i = 0; i < 10; ++i) {
  99264. m.data[i] = this.data[i] + matrix.data[i];
  99265. }
  99266. return m;
  99267. };
  99268. QuadraticMatrix.FromData = function (a, b, c, d) {
  99269. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  99270. };
  99271. //returning an array to avoid garbage collection
  99272. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  99273. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  99274. };
  99275. return QuadraticMatrix;
  99276. }());
  99277. BABYLON.QuadraticMatrix = QuadraticMatrix;
  99278. var Reference = /** @class */ (function () {
  99279. function Reference(vertexId, triangleId) {
  99280. this.vertexId = vertexId;
  99281. this.triangleId = triangleId;
  99282. }
  99283. return Reference;
  99284. }());
  99285. BABYLON.Reference = Reference;
  99286. /**
  99287. * An implementation of the Quadratic Error simplification algorithm.
  99288. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  99289. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  99290. * @author RaananW
  99291. */
  99292. var QuadraticErrorSimplification = /** @class */ (function () {
  99293. function QuadraticErrorSimplification(_mesh) {
  99294. this._mesh = _mesh;
  99295. this.syncIterations = 5000;
  99296. this.aggressiveness = 7;
  99297. this.decimationIterations = 100;
  99298. this.boundingBoxEpsilon = BABYLON.Epsilon;
  99299. }
  99300. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  99301. var _this = this;
  99302. this.initDecimatedMesh();
  99303. //iterating through the submeshes array, one after the other.
  99304. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  99305. _this.initWithMesh(loop.index, function () {
  99306. _this.runDecimation(settings, loop.index, function () {
  99307. loop.executeNext();
  99308. });
  99309. }, settings.optimizeMesh);
  99310. }, function () {
  99311. setTimeout(function () {
  99312. successCallback(_this._reconstructedMesh);
  99313. }, 0);
  99314. });
  99315. };
  99316. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  99317. var _this = this;
  99318. var targetCount = ~~(this.triangles.length * settings.quality);
  99319. var deletedTriangles = 0;
  99320. var triangleCount = this.triangles.length;
  99321. var iterationFunction = function (iteration, callback) {
  99322. setTimeout(function () {
  99323. if (iteration % 5 === 0) {
  99324. _this.updateMesh(iteration === 0);
  99325. }
  99326. for (var i = 0; i < _this.triangles.length; ++i) {
  99327. _this.triangles[i].isDirty = false;
  99328. }
  99329. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  99330. var trianglesIterator = function (i) {
  99331. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  99332. var t = _this.triangles[tIdx];
  99333. if (!t)
  99334. return;
  99335. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  99336. return;
  99337. }
  99338. for (var j = 0; j < 3; ++j) {
  99339. if (t.error[j] < threshold) {
  99340. var deleted0 = [];
  99341. var deleted1 = [];
  99342. var v0 = t.vertices[j];
  99343. var v1 = t.vertices[(j + 1) % 3];
  99344. if (v0.isBorder || v1.isBorder)
  99345. continue;
  99346. var p = BABYLON.Vector3.Zero();
  99347. var n = BABYLON.Vector3.Zero();
  99348. var uv = BABYLON.Vector2.Zero();
  99349. var color = new BABYLON.Color4(0, 0, 0, 1);
  99350. _this.calculateError(v0, v1, p, n, uv, color);
  99351. var delTr = new Array();
  99352. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  99353. continue;
  99354. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  99355. continue;
  99356. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  99357. continue;
  99358. var uniqueArray = new Array();
  99359. delTr.forEach(function (deletedT) {
  99360. if (uniqueArray.indexOf(deletedT) === -1) {
  99361. deletedT.deletePending = true;
  99362. uniqueArray.push(deletedT);
  99363. }
  99364. });
  99365. if (uniqueArray.length % 2 !== 0) {
  99366. continue;
  99367. }
  99368. v0.q = v1.q.add(v0.q);
  99369. v0.updatePosition(p);
  99370. var tStart = _this.references.length;
  99371. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  99372. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  99373. var tCount = _this.references.length - tStart;
  99374. if (tCount <= v0.triangleCount) {
  99375. if (tCount) {
  99376. for (var c = 0; c < tCount; c++) {
  99377. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  99378. }
  99379. }
  99380. }
  99381. else {
  99382. v0.triangleStart = tStart;
  99383. }
  99384. v0.triangleCount = tCount;
  99385. break;
  99386. }
  99387. }
  99388. };
  99389. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  99390. }, 0);
  99391. };
  99392. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  99393. if (triangleCount - deletedTriangles <= targetCount)
  99394. loop.breakLoop();
  99395. else {
  99396. iterationFunction(loop.index, function () {
  99397. loop.executeNext();
  99398. });
  99399. }
  99400. }, function () {
  99401. setTimeout(function () {
  99402. //reconstruct this part of the mesh
  99403. _this.reconstructMesh(submeshIndex);
  99404. successCallback();
  99405. }, 0);
  99406. });
  99407. };
  99408. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  99409. var _this = this;
  99410. this.vertices = [];
  99411. this.triangles = [];
  99412. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  99413. var indices = this._mesh.getIndices();
  99414. var submesh = this._mesh.subMeshes[submeshIndex];
  99415. var findInVertices = function (positionToSearch) {
  99416. if (optimizeMesh) {
  99417. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  99418. if (_this.vertices[ii].position.equals(positionToSearch)) {
  99419. return _this.vertices[ii];
  99420. }
  99421. }
  99422. }
  99423. return null;
  99424. };
  99425. var vertexReferences = [];
  99426. var vertexInit = function (i) {
  99427. if (!positionData) {
  99428. return;
  99429. }
  99430. var offset = i + submesh.verticesStart;
  99431. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  99432. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  99433. vertex.originalOffsets.push(offset);
  99434. if (vertex.id === _this.vertices.length) {
  99435. _this.vertices.push(vertex);
  99436. }
  99437. vertexReferences.push(vertex.id);
  99438. };
  99439. //var totalVertices = mesh.getTotalVertices();
  99440. var totalVertices = submesh.verticesCount;
  99441. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  99442. var indicesInit = function (i) {
  99443. if (!indices) {
  99444. return;
  99445. }
  99446. var offset = (submesh.indexStart / 3) + i;
  99447. var pos = (offset * 3);
  99448. var i0 = indices[pos + 0];
  99449. var i1 = indices[pos + 1];
  99450. var i2 = indices[pos + 2];
  99451. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  99452. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  99453. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  99454. var triangle = new DecimationTriangle([v0, v1, v2]);
  99455. triangle.originalOffset = pos;
  99456. _this.triangles.push(triangle);
  99457. };
  99458. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  99459. _this.init(callback);
  99460. });
  99461. });
  99462. };
  99463. QuadraticErrorSimplification.prototype.init = function (callback) {
  99464. var _this = this;
  99465. var triangleInit1 = function (i) {
  99466. var t = _this.triangles[i];
  99467. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  99468. for (var j = 0; j < 3; j++) {
  99469. 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))));
  99470. }
  99471. };
  99472. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  99473. var triangleInit2 = function (i) {
  99474. var t = _this.triangles[i];
  99475. for (var j = 0; j < 3; ++j) {
  99476. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  99477. }
  99478. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  99479. };
  99480. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  99481. callback();
  99482. });
  99483. });
  99484. };
  99485. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  99486. var newTriangles = [];
  99487. var i;
  99488. for (i = 0; i < this.vertices.length; ++i) {
  99489. this.vertices[i].triangleCount = 0;
  99490. }
  99491. var t;
  99492. var j;
  99493. for (i = 0; i < this.triangles.length; ++i) {
  99494. if (!this.triangles[i].deleted) {
  99495. t = this.triangles[i];
  99496. for (j = 0; j < 3; ++j) {
  99497. t.vertices[j].triangleCount = 1;
  99498. }
  99499. newTriangles.push(t);
  99500. }
  99501. }
  99502. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  99503. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  99504. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  99505. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  99506. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  99507. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  99508. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  99509. var vertexCount = 0;
  99510. for (i = 0; i < this.vertices.length; ++i) {
  99511. var vertex = this.vertices[i];
  99512. vertex.id = vertexCount;
  99513. if (vertex.triangleCount) {
  99514. vertex.originalOffsets.forEach(function (originalOffset) {
  99515. if (!normalData) {
  99516. return;
  99517. }
  99518. newPositionData.push(vertex.position.x);
  99519. newPositionData.push(vertex.position.y);
  99520. newPositionData.push(vertex.position.z);
  99521. newNormalData.push(normalData[originalOffset * 3]);
  99522. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  99523. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  99524. if (uvs && uvs.length) {
  99525. newUVsData.push(uvs[(originalOffset * 2)]);
  99526. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  99527. }
  99528. else if (colorsData && colorsData.length) {
  99529. newColorsData.push(colorsData[(originalOffset * 4)]);
  99530. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  99531. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  99532. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  99533. }
  99534. ++vertexCount;
  99535. });
  99536. }
  99537. }
  99538. var startingIndex = this._reconstructedMesh.getTotalIndices();
  99539. var startingVertex = this._reconstructedMesh.getTotalVertices();
  99540. var submeshesArray = this._reconstructedMesh.subMeshes;
  99541. this._reconstructedMesh.subMeshes = [];
  99542. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  99543. var originalIndices = this._mesh.getIndices();
  99544. for (i = 0; i < newTriangles.length; ++i) {
  99545. t = newTriangles[i]; //now get the new referencing point for each vertex
  99546. [0, 1, 2].forEach(function (idx) {
  99547. var id = originalIndices[t.originalOffset + idx];
  99548. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  99549. if (offset < 0)
  99550. offset = 0;
  99551. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  99552. });
  99553. }
  99554. //overwriting the old vertex buffers and indices.
  99555. this._reconstructedMesh.setIndices(newIndicesArray);
  99556. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  99557. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  99558. if (newUVsData.length > 0)
  99559. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  99560. if (newColorsData.length > 0)
  99561. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  99562. //create submesh
  99563. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  99564. if (submeshIndex > 0) {
  99565. this._reconstructedMesh.subMeshes = [];
  99566. submeshesArray.forEach(function (submesh) {
  99567. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  99568. });
  99569. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  99570. }
  99571. };
  99572. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  99573. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  99574. this._reconstructedMesh.material = this._mesh.material;
  99575. this._reconstructedMesh.parent = this._mesh.parent;
  99576. this._reconstructedMesh.isVisible = false;
  99577. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  99578. };
  99579. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  99580. for (var i = 0; i < vertex1.triangleCount; ++i) {
  99581. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  99582. if (t.deleted)
  99583. continue;
  99584. var s = this.references[vertex1.triangleStart + i].vertexId;
  99585. var v1 = t.vertices[(s + 1) % 3];
  99586. var v2 = t.vertices[(s + 2) % 3];
  99587. if ((v1 === vertex2 || v2 === vertex2)) {
  99588. deletedArray[i] = true;
  99589. delTr.push(t);
  99590. continue;
  99591. }
  99592. var d1 = v1.position.subtract(point);
  99593. d1 = d1.normalize();
  99594. var d2 = v2.position.subtract(point);
  99595. d2 = d2.normalize();
  99596. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  99597. return true;
  99598. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  99599. deletedArray[i] = false;
  99600. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  99601. return true;
  99602. }
  99603. return false;
  99604. };
  99605. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  99606. var newDeleted = deletedTriangles;
  99607. for (var i = 0; i < vertex.triangleCount; ++i) {
  99608. var ref = this.references[vertex.triangleStart + i];
  99609. var t = this.triangles[ref.triangleId];
  99610. if (t.deleted)
  99611. continue;
  99612. if (deletedArray[i] && t.deletePending) {
  99613. t.deleted = true;
  99614. newDeleted++;
  99615. continue;
  99616. }
  99617. t.vertices[ref.vertexId] = origVertex;
  99618. t.isDirty = true;
  99619. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  99620. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  99621. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  99622. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  99623. this.references.push(ref);
  99624. }
  99625. return newDeleted;
  99626. };
  99627. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  99628. for (var i = 0; i < this.vertices.length; ++i) {
  99629. var vCount = [];
  99630. var vId = [];
  99631. var v = this.vertices[i];
  99632. var j;
  99633. for (j = 0; j < v.triangleCount; ++j) {
  99634. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  99635. for (var ii = 0; ii < 3; ii++) {
  99636. var ofs = 0;
  99637. var vv = triangle.vertices[ii];
  99638. while (ofs < vCount.length) {
  99639. if (vId[ofs] === vv.id)
  99640. break;
  99641. ++ofs;
  99642. }
  99643. if (ofs === vCount.length) {
  99644. vCount.push(1);
  99645. vId.push(vv.id);
  99646. }
  99647. else {
  99648. vCount[ofs]++;
  99649. }
  99650. }
  99651. }
  99652. for (j = 0; j < vCount.length; ++j) {
  99653. if (vCount[j] === 1) {
  99654. this.vertices[vId[j]].isBorder = true;
  99655. }
  99656. else {
  99657. this.vertices[vId[j]].isBorder = false;
  99658. }
  99659. }
  99660. }
  99661. };
  99662. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  99663. if (identifyBorders === void 0) { identifyBorders = false; }
  99664. var i;
  99665. if (!identifyBorders) {
  99666. var newTrianglesVector = [];
  99667. for (i = 0; i < this.triangles.length; ++i) {
  99668. if (!this.triangles[i].deleted) {
  99669. newTrianglesVector.push(this.triangles[i]);
  99670. }
  99671. }
  99672. this.triangles = newTrianglesVector;
  99673. }
  99674. for (i = 0; i < this.vertices.length; ++i) {
  99675. this.vertices[i].triangleCount = 0;
  99676. this.vertices[i].triangleStart = 0;
  99677. }
  99678. var t;
  99679. var j;
  99680. var v;
  99681. for (i = 0; i < this.triangles.length; ++i) {
  99682. t = this.triangles[i];
  99683. for (j = 0; j < 3; ++j) {
  99684. v = t.vertices[j];
  99685. v.triangleCount++;
  99686. }
  99687. }
  99688. var tStart = 0;
  99689. for (i = 0; i < this.vertices.length; ++i) {
  99690. this.vertices[i].triangleStart = tStart;
  99691. tStart += this.vertices[i].triangleCount;
  99692. this.vertices[i].triangleCount = 0;
  99693. }
  99694. var newReferences = new Array(this.triangles.length * 3);
  99695. for (i = 0; i < this.triangles.length; ++i) {
  99696. t = this.triangles[i];
  99697. for (j = 0; j < 3; ++j) {
  99698. v = t.vertices[j];
  99699. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  99700. v.triangleCount++;
  99701. }
  99702. }
  99703. this.references = newReferences;
  99704. if (identifyBorders) {
  99705. this.identifyBorder();
  99706. }
  99707. };
  99708. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  99709. var x = point.x;
  99710. var y = point.y;
  99711. var z = point.z;
  99712. 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
  99713. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  99714. };
  99715. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  99716. var q = vertex1.q.add(vertex2.q);
  99717. var border = vertex1.isBorder && vertex2.isBorder;
  99718. var error = 0;
  99719. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  99720. if (qDet !== 0 && !border) {
  99721. if (!pointResult) {
  99722. pointResult = BABYLON.Vector3.Zero();
  99723. }
  99724. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  99725. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  99726. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  99727. error = this.vertexError(q, pointResult);
  99728. }
  99729. else {
  99730. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  99731. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  99732. var error1 = this.vertexError(q, vertex1.position);
  99733. var error2 = this.vertexError(q, vertex2.position);
  99734. var error3 = this.vertexError(q, p3);
  99735. error = Math.min(error1, error2, error3);
  99736. if (error === error1) {
  99737. if (pointResult) {
  99738. pointResult.copyFrom(vertex1.position);
  99739. }
  99740. }
  99741. else if (error === error2) {
  99742. if (pointResult) {
  99743. pointResult.copyFrom(vertex2.position);
  99744. }
  99745. }
  99746. else {
  99747. if (pointResult) {
  99748. pointResult.copyFrom(p3);
  99749. }
  99750. }
  99751. }
  99752. return error;
  99753. };
  99754. return QuadraticErrorSimplification;
  99755. }());
  99756. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  99757. })(BABYLON || (BABYLON = {}));
  99758. //# sourceMappingURL=babylon.meshSimplification.js.map
  99759. var BABYLON;
  99760. (function (BABYLON) {
  99761. Object.defineProperty(BABYLON.Scene.prototype, "simplificationQueue", {
  99762. get: function () {
  99763. if (!this._simplificationQueue) {
  99764. this._simplificationQueue = new BABYLON.SimplificationQueue();
  99765. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE);
  99766. if (!component) {
  99767. component = new SimplicationQueueSceneComponent(this);
  99768. this._addComponent(component);
  99769. }
  99770. }
  99771. return this._simplificationQueue;
  99772. },
  99773. set: function (value) {
  99774. this._simplificationQueue = value;
  99775. },
  99776. enumerable: true,
  99777. configurable: true
  99778. });
  99779. BABYLON.Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  99780. if (parallelProcessing === void 0) { parallelProcessing = true; }
  99781. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  99782. this.getScene().simplificationQueue.addTask({
  99783. settings: settings,
  99784. parallelProcessing: parallelProcessing,
  99785. mesh: this,
  99786. simplificationType: simplificationType,
  99787. successCallback: successCallback
  99788. });
  99789. return this;
  99790. };
  99791. /**
  99792. * Defines the simplification queue scene component responsible to help scheduling the various simplification task
  99793. * created in a scene
  99794. */
  99795. var SimplicationQueueSceneComponent = /** @class */ (function () {
  99796. /**
  99797. * Creates a new instance of the component for the given scene
  99798. * @param scene Defines the scene to register the component in
  99799. */
  99800. function SimplicationQueueSceneComponent(scene) {
  99801. /**
  99802. * The component name helpfull to identify the component in the list of scene components.
  99803. */
  99804. this.name = BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE;
  99805. this.scene = scene;
  99806. }
  99807. /**
  99808. * Registers the component in a given scene
  99809. */
  99810. SimplicationQueueSceneComponent.prototype.register = function () {
  99811. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE, this, this._beforeCameraUpdate);
  99812. };
  99813. /**
  99814. * Rebuilds the elements related to this component in case of
  99815. * context lost for instance.
  99816. */
  99817. SimplicationQueueSceneComponent.prototype.rebuild = function () {
  99818. // Nothing to do for this component
  99819. };
  99820. /**
  99821. * Disposes the component and the associated ressources
  99822. */
  99823. SimplicationQueueSceneComponent.prototype.dispose = function () {
  99824. // Nothing to do for this component
  99825. };
  99826. SimplicationQueueSceneComponent.prototype._beforeCameraUpdate = function () {
  99827. if (this.scene._simplificationQueue && !this.scene._simplificationQueue.running) {
  99828. this.scene._simplificationQueue.executeNext();
  99829. }
  99830. };
  99831. return SimplicationQueueSceneComponent;
  99832. }());
  99833. BABYLON.SimplicationQueueSceneComponent = SimplicationQueueSceneComponent;
  99834. })(BABYLON || (BABYLON = {}));
  99835. //# sourceMappingURL=babylon.meshSimplificationSceneComponent.js.map
  99836. var BABYLON;
  99837. (function (BABYLON) {
  99838. var MeshLODLevel = /** @class */ (function () {
  99839. function MeshLODLevel(distance, mesh) {
  99840. this.distance = distance;
  99841. this.mesh = mesh;
  99842. }
  99843. return MeshLODLevel;
  99844. }());
  99845. BABYLON.MeshLODLevel = MeshLODLevel;
  99846. })(BABYLON || (BABYLON = {}));
  99847. //# sourceMappingURL=babylon.meshLODLevel.js.map
  99848. var BABYLON;
  99849. (function (BABYLON) {
  99850. /**
  99851. * Defines the root class used to create scene optimization to use with SceneOptimizer
  99852. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  99853. */
  99854. var SceneOptimization = /** @class */ (function () {
  99855. /**
  99856. * Creates the SceneOptimization object
  99857. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  99858. * @param desc defines the description associated with the optimization
  99859. */
  99860. function SceneOptimization(
  99861. /**
  99862. * Defines the priority of this optimization (0 by default which means first in the list)
  99863. */
  99864. priority) {
  99865. if (priority === void 0) { priority = 0; }
  99866. this.priority = priority;
  99867. }
  99868. /**
  99869. * Gets a string describing the action executed by the current optimization
  99870. * @returns description string
  99871. */
  99872. SceneOptimization.prototype.getDescription = function () {
  99873. return "";
  99874. };
  99875. /**
  99876. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  99877. * @param scene defines the current scene where to apply this optimization
  99878. * @param optimizer defines the current optimizer
  99879. * @returns true if everything that can be done was applied
  99880. */
  99881. SceneOptimization.prototype.apply = function (scene, optimizer) {
  99882. return true;
  99883. };
  99884. ;
  99885. return SceneOptimization;
  99886. }());
  99887. BABYLON.SceneOptimization = SceneOptimization;
  99888. /**
  99889. * Defines an optimization used to reduce the size of render target textures
  99890. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  99891. */
  99892. var TextureOptimization = /** @class */ (function (_super) {
  99893. __extends(TextureOptimization, _super);
  99894. /**
  99895. * Creates the TextureOptimization object
  99896. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  99897. * @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
  99898. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  99899. */
  99900. function TextureOptimization(
  99901. /**
  99902. * Defines the priority of this optimization (0 by default which means first in the list)
  99903. */
  99904. priority,
  99905. /**
  99906. * 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
  99907. */
  99908. maximumSize,
  99909. /**
  99910. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  99911. */
  99912. step) {
  99913. if (priority === void 0) { priority = 0; }
  99914. if (maximumSize === void 0) { maximumSize = 1024; }
  99915. if (step === void 0) { step = 0.5; }
  99916. var _this = _super.call(this, priority) || this;
  99917. _this.priority = priority;
  99918. _this.maximumSize = maximumSize;
  99919. _this.step = step;
  99920. return _this;
  99921. }
  99922. /**
  99923. * Gets a string describing the action executed by the current optimization
  99924. * @returns description string
  99925. */
  99926. TextureOptimization.prototype.getDescription = function () {
  99927. return "Reducing render target texture size to " + this.maximumSize;
  99928. };
  99929. /**
  99930. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  99931. * @param scene defines the current scene where to apply this optimization
  99932. * @param optimizer defines the current optimizer
  99933. * @returns true if everything that can be done was applied
  99934. */
  99935. TextureOptimization.prototype.apply = function (scene, optimizer) {
  99936. var allDone = true;
  99937. for (var index = 0; index < scene.textures.length; index++) {
  99938. var texture = scene.textures[index];
  99939. if (!texture.canRescale || texture.getContext) {
  99940. continue;
  99941. }
  99942. var currentSize = texture.getSize();
  99943. var maxDimension = Math.max(currentSize.width, currentSize.height);
  99944. if (maxDimension > this.maximumSize) {
  99945. texture.scale(this.step);
  99946. allDone = false;
  99947. }
  99948. }
  99949. return allDone;
  99950. };
  99951. return TextureOptimization;
  99952. }(SceneOptimization));
  99953. BABYLON.TextureOptimization = TextureOptimization;
  99954. /**
  99955. * Defines an optimization used to increase or decrease the rendering resolution
  99956. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  99957. */
  99958. var HardwareScalingOptimization = /** @class */ (function (_super) {
  99959. __extends(HardwareScalingOptimization, _super);
  99960. /**
  99961. * Creates the HardwareScalingOptimization object
  99962. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  99963. * @param maximumScale defines the maximum scale to use (2 by default)
  99964. * @param step defines the step to use between two passes (0.5 by default)
  99965. */
  99966. function HardwareScalingOptimization(
  99967. /**
  99968. * Defines the priority of this optimization (0 by default which means first in the list)
  99969. */
  99970. priority,
  99971. /**
  99972. * Defines the maximum scale to use (2 by default)
  99973. */
  99974. maximumScale,
  99975. /**
  99976. * Defines the step to use between two passes (0.5 by default)
  99977. */
  99978. step) {
  99979. if (priority === void 0) { priority = 0; }
  99980. if (maximumScale === void 0) { maximumScale = 2; }
  99981. if (step === void 0) { step = 0.25; }
  99982. var _this = _super.call(this, priority) || this;
  99983. _this.priority = priority;
  99984. _this.maximumScale = maximumScale;
  99985. _this.step = step;
  99986. _this._currentScale = -1;
  99987. _this._directionOffset = 1;
  99988. return _this;
  99989. }
  99990. /**
  99991. * Gets a string describing the action executed by the current optimization
  99992. * @return description string
  99993. */
  99994. HardwareScalingOptimization.prototype.getDescription = function () {
  99995. return "Setting hardware scaling level to " + this._currentScale;
  99996. };
  99997. /**
  99998. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  99999. * @param scene defines the current scene where to apply this optimization
  100000. * @param optimizer defines the current optimizer
  100001. * @returns true if everything that can be done was applied
  100002. */
  100003. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  100004. if (this._currentScale === -1) {
  100005. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  100006. if (this._currentScale > this.maximumScale) {
  100007. this._directionOffset = -1;
  100008. }
  100009. }
  100010. this._currentScale += this._directionOffset * this.step;
  100011. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  100012. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  100013. };
  100014. ;
  100015. return HardwareScalingOptimization;
  100016. }(SceneOptimization));
  100017. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  100018. /**
  100019. * Defines an optimization used to remove shadows
  100020. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  100021. */
  100022. var ShadowsOptimization = /** @class */ (function (_super) {
  100023. __extends(ShadowsOptimization, _super);
  100024. function ShadowsOptimization() {
  100025. return _super !== null && _super.apply(this, arguments) || this;
  100026. }
  100027. /**
  100028. * Gets a string describing the action executed by the current optimization
  100029. * @return description string
  100030. */
  100031. ShadowsOptimization.prototype.getDescription = function () {
  100032. return "Turning shadows on/off";
  100033. };
  100034. /**
  100035. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  100036. * @param scene defines the current scene where to apply this optimization
  100037. * @param optimizer defines the current optimizer
  100038. * @returns true if everything that can be done was applied
  100039. */
  100040. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  100041. scene.shadowsEnabled = optimizer.isInImprovementMode;
  100042. return true;
  100043. };
  100044. ;
  100045. return ShadowsOptimization;
  100046. }(SceneOptimization));
  100047. BABYLON.ShadowsOptimization = ShadowsOptimization;
  100048. /**
  100049. * Defines an optimization used to turn post-processes off
  100050. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  100051. */
  100052. var PostProcessesOptimization = /** @class */ (function (_super) {
  100053. __extends(PostProcessesOptimization, _super);
  100054. function PostProcessesOptimization() {
  100055. return _super !== null && _super.apply(this, arguments) || this;
  100056. }
  100057. /**
  100058. * Gets a string describing the action executed by the current optimization
  100059. * @return description string
  100060. */
  100061. PostProcessesOptimization.prototype.getDescription = function () {
  100062. return "Turning post-processes on/off";
  100063. };
  100064. /**
  100065. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  100066. * @param scene defines the current scene where to apply this optimization
  100067. * @param optimizer defines the current optimizer
  100068. * @returns true if everything that can be done was applied
  100069. */
  100070. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  100071. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  100072. return true;
  100073. };
  100074. ;
  100075. return PostProcessesOptimization;
  100076. }(SceneOptimization));
  100077. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  100078. /**
  100079. * Defines an optimization used to turn lens flares off
  100080. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  100081. */
  100082. var LensFlaresOptimization = /** @class */ (function (_super) {
  100083. __extends(LensFlaresOptimization, _super);
  100084. function LensFlaresOptimization() {
  100085. return _super !== null && _super.apply(this, arguments) || this;
  100086. }
  100087. /**
  100088. * Gets a string describing the action executed by the current optimization
  100089. * @return description string
  100090. */
  100091. LensFlaresOptimization.prototype.getDescription = function () {
  100092. return "Turning lens flares on/off";
  100093. };
  100094. /**
  100095. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  100096. * @param scene defines the current scene where to apply this optimization
  100097. * @param optimizer defines the current optimizer
  100098. * @returns true if everything that can be done was applied
  100099. */
  100100. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  100101. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  100102. return true;
  100103. };
  100104. ;
  100105. return LensFlaresOptimization;
  100106. }(SceneOptimization));
  100107. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  100108. /**
  100109. * Defines an optimization based on user defined callback.
  100110. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  100111. */
  100112. var CustomOptimization = /** @class */ (function (_super) {
  100113. __extends(CustomOptimization, _super);
  100114. function CustomOptimization() {
  100115. return _super !== null && _super.apply(this, arguments) || this;
  100116. }
  100117. /**
  100118. * Gets a string describing the action executed by the current optimization
  100119. * @returns description string
  100120. */
  100121. CustomOptimization.prototype.getDescription = function () {
  100122. if (this.onGetDescription) {
  100123. return this.onGetDescription();
  100124. }
  100125. return "Running user defined callback";
  100126. };
  100127. /**
  100128. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  100129. * @param scene defines the current scene where to apply this optimization
  100130. * @param optimizer defines the current optimizer
  100131. * @returns true if everything that can be done was applied
  100132. */
  100133. CustomOptimization.prototype.apply = function (scene, optimizer) {
  100134. if (this.onApply) {
  100135. return this.onApply(scene, optimizer);
  100136. }
  100137. return true;
  100138. };
  100139. ;
  100140. return CustomOptimization;
  100141. }(SceneOptimization));
  100142. BABYLON.CustomOptimization = CustomOptimization;
  100143. /**
  100144. * Defines an optimization used to turn particles off
  100145. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  100146. */
  100147. var ParticlesOptimization = /** @class */ (function (_super) {
  100148. __extends(ParticlesOptimization, _super);
  100149. function ParticlesOptimization() {
  100150. return _super !== null && _super.apply(this, arguments) || this;
  100151. }
  100152. /**
  100153. * Gets a string describing the action executed by the current optimization
  100154. * @return description string
  100155. */
  100156. ParticlesOptimization.prototype.getDescription = function () {
  100157. return "Turning particles on/off";
  100158. };
  100159. /**
  100160. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  100161. * @param scene defines the current scene where to apply this optimization
  100162. * @param optimizer defines the current optimizer
  100163. * @returns true if everything that can be done was applied
  100164. */
  100165. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  100166. scene.particlesEnabled = optimizer.isInImprovementMode;
  100167. return true;
  100168. };
  100169. ;
  100170. return ParticlesOptimization;
  100171. }(SceneOptimization));
  100172. BABYLON.ParticlesOptimization = ParticlesOptimization;
  100173. /**
  100174. * Defines an optimization used to turn render targets off
  100175. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  100176. */
  100177. var RenderTargetsOptimization = /** @class */ (function (_super) {
  100178. __extends(RenderTargetsOptimization, _super);
  100179. function RenderTargetsOptimization() {
  100180. return _super !== null && _super.apply(this, arguments) || this;
  100181. }
  100182. /**
  100183. * Gets a string describing the action executed by the current optimization
  100184. * @return description string
  100185. */
  100186. RenderTargetsOptimization.prototype.getDescription = function () {
  100187. return "Turning render targets off";
  100188. };
  100189. /**
  100190. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  100191. * @param scene defines the current scene where to apply this optimization
  100192. * @param optimizer defines the current optimizer
  100193. * @returns true if everything that can be done was applied
  100194. */
  100195. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  100196. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  100197. return true;
  100198. };
  100199. ;
  100200. return RenderTargetsOptimization;
  100201. }(SceneOptimization));
  100202. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  100203. /**
  100204. * Defines an optimization used to merge meshes with compatible materials
  100205. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  100206. */
  100207. var MergeMeshesOptimization = /** @class */ (function (_super) {
  100208. __extends(MergeMeshesOptimization, _super);
  100209. function MergeMeshesOptimization() {
  100210. var _this = _super !== null && _super.apply(this, arguments) || this;
  100211. _this._canBeMerged = function (abstractMesh) {
  100212. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  100213. return false;
  100214. }
  100215. var mesh = abstractMesh;
  100216. if (mesh.isDisposed()) {
  100217. return false;
  100218. }
  100219. if (!mesh.isVisible || !mesh.isEnabled()) {
  100220. return false;
  100221. }
  100222. if (mesh.instances.length > 0) {
  100223. return false;
  100224. }
  100225. if (mesh.skeleton || mesh.hasLODLevels) {
  100226. return false;
  100227. }
  100228. return true;
  100229. };
  100230. return _this;
  100231. }
  100232. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  100233. /**
  100234. * Gets or sets a boolean which defines if optimization octree has to be updated
  100235. */
  100236. get: function () {
  100237. return MergeMeshesOptimization._UpdateSelectionTree;
  100238. },
  100239. /**
  100240. * Gets or sets a boolean which defines if optimization octree has to be updated
  100241. */
  100242. set: function (value) {
  100243. MergeMeshesOptimization._UpdateSelectionTree = value;
  100244. },
  100245. enumerable: true,
  100246. configurable: true
  100247. });
  100248. /**
  100249. * Gets a string describing the action executed by the current optimization
  100250. * @return description string
  100251. */
  100252. MergeMeshesOptimization.prototype.getDescription = function () {
  100253. return "Merging similar meshes together";
  100254. };
  100255. /**
  100256. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  100257. * @param scene defines the current scene where to apply this optimization
  100258. * @param optimizer defines the current optimizer
  100259. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  100260. * @returns true if everything that can be done was applied
  100261. */
  100262. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  100263. var globalPool = scene.meshes.slice(0);
  100264. var globalLength = globalPool.length;
  100265. for (var index = 0; index < globalLength; index++) {
  100266. var currentPool = new Array();
  100267. var current = globalPool[index];
  100268. // Checks
  100269. if (!this._canBeMerged(current)) {
  100270. continue;
  100271. }
  100272. currentPool.push(current);
  100273. // Find compatible meshes
  100274. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  100275. var otherMesh = globalPool[subIndex];
  100276. if (!this._canBeMerged(otherMesh)) {
  100277. continue;
  100278. }
  100279. if (otherMesh.material !== current.material) {
  100280. continue;
  100281. }
  100282. if (otherMesh.checkCollisions !== current.checkCollisions) {
  100283. continue;
  100284. }
  100285. currentPool.push(otherMesh);
  100286. globalLength--;
  100287. globalPool.splice(subIndex, 1);
  100288. subIndex--;
  100289. }
  100290. if (currentPool.length < 2) {
  100291. continue;
  100292. }
  100293. // Merge meshes
  100294. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  100295. }
  100296. // Call the octree system optimization if it is defined.
  100297. var sceneAsAny = scene;
  100298. if (sceneAsAny.createOrUpdateSelectionOctree) {
  100299. if (updateSelectionTree != undefined) {
  100300. if (updateSelectionTree) {
  100301. sceneAsAny.createOrUpdateSelectionOctree();
  100302. }
  100303. }
  100304. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  100305. sceneAsAny.createOrUpdateSelectionOctree();
  100306. }
  100307. }
  100308. return true;
  100309. };
  100310. ;
  100311. MergeMeshesOptimization._UpdateSelectionTree = false;
  100312. return MergeMeshesOptimization;
  100313. }(SceneOptimization));
  100314. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  100315. /**
  100316. * Defines a list of options used by SceneOptimizer
  100317. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  100318. */
  100319. var SceneOptimizerOptions = /** @class */ (function () {
  100320. /**
  100321. * Creates a new list of options used by SceneOptimizer
  100322. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  100323. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  100324. */
  100325. function SceneOptimizerOptions(
  100326. /**
  100327. * Defines the target frame rate to reach (60 by default)
  100328. */
  100329. targetFrameRate,
  100330. /**
  100331. * Defines the interval between two checkes (2000ms by default)
  100332. */
  100333. trackerDuration) {
  100334. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  100335. if (trackerDuration === void 0) { trackerDuration = 2000; }
  100336. this.targetFrameRate = targetFrameRate;
  100337. this.trackerDuration = trackerDuration;
  100338. /**
  100339. * Gets the list of optimizations to apply
  100340. */
  100341. this.optimizations = new Array();
  100342. }
  100343. /**
  100344. * Add a new optimization
  100345. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  100346. * @returns the current SceneOptimizerOptions
  100347. */
  100348. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  100349. this.optimizations.push(optimization);
  100350. return this;
  100351. };
  100352. /**
  100353. * Add a new custom optimization
  100354. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  100355. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  100356. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  100357. * @returns the current SceneOptimizerOptions
  100358. */
  100359. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  100360. if (priority === void 0) { priority = 0; }
  100361. var optimization = new CustomOptimization(priority);
  100362. optimization.onApply = onApply;
  100363. optimization.onGetDescription = onGetDescription;
  100364. this.optimizations.push(optimization);
  100365. return this;
  100366. };
  100367. /**
  100368. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  100369. * @param targetFrameRate defines the target frame rate (60 by default)
  100370. * @returns a SceneOptimizerOptions object
  100371. */
  100372. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  100373. var result = new SceneOptimizerOptions(targetFrameRate);
  100374. var priority = 0;
  100375. result.addOptimization(new MergeMeshesOptimization(priority));
  100376. result.addOptimization(new ShadowsOptimization(priority));
  100377. result.addOptimization(new LensFlaresOptimization(priority));
  100378. // Next priority
  100379. priority++;
  100380. result.addOptimization(new PostProcessesOptimization(priority));
  100381. result.addOptimization(new ParticlesOptimization(priority));
  100382. // Next priority
  100383. priority++;
  100384. result.addOptimization(new TextureOptimization(priority, 1024));
  100385. return result;
  100386. };
  100387. /**
  100388. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  100389. * @param targetFrameRate defines the target frame rate (60 by default)
  100390. * @returns a SceneOptimizerOptions object
  100391. */
  100392. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  100393. var result = new SceneOptimizerOptions(targetFrameRate);
  100394. var priority = 0;
  100395. result.addOptimization(new MergeMeshesOptimization(priority));
  100396. result.addOptimization(new ShadowsOptimization(priority));
  100397. result.addOptimization(new LensFlaresOptimization(priority));
  100398. // Next priority
  100399. priority++;
  100400. result.addOptimization(new PostProcessesOptimization(priority));
  100401. result.addOptimization(new ParticlesOptimization(priority));
  100402. // Next priority
  100403. priority++;
  100404. result.addOptimization(new TextureOptimization(priority, 512));
  100405. // Next priority
  100406. priority++;
  100407. result.addOptimization(new RenderTargetsOptimization(priority));
  100408. // Next priority
  100409. priority++;
  100410. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  100411. return result;
  100412. };
  100413. /**
  100414. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  100415. * @param targetFrameRate defines the target frame rate (60 by default)
  100416. * @returns a SceneOptimizerOptions object
  100417. */
  100418. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  100419. var result = new SceneOptimizerOptions(targetFrameRate);
  100420. var priority = 0;
  100421. result.addOptimization(new MergeMeshesOptimization(priority));
  100422. result.addOptimization(new ShadowsOptimization(priority));
  100423. result.addOptimization(new LensFlaresOptimization(priority));
  100424. // Next priority
  100425. priority++;
  100426. result.addOptimization(new PostProcessesOptimization(priority));
  100427. result.addOptimization(new ParticlesOptimization(priority));
  100428. // Next priority
  100429. priority++;
  100430. result.addOptimization(new TextureOptimization(priority, 256));
  100431. // Next priority
  100432. priority++;
  100433. result.addOptimization(new RenderTargetsOptimization(priority));
  100434. // Next priority
  100435. priority++;
  100436. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  100437. return result;
  100438. };
  100439. return SceneOptimizerOptions;
  100440. }());
  100441. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  100442. /**
  100443. * Class used to run optimizations in order to reach a target frame rate
  100444. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  100445. */
  100446. var SceneOptimizer = /** @class */ (function () {
  100447. /**
  100448. * Creates a new SceneOptimizer
  100449. * @param scene defines the scene to work on
  100450. * @param options defines the options to use with the SceneOptimizer
  100451. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  100452. * @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)
  100453. */
  100454. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  100455. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  100456. if (improvementMode === void 0) { improvementMode = false; }
  100457. var _this = this;
  100458. this._isRunning = false;
  100459. this._currentPriorityLevel = 0;
  100460. this._targetFrameRate = 60;
  100461. this._trackerDuration = 2000;
  100462. this._currentFrameRate = 0;
  100463. this._improvementMode = false;
  100464. /**
  100465. * Defines an observable called when the optimizer reaches the target frame rate
  100466. */
  100467. this.onSuccessObservable = new BABYLON.Observable();
  100468. /**
  100469. * Defines an observable called when the optimizer enables an optimization
  100470. */
  100471. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  100472. /**
  100473. * Defines an observable called when the optimizer is not able to reach the target frame rate
  100474. */
  100475. this.onFailureObservable = new BABYLON.Observable();
  100476. if (!options) {
  100477. this._options = new SceneOptimizerOptions();
  100478. }
  100479. else {
  100480. this._options = options;
  100481. }
  100482. if (this._options.targetFrameRate) {
  100483. this._targetFrameRate = this._options.targetFrameRate;
  100484. }
  100485. if (this._options.trackerDuration) {
  100486. this._trackerDuration = this._options.trackerDuration;
  100487. }
  100488. if (autoGeneratePriorities) {
  100489. var priority = 0;
  100490. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  100491. var optim = _a[_i];
  100492. optim.priority = priority++;
  100493. }
  100494. }
  100495. this._improvementMode = improvementMode;
  100496. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  100497. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  100498. _this._sceneDisposeObserver = null;
  100499. _this.dispose();
  100500. });
  100501. }
  100502. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  100503. /**
  100504. * Gets a boolean indicating if the optimizer is in improvement mode
  100505. */
  100506. get: function () {
  100507. return this._improvementMode;
  100508. },
  100509. enumerable: true,
  100510. configurable: true
  100511. });
  100512. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  100513. /**
  100514. * Gets the current priority level (0 at start)
  100515. */
  100516. get: function () {
  100517. return this._currentPriorityLevel;
  100518. },
  100519. enumerable: true,
  100520. configurable: true
  100521. });
  100522. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  100523. /**
  100524. * Gets the current frame rate checked by the SceneOptimizer
  100525. */
  100526. get: function () {
  100527. return this._currentFrameRate;
  100528. },
  100529. enumerable: true,
  100530. configurable: true
  100531. });
  100532. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  100533. /**
  100534. * Gets or sets the current target frame rate (60 by default)
  100535. */
  100536. get: function () {
  100537. return this._targetFrameRate;
  100538. },
  100539. /**
  100540. * Gets or sets the current target frame rate (60 by default)
  100541. */
  100542. set: function (value) {
  100543. this._targetFrameRate = value;
  100544. },
  100545. enumerable: true,
  100546. configurable: true
  100547. });
  100548. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  100549. /**
  100550. * Gets or sets the current interval between two checks (every 2000ms by default)
  100551. */
  100552. get: function () {
  100553. return this._trackerDuration;
  100554. },
  100555. /**
  100556. * Gets or sets the current interval between two checks (every 2000ms by default)
  100557. */
  100558. set: function (value) {
  100559. this._trackerDuration = value;
  100560. },
  100561. enumerable: true,
  100562. configurable: true
  100563. });
  100564. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  100565. /**
  100566. * Gets the list of active optimizations
  100567. */
  100568. get: function () {
  100569. return this._options.optimizations;
  100570. },
  100571. enumerable: true,
  100572. configurable: true
  100573. });
  100574. /**
  100575. * Stops the current optimizer
  100576. */
  100577. SceneOptimizer.prototype.stop = function () {
  100578. this._isRunning = false;
  100579. };
  100580. /**
  100581. * Reset the optimizer to initial step (current priority level = 0)
  100582. */
  100583. SceneOptimizer.prototype.reset = function () {
  100584. this._currentPriorityLevel = 0;
  100585. };
  100586. /**
  100587. * Start the optimizer. By default it will try to reach a specific framerate
  100588. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  100589. */
  100590. SceneOptimizer.prototype.start = function () {
  100591. var _this = this;
  100592. if (this._isRunning) {
  100593. return;
  100594. }
  100595. this._isRunning = true;
  100596. // Let's wait for the scene to be ready before running our check
  100597. this._scene.executeWhenReady(function () {
  100598. setTimeout(function () {
  100599. _this._checkCurrentState();
  100600. }, _this._trackerDuration);
  100601. });
  100602. };
  100603. SceneOptimizer.prototype._checkCurrentState = function () {
  100604. var _this = this;
  100605. if (!this._isRunning) {
  100606. return;
  100607. }
  100608. var scene = this._scene;
  100609. var options = this._options;
  100610. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  100611. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  100612. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  100613. this._isRunning = false;
  100614. this.onSuccessObservable.notifyObservers(this);
  100615. return;
  100616. }
  100617. // Apply current level of optimizations
  100618. var allDone = true;
  100619. var noOptimizationApplied = true;
  100620. for (var index = 0; index < options.optimizations.length; index++) {
  100621. var optimization = options.optimizations[index];
  100622. if (optimization.priority === this._currentPriorityLevel) {
  100623. noOptimizationApplied = false;
  100624. allDone = allDone && optimization.apply(scene, this);
  100625. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  100626. }
  100627. }
  100628. // If no optimization was applied, this is a failure :(
  100629. if (noOptimizationApplied) {
  100630. this._isRunning = false;
  100631. this.onFailureObservable.notifyObservers(this);
  100632. return;
  100633. }
  100634. // If all optimizations were done, move to next level
  100635. if (allDone) {
  100636. this._currentPriorityLevel++;
  100637. }
  100638. // Let's the system running for a specific amount of time before checking FPS
  100639. scene.executeWhenReady(function () {
  100640. setTimeout(function () {
  100641. _this._checkCurrentState();
  100642. }, _this._trackerDuration);
  100643. });
  100644. };
  100645. /**
  100646. * Release all resources
  100647. */
  100648. SceneOptimizer.prototype.dispose = function () {
  100649. this.stop();
  100650. this.onSuccessObservable.clear();
  100651. this.onFailureObservable.clear();
  100652. this.onNewOptimizationAppliedObservable.clear();
  100653. if (this._sceneDisposeObserver) {
  100654. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  100655. }
  100656. };
  100657. /**
  100658. * Helper function to create a SceneOptimizer with one single line of code
  100659. * @param scene defines the scene to work on
  100660. * @param options defines the options to use with the SceneOptimizer
  100661. * @param onSuccess defines a callback to call on success
  100662. * @param onFailure defines a callback to call on failure
  100663. * @returns the new SceneOptimizer object
  100664. */
  100665. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  100666. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  100667. if (onSuccess) {
  100668. optimizer.onSuccessObservable.add(function () {
  100669. onSuccess();
  100670. });
  100671. }
  100672. if (onFailure) {
  100673. optimizer.onFailureObservable.add(function () {
  100674. onFailure();
  100675. });
  100676. }
  100677. optimizer.start();
  100678. return optimizer;
  100679. };
  100680. return SceneOptimizer;
  100681. }());
  100682. BABYLON.SceneOptimizer = SceneOptimizer;
  100683. })(BABYLON || (BABYLON = {}));
  100684. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  100685. var BABYLON;
  100686. (function (BABYLON) {
  100687. /**
  100688. * Gets the outline renderer associated with the scene
  100689. * @returns a OutlineRenderer
  100690. */
  100691. BABYLON.Scene.prototype.getOutlineRenderer = function () {
  100692. if (!this._outlineRenderer) {
  100693. this._outlineRenderer = new OutlineRenderer(this);
  100694. }
  100695. return this._outlineRenderer;
  100696. };
  100697. Object.defineProperty(BABYLON.AbstractMesh.prototype, "renderOutline", {
  100698. get: function () {
  100699. return this._renderOutline;
  100700. },
  100701. set: function (value) {
  100702. if (value) {
  100703. // Lazy Load the component.
  100704. this.getScene().getOutlineRenderer();
  100705. }
  100706. this._renderOutline = value;
  100707. },
  100708. enumerable: true,
  100709. configurable: true
  100710. });
  100711. Object.defineProperty(BABYLON.AbstractMesh.prototype, "renderOverlay", {
  100712. get: function () {
  100713. return this._renderOverlay;
  100714. },
  100715. set: function (value) {
  100716. if (value) {
  100717. // Lazy Load the component.
  100718. this.getScene().getOutlineRenderer();
  100719. }
  100720. this._renderOverlay = value;
  100721. },
  100722. enumerable: true,
  100723. configurable: true
  100724. });
  100725. /**
  100726. * This class is responsible to draw bothe outline/overlay of meshes.
  100727. * It should not be used directly but through the available method on mesh.
  100728. */
  100729. var OutlineRenderer = /** @class */ (function () {
  100730. /**
  100731. * Instantiates a new outline renderer. (There could be only one per scene).
  100732. * @param scene Defines the scene it belongs to
  100733. */
  100734. function OutlineRenderer(scene) {
  100735. /**
  100736. * The name of the component. Each component must have a unique name.
  100737. */
  100738. this.name = BABYLON.SceneComponentConstants.NAME_OUTLINERENDERER;
  100739. /**
  100740. * Defines a zOffset to prevent zFighting between the overlay and the mesh.
  100741. */
  100742. this.zOffset = 1;
  100743. this.scene = scene;
  100744. this._engine = scene.getEngine();
  100745. this.scene._addComponent(this);
  100746. }
  100747. /**
  100748. * Register the component to one instance of a scene.
  100749. */
  100750. OutlineRenderer.prototype.register = function () {
  100751. this.scene._beforeRenderingMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE, this, this._beforeRenderingMesh);
  100752. this.scene._afterRenderingMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE, this, this._afterRenderingMesh);
  100753. };
  100754. /**
  100755. * Rebuilds the elements related to this component in case of
  100756. * context lost for instance.
  100757. */
  100758. OutlineRenderer.prototype.rebuild = function () {
  100759. // Nothing to do here.
  100760. };
  100761. /**
  100762. * Disposes the component and the associated ressources.
  100763. */
  100764. OutlineRenderer.prototype.dispose = function () {
  100765. // Nothing to do here.
  100766. };
  100767. /**
  100768. * Renders the outline in the canvas.
  100769. * @param subMesh Defines the sumesh to render
  100770. * @param batch Defines the batch of meshes in case of instances
  100771. * @param useOverlay Defines if the rendering is for the overlay or the outline
  100772. */
  100773. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  100774. var _this = this;
  100775. if (useOverlay === void 0) { useOverlay = false; }
  100776. var scene = this.scene;
  100777. var engine = scene.getEngine();
  100778. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  100779. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  100780. return;
  100781. }
  100782. var mesh = subMesh.getRenderingMesh();
  100783. var material = subMesh.getMaterial();
  100784. if (!material || !scene.activeCamera) {
  100785. return;
  100786. }
  100787. engine.enableEffect(this._effect);
  100788. // Logarithmic depth
  100789. if (material.useLogarithmicDepth) {
  100790. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  100791. }
  100792. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  100793. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  100794. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  100795. // Bones
  100796. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  100797. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  100798. }
  100799. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  100800. // Alpha test
  100801. if (material && material.needAlphaTesting()) {
  100802. var alphaTexture = material.getAlphaTestTexture();
  100803. if (alphaTexture) {
  100804. this._effect.setTexture("diffuseSampler", alphaTexture);
  100805. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  100806. }
  100807. }
  100808. engine.setZOffset(-this.zOffset);
  100809. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  100810. engine.setZOffset(0);
  100811. };
  100812. /**
  100813. * Returns whether or not the outline renderer is ready for a given submesh.
  100814. * All the dependencies e.g. submeshes, texture, effect... mus be ready
  100815. * @param subMesh Defines the submesh to check readyness for
  100816. * @param useInstances Defines wheter wee are trying to render instances or not
  100817. * @returns true if ready otherwise false
  100818. */
  100819. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  100820. var defines = [];
  100821. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  100822. var mesh = subMesh.getMesh();
  100823. var material = subMesh.getMaterial();
  100824. if (material) {
  100825. // Alpha test
  100826. if (material.needAlphaTesting()) {
  100827. defines.push("#define ALPHATEST");
  100828. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  100829. attribs.push(BABYLON.VertexBuffer.UVKind);
  100830. defines.push("#define UV1");
  100831. }
  100832. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  100833. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  100834. defines.push("#define UV2");
  100835. }
  100836. }
  100837. //Logarithmic depth
  100838. if (material.useLogarithmicDepth) {
  100839. defines.push("#define LOGARITHMICDEPTH");
  100840. }
  100841. }
  100842. // Bones
  100843. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  100844. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  100845. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  100846. if (mesh.numBoneInfluencers > 4) {
  100847. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  100848. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  100849. }
  100850. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  100851. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  100852. }
  100853. else {
  100854. defines.push("#define NUM_BONE_INFLUENCERS 0");
  100855. }
  100856. // Instances
  100857. if (useInstances) {
  100858. defines.push("#define INSTANCES");
  100859. attribs.push("world0");
  100860. attribs.push("world1");
  100861. attribs.push("world2");
  100862. attribs.push("world3");
  100863. }
  100864. // Get correct effect
  100865. var join = defines.join("\n");
  100866. if (this._cachedDefines !== join) {
  100867. this._cachedDefines = join;
  100868. this._effect = this.scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  100869. }
  100870. return this._effect.isReady();
  100871. };
  100872. OutlineRenderer.prototype._beforeRenderingMesh = function (mesh, subMesh, batch) {
  100873. // Outline - step 1
  100874. this._savedDepthWrite = this._engine.getDepthWrite();
  100875. if (mesh.renderOutline) {
  100876. this._engine.setDepthWrite(false);
  100877. this.render(subMesh, batch);
  100878. this._engine.setDepthWrite(this._savedDepthWrite);
  100879. }
  100880. };
  100881. OutlineRenderer.prototype._afterRenderingMesh = function (mesh, subMesh, batch) {
  100882. // Outline - step 2
  100883. if (mesh.renderOutline && this._savedDepthWrite) {
  100884. this._engine.setDepthWrite(true);
  100885. this._engine.setColorWrite(false);
  100886. this.render(subMesh, batch);
  100887. this._engine.setColorWrite(true);
  100888. }
  100889. // Overlay
  100890. if (mesh.renderOverlay) {
  100891. var currentMode = this._engine.getAlphaMode();
  100892. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  100893. this.render(subMesh, batch, true);
  100894. this._engine.setAlphaMode(currentMode);
  100895. }
  100896. };
  100897. return OutlineRenderer;
  100898. }());
  100899. BABYLON.OutlineRenderer = OutlineRenderer;
  100900. })(BABYLON || (BABYLON = {}));
  100901. //# sourceMappingURL=babylon.outlineRenderer.js.map
  100902. var BABYLON;
  100903. (function (BABYLON) {
  100904. BABYLON.AbstractMesh.prototype.disableEdgesRendering = function () {
  100905. if (this._edgesRenderer) {
  100906. this._edgesRenderer.dispose();
  100907. this._edgesRenderer = null;
  100908. }
  100909. return this;
  100910. };
  100911. BABYLON.AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  100912. if (epsilon === void 0) { epsilon = 0.95; }
  100913. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  100914. this.disableEdgesRendering();
  100915. this._edgesRenderer = new EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  100916. return this;
  100917. };
  100918. Object.defineProperty(BABYLON.AbstractMesh.prototype, "edgesRenderer", {
  100919. get: function () {
  100920. return this._edgesRenderer;
  100921. },
  100922. enumerable: true,
  100923. configurable: true
  100924. });
  100925. BABYLON.LinesMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  100926. if (epsilon === void 0) { epsilon = 0.95; }
  100927. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  100928. this.disableEdgesRendering();
  100929. this._edgesRenderer = new BABYLON.LineEdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  100930. return this;
  100931. };
  100932. /**
  100933. * FaceAdjacencies Helper class to generate edges
  100934. */
  100935. var FaceAdjacencies = /** @class */ (function () {
  100936. function FaceAdjacencies() {
  100937. this.edges = new Array();
  100938. this.edgesConnectedCount = 0;
  100939. }
  100940. return FaceAdjacencies;
  100941. }());
  100942. /**
  100943. * This class is used to generate edges of the mesh that could then easily be rendered in a scene.
  100944. */
  100945. var EdgesRenderer = /** @class */ (function () {
  100946. /**
  100947. * Creates an instance of the EdgesRenderer. It is primarily use to display edges of a mesh.
  100948. * Beware when you use this class with complex objects as the adjacencies computation can be really long
  100949. * @param source Mesh used to create edges
  100950. * @param epsilon sum of angles in adjacency to check for edge
  100951. * @param checkVerticesInsteadOfIndices
  100952. * @param generateEdgesLines - should generate Lines or only prepare resources.
  100953. */
  100954. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices, generateEdgesLines) {
  100955. if (epsilon === void 0) { epsilon = 0.95; }
  100956. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  100957. if (generateEdgesLines === void 0) { generateEdgesLines = true; }
  100958. var _this = this;
  100959. this.edgesWidthScalerForOrthographic = 1000.0;
  100960. this.edgesWidthScalerForPerspective = 50.0;
  100961. this._linesPositions = new Array();
  100962. this._linesNormals = new Array();
  100963. this._linesIndices = new Array();
  100964. this._buffers = {};
  100965. this._checkVerticesInsteadOfIndices = false;
  100966. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  100967. this.isEnabled = true;
  100968. this._source = source;
  100969. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  100970. this._epsilon = epsilon;
  100971. this._prepareRessources();
  100972. if (generateEdgesLines) {
  100973. this._generateEdgesLines();
  100974. }
  100975. this._meshRebuildObserver = this._source.onRebuildObservable.add(function () {
  100976. _this._rebuild();
  100977. });
  100978. this._meshDisposeObserver = this._source.onDisposeObservable.add(function () {
  100979. _this.dispose();
  100980. });
  100981. }
  100982. EdgesRenderer.prototype._prepareRessources = function () {
  100983. if (this._lineShader) {
  100984. return;
  100985. }
  100986. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  100987. attributes: ["position", "normal"],
  100988. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  100989. });
  100990. this._lineShader.disableDepthWrite = true;
  100991. this._lineShader.backFaceCulling = false;
  100992. };
  100993. /** @hidden */
  100994. EdgesRenderer.prototype._rebuild = function () {
  100995. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  100996. if (buffer) {
  100997. buffer._rebuild();
  100998. }
  100999. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  101000. if (buffer) {
  101001. buffer._rebuild();
  101002. }
  101003. var scene = this._source.getScene();
  101004. var engine = scene.getEngine();
  101005. this._ib = engine.createIndexBuffer(this._linesIndices);
  101006. };
  101007. /**
  101008. * Releases the required resources for the edges renderer
  101009. */
  101010. EdgesRenderer.prototype.dispose = function () {
  101011. this._source.onRebuildObservable.remove(this._meshRebuildObserver);
  101012. this._source.onDisposeObservable.remove(this._meshDisposeObserver);
  101013. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  101014. if (buffer) {
  101015. buffer.dispose();
  101016. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  101017. }
  101018. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  101019. if (buffer) {
  101020. buffer.dispose();
  101021. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  101022. }
  101023. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  101024. this._lineShader.dispose();
  101025. };
  101026. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  101027. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  101028. return 0;
  101029. }
  101030. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  101031. return 1;
  101032. }
  101033. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  101034. return 2;
  101035. }
  101036. return -1;
  101037. };
  101038. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  101039. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  101040. return 0;
  101041. }
  101042. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  101043. return 1;
  101044. }
  101045. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  101046. return 2;
  101047. }
  101048. return -1;
  101049. };
  101050. /**
  101051. * Checks if the pair of p0 and p1 is en edge
  101052. * @param faceIndex
  101053. * @param edge
  101054. * @param faceNormals
  101055. * @param p0
  101056. * @param p1
  101057. * @private
  101058. */
  101059. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  101060. var needToCreateLine;
  101061. if (edge === undefined) {
  101062. needToCreateLine = true;
  101063. }
  101064. else {
  101065. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  101066. needToCreateLine = dotProduct < this._epsilon;
  101067. }
  101068. if (needToCreateLine) {
  101069. var offset = this._linesPositions.length / 3;
  101070. var normal = p0.subtract(p1);
  101071. normal.normalize();
  101072. // Positions
  101073. this._linesPositions.push(p0.x);
  101074. this._linesPositions.push(p0.y);
  101075. this._linesPositions.push(p0.z);
  101076. this._linesPositions.push(p0.x);
  101077. this._linesPositions.push(p0.y);
  101078. this._linesPositions.push(p0.z);
  101079. this._linesPositions.push(p1.x);
  101080. this._linesPositions.push(p1.y);
  101081. this._linesPositions.push(p1.z);
  101082. this._linesPositions.push(p1.x);
  101083. this._linesPositions.push(p1.y);
  101084. this._linesPositions.push(p1.z);
  101085. // Normals
  101086. this._linesNormals.push(p1.x);
  101087. this._linesNormals.push(p1.y);
  101088. this._linesNormals.push(p1.z);
  101089. this._linesNormals.push(-1);
  101090. this._linesNormals.push(p1.x);
  101091. this._linesNormals.push(p1.y);
  101092. this._linesNormals.push(p1.z);
  101093. this._linesNormals.push(1);
  101094. this._linesNormals.push(p0.x);
  101095. this._linesNormals.push(p0.y);
  101096. this._linesNormals.push(p0.z);
  101097. this._linesNormals.push(-1);
  101098. this._linesNormals.push(p0.x);
  101099. this._linesNormals.push(p0.y);
  101100. this._linesNormals.push(p0.z);
  101101. this._linesNormals.push(1);
  101102. // Indices
  101103. this._linesIndices.push(offset);
  101104. this._linesIndices.push(offset + 1);
  101105. this._linesIndices.push(offset + 2);
  101106. this._linesIndices.push(offset);
  101107. this._linesIndices.push(offset + 2);
  101108. this._linesIndices.push(offset + 3);
  101109. }
  101110. };
  101111. /**
  101112. * Generates lines edges from adjacencjes
  101113. * @private
  101114. */
  101115. EdgesRenderer.prototype._generateEdgesLines = function () {
  101116. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  101117. var indices = this._source.getIndices();
  101118. if (!indices || !positions) {
  101119. return;
  101120. }
  101121. // First let's find adjacencies
  101122. var adjacencies = new Array();
  101123. var faceNormals = new Array();
  101124. var index;
  101125. var faceAdjacencies;
  101126. // Prepare faces
  101127. for (index = 0; index < indices.length; index += 3) {
  101128. faceAdjacencies = new FaceAdjacencies();
  101129. var p0Index = indices[index];
  101130. var p1Index = indices[index + 1];
  101131. var p2Index = indices[index + 2];
  101132. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  101133. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  101134. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  101135. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  101136. faceNormal.normalize();
  101137. faceNormals.push(faceNormal);
  101138. adjacencies.push(faceAdjacencies);
  101139. }
  101140. // Scan
  101141. for (index = 0; index < adjacencies.length; index++) {
  101142. faceAdjacencies = adjacencies[index];
  101143. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  101144. var otherFaceAdjacencies = adjacencies[otherIndex];
  101145. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  101146. break;
  101147. }
  101148. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  101149. continue;
  101150. }
  101151. var otherP0 = indices[otherIndex * 3];
  101152. var otherP1 = indices[otherIndex * 3 + 1];
  101153. var otherP2 = indices[otherIndex * 3 + 2];
  101154. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  101155. var otherEdgeIndex = 0;
  101156. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  101157. continue;
  101158. }
  101159. switch (edgeIndex) {
  101160. case 0:
  101161. if (this._checkVerticesInsteadOfIndices) {
  101162. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  101163. }
  101164. else {
  101165. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  101166. }
  101167. break;
  101168. case 1:
  101169. if (this._checkVerticesInsteadOfIndices) {
  101170. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  101171. }
  101172. else {
  101173. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  101174. }
  101175. break;
  101176. case 2:
  101177. if (this._checkVerticesInsteadOfIndices) {
  101178. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  101179. }
  101180. else {
  101181. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  101182. }
  101183. break;
  101184. }
  101185. if (otherEdgeIndex === -1) {
  101186. continue;
  101187. }
  101188. faceAdjacencies.edges[edgeIndex] = otherIndex;
  101189. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  101190. faceAdjacencies.edgesConnectedCount++;
  101191. otherFaceAdjacencies.edgesConnectedCount++;
  101192. if (faceAdjacencies.edgesConnectedCount === 3) {
  101193. break;
  101194. }
  101195. }
  101196. }
  101197. }
  101198. // Create lines
  101199. for (index = 0; index < adjacencies.length; index++) {
  101200. // 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
  101201. var current = adjacencies[index];
  101202. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  101203. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  101204. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  101205. }
  101206. // Merge into a single mesh
  101207. var engine = this._source.getScene().getEngine();
  101208. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  101209. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  101210. this._ib = engine.createIndexBuffer(this._linesIndices);
  101211. this._indicesCount = this._linesIndices.length;
  101212. };
  101213. /**
  101214. * Checks wether or not the edges renderer is ready to render.
  101215. * @return true if ready, otherwise false.
  101216. */
  101217. EdgesRenderer.prototype.isReady = function () {
  101218. return this._lineShader.isReady();
  101219. };
  101220. /**
  101221. * Renders the edges of the attached mesh,
  101222. */
  101223. EdgesRenderer.prototype.render = function () {
  101224. var scene = this._source.getScene();
  101225. if (!this.isReady() || !scene.activeCamera) {
  101226. return;
  101227. }
  101228. var engine = scene.getEngine();
  101229. this._lineShader._preBind();
  101230. if (this._source.edgesColor.a !== 1) {
  101231. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  101232. }
  101233. else {
  101234. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  101235. }
  101236. // VBOs
  101237. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  101238. scene.resetCachedMaterial();
  101239. this._lineShader.setColor4("color", this._source.edgesColor);
  101240. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  101241. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  101242. }
  101243. else {
  101244. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  101245. }
  101246. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  101247. this._lineShader.bind(this._source.getWorldMatrix());
  101248. // Draw order
  101249. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  101250. this._lineShader.unbind();
  101251. };
  101252. return EdgesRenderer;
  101253. }());
  101254. BABYLON.EdgesRenderer = EdgesRenderer;
  101255. })(BABYLON || (BABYLON = {}));
  101256. //# sourceMappingURL=babylon.edgesRenderer.js.map
  101257. var BABYLON;
  101258. (function (BABYLON) {
  101259. /**
  101260. * FaceAdjacencies Helper class to generate edges
  101261. */
  101262. var FaceAdjacencies = /** @class */ (function () {
  101263. function FaceAdjacencies() {
  101264. this.edges = new Array();
  101265. this.edgesConnectedCount = 0;
  101266. }
  101267. return FaceAdjacencies;
  101268. }());
  101269. /**
  101270. * LineEdgesRenderer for LineMeshes to remove unnecessary triangulation
  101271. */
  101272. var LineEdgesRenderer = /** @class */ (function (_super) {
  101273. __extends(LineEdgesRenderer, _super);
  101274. /**
  101275. * This constructor turns off auto generating edges line in Edges Renderer to make it here.
  101276. * @param source LineMesh used to generate edges
  101277. * @param epsilon not important (specified angle for edge detection)
  101278. * @param checkVerticesInsteadOfIndices not important for LineMesh
  101279. */
  101280. function LineEdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  101281. if (epsilon === void 0) { epsilon = 0.95; }
  101282. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  101283. var _this = _super.call(this, source, epsilon, checkVerticesInsteadOfIndices, false) || this;
  101284. _this._generateEdgesLines();
  101285. return _this;
  101286. }
  101287. /**
  101288. * Always create the edge since its a line so only important things are p0 and p1
  101289. * @param faceIndex not important for LineMesh
  101290. * @param edge not important for LineMesh
  101291. * @param faceNormals not important for LineMesh
  101292. * @param p0 beginnig of line
  101293. * @param p1 end of line
  101294. */
  101295. LineEdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  101296. var offset = this._linesPositions.length / 3;
  101297. var normal = p0.subtract(p1);
  101298. normal.normalize();
  101299. // Positions
  101300. this._linesPositions.push(p0.x);
  101301. this._linesPositions.push(p0.y);
  101302. this._linesPositions.push(p0.z);
  101303. this._linesPositions.push(p0.x);
  101304. this._linesPositions.push(p0.y);
  101305. this._linesPositions.push(p0.z);
  101306. this._linesPositions.push(p1.x);
  101307. this._linesPositions.push(p1.y);
  101308. this._linesPositions.push(p1.z);
  101309. this._linesPositions.push(p1.x);
  101310. this._linesPositions.push(p1.y);
  101311. this._linesPositions.push(p1.z);
  101312. // Normals
  101313. this._linesNormals.push(p1.x);
  101314. this._linesNormals.push(p1.y);
  101315. this._linesNormals.push(p1.z);
  101316. this._linesNormals.push(-1);
  101317. this._linesNormals.push(p1.x);
  101318. this._linesNormals.push(p1.y);
  101319. this._linesNormals.push(p1.z);
  101320. this._linesNormals.push(1);
  101321. this._linesNormals.push(p0.x);
  101322. this._linesNormals.push(p0.y);
  101323. this._linesNormals.push(p0.z);
  101324. this._linesNormals.push(-1);
  101325. this._linesNormals.push(p0.x);
  101326. this._linesNormals.push(p0.y);
  101327. this._linesNormals.push(p0.z);
  101328. this._linesNormals.push(1);
  101329. // Indices
  101330. this._linesIndices.push(offset);
  101331. this._linesIndices.push(offset + 1);
  101332. this._linesIndices.push(offset + 2);
  101333. this._linesIndices.push(offset);
  101334. this._linesIndices.push(offset + 2);
  101335. this._linesIndices.push(offset + 3);
  101336. };
  101337. /**
  101338. * Generate edges for each line in LinesMesh. Every Line should be rendered as edge.
  101339. */
  101340. LineEdgesRenderer.prototype._generateEdgesLines = function () {
  101341. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  101342. var indices = this._source.getIndices();
  101343. if (!indices || !positions) {
  101344. return;
  101345. }
  101346. // First let's find adjacencies
  101347. var adjacencies = new Array();
  101348. var faceNormals = new Array();
  101349. var index;
  101350. for (var i = 0; i < (positions.length / 3) - 1; i++) {
  101351. var currentAdjecancy = new FaceAdjacencies();
  101352. currentAdjecancy.p0 = new BABYLON.Vector3(positions[i * 3], positions[i * 3 + 1], positions[i * 3 + 2]);
  101353. currentAdjecancy.p1 = new BABYLON.Vector3(positions[(i + 1) * 3], positions[(i + 1) * 3 + 1], positions[(i + 1) * 3 + 2]);
  101354. adjacencies.push(currentAdjecancy);
  101355. }
  101356. // Create lines
  101357. for (index = 0; index < adjacencies.length; index++) {
  101358. // 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
  101359. var current = adjacencies[index];
  101360. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  101361. }
  101362. // Merge into a single mesh
  101363. var engine = this._source.getScene().getEngine();
  101364. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  101365. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  101366. this._ib = engine.createIndexBuffer(this._linesIndices);
  101367. this._indicesCount = this._linesIndices.length;
  101368. };
  101369. return LineEdgesRenderer;
  101370. }(BABYLON.EdgesRenderer));
  101371. BABYLON.LineEdgesRenderer = LineEdgesRenderer;
  101372. })(BABYLON || (BABYLON = {}));
  101373. //# sourceMappingURL=babylon.lineEdgesRenderer.js.map
  101374. var BABYLON;
  101375. (function (BABYLON) {
  101376. // Adds the parser to the scene parsers.
  101377. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER, function (parsedData, scene, container, rootUrl) {
  101378. if (parsedData.effectLayers) {
  101379. if (!container.effectLayers) {
  101380. container.effectLayers = new Array();
  101381. }
  101382. for (var index = 0; index < parsedData.effectLayers.length; index++) {
  101383. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  101384. container.effectLayers.push(effectLayer);
  101385. }
  101386. }
  101387. });
  101388. BABYLON.AbstractScene.prototype.removeEffectLayer = function (toRemove) {
  101389. var index = this.effectLayers.indexOf(toRemove);
  101390. if (index !== -1) {
  101391. this.effectLayers.splice(index, 1);
  101392. }
  101393. return index;
  101394. };
  101395. BABYLON.AbstractScene.prototype.addEffectLayer = function (newEffectLayer) {
  101396. this.effectLayers.push(newEffectLayer);
  101397. };
  101398. /**
  101399. * Defines the layer scene component responsible to manage any effect layers
  101400. * in a given scene.
  101401. */
  101402. var EffectLayerSceneComponent = /** @class */ (function () {
  101403. /**
  101404. * Creates a new instance of the component for the given scene
  101405. * @param scene Defines the scene to register the component in
  101406. */
  101407. function EffectLayerSceneComponent(scene) {
  101408. /**
  101409. * The component name helpfull to identify the component in the list of scene components.
  101410. */
  101411. this.name = BABYLON.SceneComponentConstants.NAME_EFFECTLAYER;
  101412. this._renderEffects = false;
  101413. this._needStencil = false;
  101414. this._previousStencilState = false;
  101415. this.scene = scene;
  101416. this._engine = scene.getEngine();
  101417. scene.effectLayers = new Array();
  101418. }
  101419. /**
  101420. * Registers the component in a given scene
  101421. */
  101422. EffectLayerSceneComponent.prototype.register = function () {
  101423. this.scene._isReadyForMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER, this, this._isReadyForMesh);
  101424. this.scene._cameraDrawRenderTargetStage.registerStep(BABYLON.SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER, this, this._renderMainTexture);
  101425. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER, this, this._setStencil);
  101426. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW, this, this._drawRenderingGroup);
  101427. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER, this, this._setStencilBack);
  101428. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW, this, this._drawCamera);
  101429. };
  101430. /**
  101431. * Rebuilds the elements related to this component in case of
  101432. * context lost for instance.
  101433. */
  101434. EffectLayerSceneComponent.prototype.rebuild = function () {
  101435. var layers = this.scene.effectLayers;
  101436. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  101437. var effectLayer = layers_1[_i];
  101438. effectLayer._rebuild();
  101439. }
  101440. };
  101441. /**
  101442. * Serializes the component data to the specified json object
  101443. * @param serializationObject The object to serialize to
  101444. */
  101445. EffectLayerSceneComponent.prototype.serialize = function (serializationObject) {
  101446. // Effect layers
  101447. serializationObject.effectLayers = [];
  101448. var layers = this.scene.effectLayers;
  101449. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  101450. var effectLayer = layers_2[_i];
  101451. if (effectLayer.serialize) {
  101452. serializationObject.effectLayers.push(effectLayer.serialize());
  101453. }
  101454. }
  101455. };
  101456. /**
  101457. * Adds all the element from the container to the scene
  101458. * @param container the container holding the elements
  101459. */
  101460. EffectLayerSceneComponent.prototype.addFromContainer = function (container) {
  101461. var _this = this;
  101462. if (!container.effectLayers) {
  101463. return;
  101464. }
  101465. container.effectLayers.forEach(function (o) {
  101466. _this.scene.addEffectLayer(o);
  101467. });
  101468. };
  101469. /**
  101470. * Removes all the elements in the container from the scene
  101471. * @param container contains the elements to remove
  101472. */
  101473. EffectLayerSceneComponent.prototype.removeFromContainer = function (container) {
  101474. var _this = this;
  101475. if (!container.effectLayers) {
  101476. return;
  101477. }
  101478. container.effectLayers.forEach(function (o) {
  101479. _this.scene.removeEffectLayer(o);
  101480. });
  101481. };
  101482. /**
  101483. * Disposes the component and the associated ressources.
  101484. */
  101485. EffectLayerSceneComponent.prototype.dispose = function () {
  101486. var layers = this.scene.effectLayers;
  101487. while (layers.length) {
  101488. layers[0].dispose();
  101489. }
  101490. };
  101491. EffectLayerSceneComponent.prototype._isReadyForMesh = function (mesh, hardwareInstancedRendering) {
  101492. var layers = this.scene.effectLayers;
  101493. for (var _i = 0, layers_3 = layers; _i < layers_3.length; _i++) {
  101494. var layer = layers_3[_i];
  101495. if (!layer.hasMesh(mesh)) {
  101496. continue;
  101497. }
  101498. for (var _a = 0, _b = mesh.subMeshes; _a < _b.length; _a++) {
  101499. var subMesh = _b[_a];
  101500. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  101501. return false;
  101502. }
  101503. }
  101504. }
  101505. return true;
  101506. };
  101507. EffectLayerSceneComponent.prototype._renderMainTexture = function (camera) {
  101508. this._renderEffects = false;
  101509. this._needStencil = false;
  101510. var layers = this.scene.effectLayers;
  101511. if (layers && layers.length > 0) {
  101512. this._previousStencilState = this._engine.getStencilBuffer();
  101513. for (var _i = 0, layers_4 = layers; _i < layers_4.length; _i++) {
  101514. var effectLayer = layers_4[_i];
  101515. if (effectLayer.shouldRender() &&
  101516. (!effectLayer.camera ||
  101517. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  101518. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  101519. this._renderEffects = true;
  101520. this._needStencil = this._needStencil || effectLayer.needStencil();
  101521. var renderTarget = effectLayer._mainTexture;
  101522. if (renderTarget._shouldRender()) {
  101523. this.scene.incrementRenderId();
  101524. renderTarget.render(false, false);
  101525. }
  101526. }
  101527. }
  101528. this.scene.incrementRenderId();
  101529. }
  101530. };
  101531. EffectLayerSceneComponent.prototype._setStencil = function (camera) {
  101532. // Activate effect Layer stencil
  101533. if (this._needStencil) {
  101534. this._engine.setStencilBuffer(true);
  101535. }
  101536. };
  101537. EffectLayerSceneComponent.prototype._setStencilBack = function (camera) {
  101538. // Restore effect Layer stencil
  101539. if (this._needStencil) {
  101540. this._engine.setStencilBuffer(this._previousStencilState);
  101541. }
  101542. };
  101543. EffectLayerSceneComponent.prototype._draw = function (renderingGroupId) {
  101544. if (this._renderEffects) {
  101545. this._engine.setDepthBuffer(false);
  101546. var layers = this.scene.effectLayers;
  101547. for (var i = 0; i < layers.length; i++) {
  101548. var effectLayer = layers[i];
  101549. if (effectLayer.renderingGroupId === renderingGroupId) {
  101550. if (effectLayer.shouldRender()) {
  101551. effectLayer.render();
  101552. }
  101553. }
  101554. }
  101555. this._engine.setDepthBuffer(true);
  101556. }
  101557. };
  101558. EffectLayerSceneComponent.prototype._drawCamera = function (camera) {
  101559. if (this._renderEffects) {
  101560. this._draw(-1);
  101561. }
  101562. };
  101563. EffectLayerSceneComponent.prototype._drawRenderingGroup = function (index) {
  101564. if (!this.scene._isInIntermediateRendering() && this._renderEffects) {
  101565. this._draw(index);
  101566. }
  101567. };
  101568. return EffectLayerSceneComponent;
  101569. }());
  101570. BABYLON.EffectLayerSceneComponent = EffectLayerSceneComponent;
  101571. })(BABYLON || (BABYLON = {}));
  101572. //# sourceMappingURL=babylon.effectLayerSceneComponent.js.map
  101573. var __assign = (this && this.__assign) || function () {
  101574. __assign = Object.assign || function(t) {
  101575. for (var s, i = 1, n = arguments.length; i < n; i++) {
  101576. s = arguments[i];
  101577. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  101578. t[p] = s[p];
  101579. }
  101580. return t;
  101581. };
  101582. return __assign.apply(this, arguments);
  101583. };
  101584. var BABYLON;
  101585. (function (BABYLON) {
  101586. /**
  101587. * The effect layer Helps adding post process effect blended with the main pass.
  101588. *
  101589. * This can be for instance use to generate glow or higlight effects on the scene.
  101590. *
  101591. * The effect layer class can not be used directly and is intented to inherited from to be
  101592. * customized per effects.
  101593. */
  101594. var EffectLayer = /** @class */ (function () {
  101595. /**
  101596. * Instantiates a new effect Layer and references it in the scene.
  101597. * @param name The name of the layer
  101598. * @param scene The scene to use the layer in
  101599. */
  101600. function EffectLayer(
  101601. /** The Friendly of the effect in the scene */
  101602. name, scene) {
  101603. this._vertexBuffers = {};
  101604. this._maxSize = 0;
  101605. this._mainTextureDesiredSize = { width: 0, height: 0 };
  101606. this._shouldRender = true;
  101607. this._postProcesses = [];
  101608. this._textures = [];
  101609. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  101610. /**
  101611. * The clear color of the texture used to generate the glow map.
  101612. */
  101613. this.neutralColor = new BABYLON.Color4();
  101614. /**
  101615. * Specifies wether the highlight layer is enabled or not.
  101616. */
  101617. this.isEnabled = true;
  101618. /**
  101619. * An event triggered when the effect layer has been disposed.
  101620. */
  101621. this.onDisposeObservable = new BABYLON.Observable();
  101622. /**
  101623. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  101624. */
  101625. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  101626. /**
  101627. * An event triggered when the generated texture is being merged in the scene.
  101628. */
  101629. this.onBeforeComposeObservable = new BABYLON.Observable();
  101630. /**
  101631. * An event triggered when the generated texture has been merged in the scene.
  101632. */
  101633. this.onAfterComposeObservable = new BABYLON.Observable();
  101634. /**
  101635. * An event triggered when the efffect layer changes its size.
  101636. */
  101637. this.onSizeChangedObservable = new BABYLON.Observable();
  101638. this.name = name;
  101639. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  101640. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER);
  101641. if (!component) {
  101642. component = new BABYLON.EffectLayerSceneComponent(this._scene);
  101643. this._scene._addComponent(component);
  101644. }
  101645. this._engine = this._scene.getEngine();
  101646. this._maxSize = this._engine.getCaps().maxTextureSize;
  101647. this._scene.effectLayers.push(this);
  101648. // Generate Buffers
  101649. this._generateIndexBuffer();
  101650. this._genrateVertexBuffer();
  101651. }
  101652. Object.defineProperty(EffectLayer.prototype, "camera", {
  101653. /**
  101654. * Gets the camera attached to the layer.
  101655. */
  101656. get: function () {
  101657. return this._effectLayerOptions.camera;
  101658. },
  101659. enumerable: true,
  101660. configurable: true
  101661. });
  101662. Object.defineProperty(EffectLayer.prototype, "renderingGroupId", {
  101663. /**
  101664. * Gets the rendering group id the layer should render in.
  101665. */
  101666. get: function () {
  101667. return this._effectLayerOptions.renderingGroupId;
  101668. },
  101669. enumerable: true,
  101670. configurable: true
  101671. });
  101672. /**
  101673. * Initializes the effect layer with the required options.
  101674. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  101675. */
  101676. EffectLayer.prototype._init = function (options) {
  101677. // Adapt options
  101678. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);
  101679. this._setMainTextureSize();
  101680. this._createMainTexture();
  101681. this._createTextureAndPostProcesses();
  101682. this._mergeEffect = this._createMergeEffect();
  101683. };
  101684. /**
  101685. * Generates the index buffer of the full screen quad blending to the main canvas.
  101686. */
  101687. EffectLayer.prototype._generateIndexBuffer = function () {
  101688. // Indices
  101689. var indices = [];
  101690. indices.push(0);
  101691. indices.push(1);
  101692. indices.push(2);
  101693. indices.push(0);
  101694. indices.push(2);
  101695. indices.push(3);
  101696. this._indexBuffer = this._engine.createIndexBuffer(indices);
  101697. };
  101698. /**
  101699. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  101700. */
  101701. EffectLayer.prototype._genrateVertexBuffer = function () {
  101702. // VBO
  101703. var vertices = [];
  101704. vertices.push(1, 1);
  101705. vertices.push(-1, 1);
  101706. vertices.push(-1, -1);
  101707. vertices.push(1, -1);
  101708. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  101709. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  101710. };
  101711. /**
  101712. * Sets the main texture desired size which is the closest power of two
  101713. * of the engine canvas size.
  101714. */
  101715. EffectLayer.prototype._setMainTextureSize = function () {
  101716. if (this._effectLayerOptions.mainTextureFixedSize) {
  101717. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  101718. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  101719. }
  101720. else {
  101721. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  101722. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  101723. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  101724. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  101725. }
  101726. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  101727. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  101728. };
  101729. /**
  101730. * Creates the main texture for the effect layer.
  101731. */
  101732. EffectLayer.prototype._createMainTexture = function () {
  101733. var _this = this;
  101734. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  101735. width: this._mainTextureDesiredSize.width,
  101736. height: this._mainTextureDesiredSize.height
  101737. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  101738. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  101739. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101740. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101741. this._mainTexture.anisotropicFilteringLevel = 1;
  101742. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  101743. this._mainTexture.renderParticles = false;
  101744. this._mainTexture.renderList = null;
  101745. this._mainTexture.ignoreCameraViewport = true;
  101746. // Custom render function
  101747. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  101748. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  101749. var index;
  101750. var engine = _this._scene.getEngine();
  101751. if (depthOnlySubMeshes.length) {
  101752. engine.setColorWrite(false);
  101753. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  101754. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  101755. }
  101756. engine.setColorWrite(true);
  101757. }
  101758. for (index = 0; index < opaqueSubMeshes.length; index++) {
  101759. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  101760. }
  101761. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  101762. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  101763. }
  101764. for (index = 0; index < transparentSubMeshes.length; index++) {
  101765. _this._renderSubMesh(transparentSubMeshes.data[index]);
  101766. }
  101767. };
  101768. this._mainTexture.onClearObservable.add(function (engine) {
  101769. engine.clear(_this.neutralColor, true, true, true);
  101770. });
  101771. };
  101772. /**
  101773. * Checks for the readiness of the element composing the layer.
  101774. * @param subMesh the mesh to check for
  101775. * @param useInstances specify wether or not to use instances to render the mesh
  101776. * @param emissiveTexture the associated emissive texture used to generate the glow
  101777. * @return true if ready otherwise, false
  101778. */
  101779. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  101780. var material = subMesh.getMaterial();
  101781. if (!material) {
  101782. return false;
  101783. }
  101784. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  101785. return false;
  101786. }
  101787. var defines = [];
  101788. var attribs = [BABYLON.VertexBuffer.PositionKind];
  101789. var mesh = subMesh.getMesh();
  101790. var uv1 = false;
  101791. var uv2 = false;
  101792. // Alpha test
  101793. if (material && material.needAlphaTesting()) {
  101794. var alphaTexture = material.getAlphaTestTexture();
  101795. if (alphaTexture) {
  101796. defines.push("#define ALPHATEST");
  101797. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  101798. alphaTexture.coordinatesIndex === 1) {
  101799. defines.push("#define DIFFUSEUV2");
  101800. uv2 = true;
  101801. }
  101802. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  101803. defines.push("#define DIFFUSEUV1");
  101804. uv1 = true;
  101805. }
  101806. }
  101807. }
  101808. // Emissive
  101809. if (emissiveTexture) {
  101810. defines.push("#define EMISSIVE");
  101811. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  101812. emissiveTexture.coordinatesIndex === 1) {
  101813. defines.push("#define EMISSIVEUV2");
  101814. uv2 = true;
  101815. }
  101816. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  101817. defines.push("#define EMISSIVEUV1");
  101818. uv1 = true;
  101819. }
  101820. }
  101821. if (uv1) {
  101822. attribs.push(BABYLON.VertexBuffer.UVKind);
  101823. defines.push("#define UV1");
  101824. }
  101825. if (uv2) {
  101826. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  101827. defines.push("#define UV2");
  101828. }
  101829. // Bones
  101830. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  101831. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  101832. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  101833. if (mesh.numBoneInfluencers > 4) {
  101834. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  101835. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  101836. }
  101837. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  101838. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  101839. }
  101840. else {
  101841. defines.push("#define NUM_BONE_INFLUENCERS 0");
  101842. }
  101843. // Morph targets
  101844. var manager = mesh.morphTargetManager;
  101845. var morphInfluencers = 0;
  101846. if (manager) {
  101847. if (manager.numInfluencers > 0) {
  101848. defines.push("#define MORPHTARGETS");
  101849. morphInfluencers = manager.numInfluencers;
  101850. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  101851. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  101852. }
  101853. }
  101854. // Instances
  101855. if (useInstances) {
  101856. defines.push("#define INSTANCES");
  101857. attribs.push("world0");
  101858. attribs.push("world1");
  101859. attribs.push("world2");
  101860. attribs.push("world3");
  101861. }
  101862. // Get correct effect
  101863. var join = defines.join("\n");
  101864. if (this._cachedDefines !== join) {
  101865. this._cachedDefines = join;
  101866. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  101867. }
  101868. return this._effectLayerMapGenerationEffect.isReady();
  101869. };
  101870. /**
  101871. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  101872. */
  101873. EffectLayer.prototype.render = function () {
  101874. var currentEffect = this._mergeEffect;
  101875. // Check
  101876. if (!currentEffect.isReady())
  101877. return;
  101878. for (var i = 0; i < this._postProcesses.length; i++) {
  101879. if (!this._postProcesses[i].isReady()) {
  101880. return;
  101881. }
  101882. }
  101883. var engine = this._scene.getEngine();
  101884. this.onBeforeComposeObservable.notifyObservers(this);
  101885. // Render
  101886. engine.enableEffect(currentEffect);
  101887. engine.setState(false);
  101888. // VBOs
  101889. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  101890. // Cache
  101891. var previousAlphaMode = engine.getAlphaMode();
  101892. // Go Blend.
  101893. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  101894. // Blends the map on the main canvas.
  101895. this._internalRender(currentEffect);
  101896. // Restore Alpha
  101897. engine.setAlphaMode(previousAlphaMode);
  101898. this.onAfterComposeObservable.notifyObservers(this);
  101899. // Handle size changes.
  101900. var size = this._mainTexture.getSize();
  101901. this._setMainTextureSize();
  101902. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  101903. // Recreate RTT and post processes on size change.
  101904. this.onSizeChangedObservable.notifyObservers(this);
  101905. this._disposeTextureAndPostProcesses();
  101906. this._createMainTexture();
  101907. this._createTextureAndPostProcesses();
  101908. }
  101909. };
  101910. /**
  101911. * Determine if a given mesh will be used in the current effect.
  101912. * @param mesh mesh to test
  101913. * @returns true if the mesh will be used
  101914. */
  101915. EffectLayer.prototype.hasMesh = function (mesh) {
  101916. if (this.renderingGroupId === -1 || mesh.renderingGroupId === this.renderingGroupId) {
  101917. return true;
  101918. }
  101919. return false;
  101920. };
  101921. /**
  101922. * Returns true if the layer contains information to display, otherwise false.
  101923. * @returns true if the glow layer should be rendered
  101924. */
  101925. EffectLayer.prototype.shouldRender = function () {
  101926. return this.isEnabled && this._shouldRender;
  101927. };
  101928. /**
  101929. * Returns true if the mesh should render, otherwise false.
  101930. * @param mesh The mesh to render
  101931. * @returns true if it should render otherwise false
  101932. */
  101933. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  101934. return true;
  101935. };
  101936. /**
  101937. * Returns true if the mesh should render, otherwise false.
  101938. * @param mesh The mesh to render
  101939. * @returns true if it should render otherwise false
  101940. */
  101941. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  101942. return true;
  101943. };
  101944. /**
  101945. * Renders the submesh passed in parameter to the generation map.
  101946. */
  101947. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  101948. var _this = this;
  101949. if (!this.shouldRender()) {
  101950. return;
  101951. }
  101952. var material = subMesh.getMaterial();
  101953. var mesh = subMesh.getRenderingMesh();
  101954. var scene = this._scene;
  101955. var engine = scene.getEngine();
  101956. if (!material) {
  101957. return;
  101958. }
  101959. // Do not block in blend mode.
  101960. if (material.needAlphaBlendingForMesh(mesh)) {
  101961. return;
  101962. }
  101963. // Culling
  101964. engine.setState(material.backFaceCulling);
  101965. // Managing instances
  101966. var batch = mesh._getInstancesRenderList(subMesh._id);
  101967. if (batch.mustReturn) {
  101968. return;
  101969. }
  101970. // Early Exit per mesh
  101971. if (!this._shouldRenderMesh(mesh)) {
  101972. return;
  101973. }
  101974. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  101975. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  101976. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  101977. engine.enableEffect(this._effectLayerMapGenerationEffect);
  101978. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  101979. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  101980. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  101981. // Alpha test
  101982. if (material && material.needAlphaTesting()) {
  101983. var alphaTexture = material.getAlphaTestTexture();
  101984. if (alphaTexture) {
  101985. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  101986. var textureMatrix = alphaTexture.getTextureMatrix();
  101987. if (textureMatrix) {
  101988. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  101989. }
  101990. }
  101991. }
  101992. // Glow emissive only
  101993. if (this._emissiveTextureAndColor.texture) {
  101994. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  101995. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  101996. }
  101997. // Bones
  101998. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  101999. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  102000. }
  102001. // Morph targets
  102002. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  102003. // Draw
  102004. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  102005. }
  102006. else {
  102007. // Need to reset refresh rate of the main map
  102008. this._mainTexture.resetRefreshCounter();
  102009. }
  102010. };
  102011. /**
  102012. * Rebuild the required buffers.
  102013. * @hidden Internal use only.
  102014. */
  102015. EffectLayer.prototype._rebuild = function () {
  102016. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  102017. if (vb) {
  102018. vb._rebuild();
  102019. }
  102020. this._generateIndexBuffer();
  102021. };
  102022. /**
  102023. * Dispose only the render target textures and post process.
  102024. */
  102025. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  102026. this._mainTexture.dispose();
  102027. for (var i = 0; i < this._postProcesses.length; i++) {
  102028. if (this._postProcesses[i]) {
  102029. this._postProcesses[i].dispose();
  102030. }
  102031. }
  102032. this._postProcesses = [];
  102033. for (var i = 0; i < this._textures.length; i++) {
  102034. if (this._textures[i]) {
  102035. this._textures[i].dispose();
  102036. }
  102037. }
  102038. this._textures = [];
  102039. };
  102040. /**
  102041. * Dispose the highlight layer and free resources.
  102042. */
  102043. EffectLayer.prototype.dispose = function () {
  102044. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  102045. if (vertexBuffer) {
  102046. vertexBuffer.dispose();
  102047. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  102048. }
  102049. if (this._indexBuffer) {
  102050. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  102051. this._indexBuffer = null;
  102052. }
  102053. // Clean textures and post processes
  102054. this._disposeTextureAndPostProcesses();
  102055. // Remove from scene
  102056. var index = this._scene.effectLayers.indexOf(this, 0);
  102057. if (index > -1) {
  102058. this._scene.effectLayers.splice(index, 1);
  102059. }
  102060. // Callback
  102061. this.onDisposeObservable.notifyObservers(this);
  102062. this.onDisposeObservable.clear();
  102063. this.onBeforeRenderMainTextureObservable.clear();
  102064. this.onBeforeComposeObservable.clear();
  102065. this.onAfterComposeObservable.clear();
  102066. this.onSizeChangedObservable.clear();
  102067. };
  102068. /**
  102069. * Gets the class name of the effect layer
  102070. * @returns the string with the class name of the effect layer
  102071. */
  102072. EffectLayer.prototype.getClassName = function () {
  102073. return "EffectLayer";
  102074. };
  102075. /**
  102076. * Creates an effect layer from parsed effect layer data
  102077. * @param parsedEffectLayer defines effect layer data
  102078. * @param scene defines the current scene
  102079. * @param rootUrl defines the root URL containing the effect layer information
  102080. * @returns a parsed effect Layer
  102081. */
  102082. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  102083. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  102084. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  102085. };
  102086. __decorate([
  102087. BABYLON.serialize()
  102088. ], EffectLayer.prototype, "name", void 0);
  102089. __decorate([
  102090. BABYLON.serializeAsColor4()
  102091. ], EffectLayer.prototype, "neutralColor", void 0);
  102092. __decorate([
  102093. BABYLON.serialize()
  102094. ], EffectLayer.prototype, "isEnabled", void 0);
  102095. __decorate([
  102096. BABYLON.serializeAsCameraReference()
  102097. ], EffectLayer.prototype, "camera", null);
  102098. __decorate([
  102099. BABYLON.serialize()
  102100. ], EffectLayer.prototype, "renderingGroupId", null);
  102101. return EffectLayer;
  102102. }());
  102103. BABYLON.EffectLayer = EffectLayer;
  102104. })(BABYLON || (BABYLON = {}));
  102105. //# sourceMappingURL=babylon.effectLayer.js.map
  102106. var BABYLON;
  102107. (function (BABYLON) {
  102108. BABYLON.AbstractScene.prototype.getHighlightLayerByName = function (name) {
  102109. for (var index = 0; index < this.effectLayers.length; index++) {
  102110. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === HighlightLayer.EffectName) {
  102111. return this.effectLayers[index];
  102112. }
  102113. }
  102114. return null;
  102115. };
  102116. /**
  102117. * Special Glow Blur post process only blurring the alpha channel
  102118. * It enforces keeping the most luminous color in the color channel.
  102119. */
  102120. var GlowBlurPostProcess = /** @class */ (function (_super) {
  102121. __extends(GlowBlurPostProcess, _super);
  102122. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  102123. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  102124. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  102125. _this.direction = direction;
  102126. _this.kernel = kernel;
  102127. _this.onApplyObservable.add(function (effect) {
  102128. effect.setFloat2("screenSize", _this.width, _this.height);
  102129. effect.setVector2("direction", _this.direction);
  102130. effect.setFloat("blurWidth", _this.kernel);
  102131. });
  102132. return _this;
  102133. }
  102134. return GlowBlurPostProcess;
  102135. }(BABYLON.PostProcess));
  102136. /**
  102137. * The highlight layer Helps adding a glow effect around a mesh.
  102138. *
  102139. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  102140. * glowy meshes to your scene.
  102141. *
  102142. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  102143. */
  102144. var HighlightLayer = /** @class */ (function (_super) {
  102145. __extends(HighlightLayer, _super);
  102146. /**
  102147. * Instantiates a new highlight Layer and references it to the scene..
  102148. * @param name The name of the layer
  102149. * @param scene The scene to use the layer in
  102150. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  102151. */
  102152. function HighlightLayer(name, scene, options) {
  102153. var _this = _super.call(this, name, scene) || this;
  102154. _this.name = name;
  102155. /**
  102156. * Specifies whether or not the inner glow is ACTIVE in the layer.
  102157. */
  102158. _this.innerGlow = true;
  102159. /**
  102160. * Specifies whether or not the outer glow is ACTIVE in the layer.
  102161. */
  102162. _this.outerGlow = true;
  102163. /**
  102164. * An event triggered when the highlight layer is being blurred.
  102165. */
  102166. _this.onBeforeBlurObservable = new BABYLON.Observable();
  102167. /**
  102168. * An event triggered when the highlight layer has been blurred.
  102169. */
  102170. _this.onAfterBlurObservable = new BABYLON.Observable();
  102171. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  102172. _this._meshes = {};
  102173. _this._excludedMeshes = {};
  102174. _this.neutralColor = HighlightLayer.NeutralColor;
  102175. // Warn on stencil
  102176. if (!_this._engine.isStencilEnable) {
  102177. 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 }");
  102178. }
  102179. // Adapt options
  102180. _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);
  102181. // Initialize the layer
  102182. _this._init({
  102183. alphaBlendingMode: _this._options.alphaBlendingMode,
  102184. camera: _this._options.camera,
  102185. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  102186. mainTextureRatio: _this._options.mainTextureRatio,
  102187. renderingGroupId: _this._options.renderingGroupId
  102188. });
  102189. // Do not render as long as no meshes have been added
  102190. _this._shouldRender = false;
  102191. return _this;
  102192. }
  102193. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  102194. /**
  102195. * Gets the horizontal size of the blur.
  102196. */
  102197. get: function () {
  102198. return this._horizontalBlurPostprocess.kernel;
  102199. },
  102200. /**
  102201. * Specifies the horizontal size of the blur.
  102202. */
  102203. set: function (value) {
  102204. this._horizontalBlurPostprocess.kernel = value;
  102205. },
  102206. enumerable: true,
  102207. configurable: true
  102208. });
  102209. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  102210. /**
  102211. * Gets the vertical size of the blur.
  102212. */
  102213. get: function () {
  102214. return this._verticalBlurPostprocess.kernel;
  102215. },
  102216. /**
  102217. * Specifies the vertical size of the blur.
  102218. */
  102219. set: function (value) {
  102220. this._verticalBlurPostprocess.kernel = value;
  102221. },
  102222. enumerable: true,
  102223. configurable: true
  102224. });
  102225. /**
  102226. * Get the effect name of the layer.
  102227. * @return The effect name
  102228. */
  102229. HighlightLayer.prototype.getEffectName = function () {
  102230. return HighlightLayer.EffectName;
  102231. };
  102232. /**
  102233. * Create the merge effect. This is the shader use to blit the information back
  102234. * to the main canvas at the end of the scene rendering.
  102235. */
  102236. HighlightLayer.prototype._createMergeEffect = function () {
  102237. // Effect
  102238. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  102239. };
  102240. /**
  102241. * Creates the render target textures and post processes used in the highlight layer.
  102242. */
  102243. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  102244. var _this = this;
  102245. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  102246. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  102247. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  102248. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  102249. var textureType = 0;
  102250. if (this._engine.getCaps().textureHalfFloatRender) {
  102251. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  102252. }
  102253. else {
  102254. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  102255. }
  102256. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  102257. width: blurTextureWidth,
  102258. height: blurTextureHeight
  102259. }, this._scene, false, true, textureType);
  102260. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102261. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102262. this._blurTexture.anisotropicFilteringLevel = 16;
  102263. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  102264. this._blurTexture.renderParticles = false;
  102265. this._blurTexture.ignoreCameraViewport = true;
  102266. this._textures = [this._blurTexture];
  102267. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  102268. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  102269. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  102270. effect.setTexture("textureSampler", _this._mainTexture);
  102271. });
  102272. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  102273. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  102274. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  102275. });
  102276. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  102277. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  102278. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  102279. });
  102280. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  102281. }
  102282. else {
  102283. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  102284. width: blurTextureWidth,
  102285. height: blurTextureHeight
  102286. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  102287. this._horizontalBlurPostprocess.width = blurTextureWidth;
  102288. this._horizontalBlurPostprocess.height = blurTextureHeight;
  102289. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  102290. effect.setTexture("textureSampler", _this._mainTexture);
  102291. });
  102292. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  102293. width: blurTextureWidth,
  102294. height: blurTextureHeight
  102295. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  102296. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  102297. }
  102298. this._mainTexture.onAfterUnbindObservable.add(function () {
  102299. _this.onBeforeBlurObservable.notifyObservers(_this);
  102300. var internalTexture = _this._blurTexture.getInternalTexture();
  102301. if (internalTexture) {
  102302. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  102303. }
  102304. _this.onAfterBlurObservable.notifyObservers(_this);
  102305. });
  102306. // Prevent autoClear.
  102307. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  102308. };
  102309. /**
  102310. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  102311. */
  102312. HighlightLayer.prototype.needStencil = function () {
  102313. return true;
  102314. };
  102315. /**
  102316. * Checks for the readiness of the element composing the layer.
  102317. * @param subMesh the mesh to check for
  102318. * @param useInstances specify wether or not to use instances to render the mesh
  102319. * @param emissiveTexture the associated emissive texture used to generate the glow
  102320. * @return true if ready otherwise, false
  102321. */
  102322. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  102323. var material = subMesh.getMaterial();
  102324. var mesh = subMesh.getRenderingMesh();
  102325. if (!material || !mesh || !this._meshes) {
  102326. return false;
  102327. }
  102328. var emissiveTexture = null;
  102329. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  102330. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  102331. emissiveTexture = material.emissiveTexture;
  102332. }
  102333. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  102334. };
  102335. /**
  102336. * Implementation specific of rendering the generating effect on the main canvas.
  102337. * @param effect The effect used to render through
  102338. */
  102339. HighlightLayer.prototype._internalRender = function (effect) {
  102340. // Texture
  102341. effect.setTexture("textureSampler", this._blurTexture);
  102342. // Cache
  102343. var engine = this._engine;
  102344. var previousStencilBuffer = engine.getStencilBuffer();
  102345. var previousStencilFunction = engine.getStencilFunction();
  102346. var previousStencilMask = engine.getStencilMask();
  102347. var previousStencilOperationPass = engine.getStencilOperationPass();
  102348. var previousStencilOperationFail = engine.getStencilOperationFail();
  102349. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  102350. var previousStencilReference = engine.getStencilFunctionReference();
  102351. // Stencil operations
  102352. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  102353. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  102354. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  102355. // Draw order
  102356. engine.setStencilMask(0x00);
  102357. engine.setStencilBuffer(true);
  102358. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  102359. // 2 passes inner outer
  102360. if (this.outerGlow) {
  102361. effect.setFloat("offset", 0);
  102362. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  102363. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  102364. }
  102365. if (this.innerGlow) {
  102366. effect.setFloat("offset", 1);
  102367. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  102368. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  102369. }
  102370. // Restore Cache
  102371. engine.setStencilFunction(previousStencilFunction);
  102372. engine.setStencilMask(previousStencilMask);
  102373. engine.setStencilBuffer(previousStencilBuffer);
  102374. engine.setStencilOperationPass(previousStencilOperationPass);
  102375. engine.setStencilOperationFail(previousStencilOperationFail);
  102376. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  102377. engine.setStencilFunctionReference(previousStencilReference);
  102378. };
  102379. /**
  102380. * Returns true if the layer contains information to display, otherwise false.
  102381. */
  102382. HighlightLayer.prototype.shouldRender = function () {
  102383. if (_super.prototype.shouldRender.call(this)) {
  102384. return this._meshes ? true : false;
  102385. }
  102386. return false;
  102387. };
  102388. /**
  102389. * Returns true if the mesh should render, otherwise false.
  102390. * @param mesh The mesh to render
  102391. * @returns true if it should render otherwise false
  102392. */
  102393. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  102394. // Excluded Mesh
  102395. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  102396. return false;
  102397. }
  102398. ;
  102399. if (!_super.prototype.hasMesh.call(this, mesh)) {
  102400. return false;
  102401. }
  102402. return true;
  102403. };
  102404. /**
  102405. * Sets the required values for both the emissive texture and and the main color.
  102406. */
  102407. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  102408. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  102409. if (highlightLayerMesh) {
  102410. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  102411. }
  102412. else {
  102413. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  102414. }
  102415. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  102416. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  102417. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  102418. }
  102419. else {
  102420. this._emissiveTextureAndColor.texture = null;
  102421. }
  102422. };
  102423. /**
  102424. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  102425. * @param mesh The mesh to exclude from the highlight layer
  102426. */
  102427. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  102428. if (!this._excludedMeshes) {
  102429. return;
  102430. }
  102431. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  102432. if (!meshExcluded) {
  102433. this._excludedMeshes[mesh.uniqueId] = {
  102434. mesh: mesh,
  102435. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  102436. mesh.getEngine().setStencilBuffer(false);
  102437. }),
  102438. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  102439. mesh.getEngine().setStencilBuffer(true);
  102440. }),
  102441. };
  102442. }
  102443. };
  102444. /**
  102445. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  102446. * @param mesh The mesh to highlight
  102447. */
  102448. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  102449. if (!this._excludedMeshes) {
  102450. return;
  102451. }
  102452. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  102453. if (meshExcluded) {
  102454. if (meshExcluded.beforeRender) {
  102455. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  102456. }
  102457. if (meshExcluded.afterRender) {
  102458. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  102459. }
  102460. }
  102461. this._excludedMeshes[mesh.uniqueId] = null;
  102462. };
  102463. /**
  102464. * Determine if a given mesh will be highlighted by the current HighlightLayer
  102465. * @param mesh mesh to test
  102466. * @returns true if the mesh will be highlighted by the current HighlightLayer
  102467. */
  102468. HighlightLayer.prototype.hasMesh = function (mesh) {
  102469. if (!this._meshes) {
  102470. return false;
  102471. }
  102472. if (!_super.prototype.hasMesh.call(this, mesh)) {
  102473. return false;
  102474. }
  102475. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  102476. };
  102477. /**
  102478. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  102479. * @param mesh The mesh to highlight
  102480. * @param color The color of the highlight
  102481. * @param glowEmissiveOnly Extract the glow from the emissive texture
  102482. */
  102483. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  102484. var _this = this;
  102485. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  102486. if (!this._meshes) {
  102487. return;
  102488. }
  102489. var meshHighlight = this._meshes[mesh.uniqueId];
  102490. if (meshHighlight) {
  102491. meshHighlight.color = color;
  102492. }
  102493. else {
  102494. this._meshes[mesh.uniqueId] = {
  102495. mesh: mesh,
  102496. color: color,
  102497. // Lambda required for capture due to Observable this context
  102498. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  102499. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  102500. _this._defaultStencilReference(mesh);
  102501. }
  102502. else {
  102503. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  102504. }
  102505. }),
  102506. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  102507. glowEmissiveOnly: glowEmissiveOnly
  102508. };
  102509. mesh.onDisposeObservable.add(function () {
  102510. _this._disposeMesh(mesh);
  102511. });
  102512. }
  102513. this._shouldRender = true;
  102514. };
  102515. /**
  102516. * Remove a mesh from the highlight layer in order to make it stop glowing.
  102517. * @param mesh The mesh to highlight
  102518. */
  102519. HighlightLayer.prototype.removeMesh = function (mesh) {
  102520. if (!this._meshes) {
  102521. return;
  102522. }
  102523. var meshHighlight = this._meshes[mesh.uniqueId];
  102524. if (meshHighlight) {
  102525. if (meshHighlight.observerHighlight) {
  102526. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  102527. }
  102528. if (meshHighlight.observerDefault) {
  102529. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  102530. }
  102531. delete this._meshes[mesh.uniqueId];
  102532. }
  102533. this._shouldRender = false;
  102534. for (var meshHighlightToCheck in this._meshes) {
  102535. if (this._meshes[meshHighlightToCheck]) {
  102536. this._shouldRender = true;
  102537. break;
  102538. }
  102539. }
  102540. };
  102541. /**
  102542. * Force the stencil to the normal expected value for none glowing parts
  102543. */
  102544. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  102545. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  102546. };
  102547. /**
  102548. * Free any resources and references associated to a mesh.
  102549. * Internal use
  102550. * @param mesh The mesh to free.
  102551. * @hidden
  102552. */
  102553. HighlightLayer.prototype._disposeMesh = function (mesh) {
  102554. this.removeMesh(mesh);
  102555. this.removeExcludedMesh(mesh);
  102556. };
  102557. /**
  102558. * Dispose the highlight layer and free resources.
  102559. */
  102560. HighlightLayer.prototype.dispose = function () {
  102561. if (this._meshes) {
  102562. // Clean mesh references
  102563. for (var id in this._meshes) {
  102564. var meshHighlight = this._meshes[id];
  102565. if (meshHighlight && meshHighlight.mesh) {
  102566. if (meshHighlight.observerHighlight) {
  102567. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  102568. }
  102569. if (meshHighlight.observerDefault) {
  102570. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  102571. }
  102572. }
  102573. }
  102574. this._meshes = null;
  102575. }
  102576. if (this._excludedMeshes) {
  102577. for (var id in this._excludedMeshes) {
  102578. var meshHighlight = this._excludedMeshes[id];
  102579. if (meshHighlight) {
  102580. if (meshHighlight.beforeRender) {
  102581. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  102582. }
  102583. if (meshHighlight.afterRender) {
  102584. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  102585. }
  102586. }
  102587. }
  102588. this._excludedMeshes = null;
  102589. }
  102590. _super.prototype.dispose.call(this);
  102591. };
  102592. /**
  102593. * Gets the class name of the effect layer
  102594. * @returns the string with the class name of the effect layer
  102595. */
  102596. HighlightLayer.prototype.getClassName = function () {
  102597. return "HighlightLayer";
  102598. };
  102599. /**
  102600. * Serializes this Highlight layer
  102601. * @returns a serialized Highlight layer object
  102602. */
  102603. HighlightLayer.prototype.serialize = function () {
  102604. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  102605. serializationObject.customType = "BABYLON.HighlightLayer";
  102606. // Highlighted meshes
  102607. serializationObject.meshes = [];
  102608. if (this._meshes) {
  102609. for (var m in this._meshes) {
  102610. var mesh = this._meshes[m];
  102611. if (mesh) {
  102612. serializationObject.meshes.push({
  102613. glowEmissiveOnly: mesh.glowEmissiveOnly,
  102614. color: mesh.color.asArray(),
  102615. meshId: mesh.mesh.id
  102616. });
  102617. }
  102618. }
  102619. }
  102620. // Excluded meshes
  102621. serializationObject.excludedMeshes = [];
  102622. if (this._excludedMeshes) {
  102623. for (var e in this._excludedMeshes) {
  102624. var excludedMesh = this._excludedMeshes[e];
  102625. if (excludedMesh) {
  102626. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  102627. }
  102628. }
  102629. }
  102630. return serializationObject;
  102631. };
  102632. /**
  102633. * Creates a Highlight layer from parsed Highlight layer data
  102634. * @param parsedHightlightLayer defines the Highlight layer data
  102635. * @param scene defines the current scene
  102636. * @param rootUrl defines the root URL containing the Highlight layer information
  102637. * @returns a parsed Highlight layer
  102638. */
  102639. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  102640. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  102641. var index;
  102642. // Excluded meshes
  102643. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  102644. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  102645. if (mesh) {
  102646. hl.addExcludedMesh(mesh);
  102647. }
  102648. }
  102649. // Included meshes
  102650. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  102651. var highlightedMesh = parsedHightlightLayer.meshes[index];
  102652. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  102653. if (mesh) {
  102654. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  102655. }
  102656. }
  102657. return hl;
  102658. };
  102659. /**
  102660. * Effect Name of the highlight layer.
  102661. */
  102662. HighlightLayer.EffectName = "HighlightLayer";
  102663. /**
  102664. * The neutral color used during the preparation of the glow effect.
  102665. * This is black by default as the blend operation is a blend operation.
  102666. */
  102667. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  102668. /**
  102669. * Stencil value used for glowing meshes.
  102670. */
  102671. HighlightLayer.GlowingMeshStencilReference = 0x02;
  102672. /**
  102673. * Stencil value used for the other meshes in the scene.
  102674. */
  102675. HighlightLayer.NormalMeshStencilReference = 0x01;
  102676. __decorate([
  102677. BABYLON.serialize()
  102678. ], HighlightLayer.prototype, "innerGlow", void 0);
  102679. __decorate([
  102680. BABYLON.serialize()
  102681. ], HighlightLayer.prototype, "outerGlow", void 0);
  102682. __decorate([
  102683. BABYLON.serialize()
  102684. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  102685. __decorate([
  102686. BABYLON.serialize()
  102687. ], HighlightLayer.prototype, "blurVerticalSize", null);
  102688. __decorate([
  102689. BABYLON.serialize("options")
  102690. ], HighlightLayer.prototype, "_options", void 0);
  102691. return HighlightLayer;
  102692. }(BABYLON.EffectLayer));
  102693. BABYLON.HighlightLayer = HighlightLayer;
  102694. })(BABYLON || (BABYLON = {}));
  102695. //# sourceMappingURL=babylon.highlightLayer.js.map
  102696. var BABYLON;
  102697. (function (BABYLON) {
  102698. BABYLON.AbstractScene.prototype.getGlowLayerByName = function (name) {
  102699. for (var index = 0; index < this.effectLayers.length; index++) {
  102700. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === GlowLayer.EffectName) {
  102701. return this.effectLayers[index];
  102702. }
  102703. }
  102704. return null;
  102705. };
  102706. /**
  102707. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  102708. *
  102709. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  102710. * glowy meshes to your scene.
  102711. *
  102712. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  102713. */
  102714. var GlowLayer = /** @class */ (function (_super) {
  102715. __extends(GlowLayer, _super);
  102716. /**
  102717. * Instantiates a new glow Layer and references it to the scene.
  102718. * @param name The name of the layer
  102719. * @param scene The scene to use the layer in
  102720. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  102721. */
  102722. function GlowLayer(name, scene, options) {
  102723. var _this = _super.call(this, name, scene) || this;
  102724. _this._intensity = 1.0;
  102725. _this._includedOnlyMeshes = [];
  102726. _this._excludedMeshes = [];
  102727. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  102728. // Adapt options
  102729. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1, renderingGroupId: -1 }, options);
  102730. // Initialize the layer
  102731. _this._init({
  102732. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  102733. camera: _this._options.camera,
  102734. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  102735. mainTextureRatio: _this._options.mainTextureRatio,
  102736. renderingGroupId: _this._options.renderingGroupId
  102737. });
  102738. return _this;
  102739. }
  102740. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  102741. /**
  102742. * Gets the kernel size of the blur.
  102743. */
  102744. get: function () {
  102745. return this._horizontalBlurPostprocess1.kernel;
  102746. },
  102747. /**
  102748. * Sets the kernel size of the blur.
  102749. */
  102750. set: function (value) {
  102751. this._horizontalBlurPostprocess1.kernel = value;
  102752. this._verticalBlurPostprocess1.kernel = value;
  102753. this._horizontalBlurPostprocess2.kernel = value;
  102754. this._verticalBlurPostprocess2.kernel = value;
  102755. },
  102756. enumerable: true,
  102757. configurable: true
  102758. });
  102759. Object.defineProperty(GlowLayer.prototype, "intensity", {
  102760. /**
  102761. * Gets the glow intensity.
  102762. */
  102763. get: function () {
  102764. return this._intensity;
  102765. },
  102766. /**
  102767. * Sets the glow intensity.
  102768. */
  102769. set: function (value) {
  102770. this._intensity = value;
  102771. },
  102772. enumerable: true,
  102773. configurable: true
  102774. });
  102775. /**
  102776. * Get the effect name of the layer.
  102777. * @return The effect name
  102778. */
  102779. GlowLayer.prototype.getEffectName = function () {
  102780. return GlowLayer.EffectName;
  102781. };
  102782. /**
  102783. * Create the merge effect. This is the shader use to blit the information back
  102784. * to the main canvas at the end of the scene rendering.
  102785. */
  102786. GlowLayer.prototype._createMergeEffect = function () {
  102787. // Effect
  102788. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  102789. };
  102790. /**
  102791. * Creates the render target textures and post processes used in the glow layer.
  102792. */
  102793. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  102794. var _this = this;
  102795. var blurTextureWidth = this._mainTextureDesiredSize.width;
  102796. var blurTextureHeight = this._mainTextureDesiredSize.height;
  102797. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  102798. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  102799. var textureType = 0;
  102800. if (this._engine.getCaps().textureHalfFloatRender) {
  102801. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  102802. }
  102803. else {
  102804. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  102805. }
  102806. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  102807. width: blurTextureWidth,
  102808. height: blurTextureHeight
  102809. }, this._scene, false, true, textureType);
  102810. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102811. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102812. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  102813. this._blurTexture1.renderParticles = false;
  102814. this._blurTexture1.ignoreCameraViewport = true;
  102815. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  102816. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  102817. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  102818. width: blurTextureWidth2,
  102819. height: blurTextureHeight2
  102820. }, this._scene, false, true, textureType);
  102821. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102822. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102823. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  102824. this._blurTexture2.renderParticles = false;
  102825. this._blurTexture2.ignoreCameraViewport = true;
  102826. this._textures = [this._blurTexture1, this._blurTexture2];
  102827. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  102828. width: blurTextureWidth,
  102829. height: blurTextureHeight
  102830. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  102831. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  102832. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  102833. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  102834. effect.setTexture("textureSampler", _this._mainTexture);
  102835. });
  102836. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  102837. width: blurTextureWidth,
  102838. height: blurTextureHeight
  102839. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  102840. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  102841. width: blurTextureWidth2,
  102842. height: blurTextureHeight2
  102843. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  102844. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  102845. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  102846. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  102847. effect.setTexture("textureSampler", _this._blurTexture1);
  102848. });
  102849. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  102850. width: blurTextureWidth2,
  102851. height: blurTextureHeight2
  102852. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  102853. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  102854. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  102855. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  102856. this._mainTexture.samples = this._options.mainTextureSamples;
  102857. this._mainTexture.onAfterUnbindObservable.add(function () {
  102858. var internalTexture = _this._blurTexture1.getInternalTexture();
  102859. if (internalTexture) {
  102860. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  102861. internalTexture = _this._blurTexture2.getInternalTexture();
  102862. if (internalTexture) {
  102863. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  102864. }
  102865. }
  102866. });
  102867. // Prevent autoClear.
  102868. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  102869. };
  102870. /**
  102871. * Checks for the readiness of the element composing the layer.
  102872. * @param subMesh the mesh to check for
  102873. * @param useInstances specify wether or not to use instances to render the mesh
  102874. * @param emissiveTexture the associated emissive texture used to generate the glow
  102875. * @return true if ready otherwise, false
  102876. */
  102877. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  102878. var material = subMesh.getMaterial();
  102879. var mesh = subMesh.getRenderingMesh();
  102880. if (!material || !mesh) {
  102881. return false;
  102882. }
  102883. var emissiveTexture = material.emissiveTexture;
  102884. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  102885. };
  102886. /**
  102887. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  102888. */
  102889. GlowLayer.prototype.needStencil = function () {
  102890. return false;
  102891. };
  102892. /**
  102893. * Implementation specific of rendering the generating effect on the main canvas.
  102894. * @param effect The effect used to render through
  102895. */
  102896. GlowLayer.prototype._internalRender = function (effect) {
  102897. // Texture
  102898. effect.setTexture("textureSampler", this._blurTexture1);
  102899. effect.setTexture("textureSampler2", this._blurTexture2);
  102900. effect.setFloat("offset", this._intensity);
  102901. // Cache
  102902. var engine = this._engine;
  102903. var previousStencilBuffer = engine.getStencilBuffer();
  102904. // Draw order
  102905. engine.setStencilBuffer(false);
  102906. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  102907. // Draw order
  102908. engine.setStencilBuffer(previousStencilBuffer);
  102909. };
  102910. /**
  102911. * Sets the required values for both the emissive texture and and the main color.
  102912. */
  102913. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  102914. var textureLevel = 1.0;
  102915. if (this.customEmissiveTextureSelector) {
  102916. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  102917. }
  102918. else {
  102919. if (material) {
  102920. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  102921. if (this._emissiveTextureAndColor.texture) {
  102922. textureLevel = this._emissiveTextureAndColor.texture.level;
  102923. }
  102924. }
  102925. else {
  102926. this._emissiveTextureAndColor.texture = null;
  102927. }
  102928. }
  102929. if (this.customEmissiveColorSelector) {
  102930. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  102931. }
  102932. else {
  102933. if (material.emissiveColor) {
  102934. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  102935. }
  102936. else {
  102937. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  102938. }
  102939. }
  102940. };
  102941. /**
  102942. * Returns true if the mesh should render, otherwise false.
  102943. * @param mesh The mesh to render
  102944. * @returns true if it should render otherwise false
  102945. */
  102946. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  102947. return this.hasMesh(mesh);
  102948. };
  102949. /**
  102950. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  102951. * @param mesh The mesh to exclude from the glow layer
  102952. */
  102953. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  102954. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  102955. this._excludedMeshes.push(mesh.uniqueId);
  102956. }
  102957. };
  102958. /**
  102959. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  102960. * @param mesh The mesh to remove
  102961. */
  102962. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  102963. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  102964. if (index !== -1) {
  102965. this._excludedMeshes.splice(index, 1);
  102966. }
  102967. };
  102968. /**
  102969. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  102970. * @param mesh The mesh to include in the glow layer
  102971. */
  102972. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  102973. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  102974. this._includedOnlyMeshes.push(mesh.uniqueId);
  102975. }
  102976. };
  102977. /**
  102978. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  102979. * @param mesh The mesh to remove
  102980. */
  102981. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  102982. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  102983. if (index !== -1) {
  102984. this._includedOnlyMeshes.splice(index, 1);
  102985. }
  102986. };
  102987. /**
  102988. * Determine if a given mesh will be used in the glow layer
  102989. * @param mesh The mesh to test
  102990. * @returns true if the mesh will be highlighted by the current glow layer
  102991. */
  102992. GlowLayer.prototype.hasMesh = function (mesh) {
  102993. if (!_super.prototype.hasMesh.call(this, mesh)) {
  102994. return false;
  102995. }
  102996. // Included Mesh
  102997. if (this._includedOnlyMeshes.length) {
  102998. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  102999. }
  103000. ;
  103001. // Excluded Mesh
  103002. if (this._excludedMeshes.length) {
  103003. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  103004. }
  103005. ;
  103006. return true;
  103007. };
  103008. /**
  103009. * Free any resources and references associated to a mesh.
  103010. * Internal use
  103011. * @param mesh The mesh to free.
  103012. * @hidden
  103013. */
  103014. GlowLayer.prototype._disposeMesh = function (mesh) {
  103015. this.removeIncludedOnlyMesh(mesh);
  103016. this.removeExcludedMesh(mesh);
  103017. };
  103018. /**
  103019. * Gets the class name of the effect layer
  103020. * @returns the string with the class name of the effect layer
  103021. */
  103022. GlowLayer.prototype.getClassName = function () {
  103023. return "GlowLayer";
  103024. };
  103025. /**
  103026. * Serializes this glow layer
  103027. * @returns a serialized glow layer object
  103028. */
  103029. GlowLayer.prototype.serialize = function () {
  103030. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  103031. serializationObject.customType = "BABYLON.GlowLayer";
  103032. var index;
  103033. // Included meshes
  103034. serializationObject.includedMeshes = [];
  103035. if (this._includedOnlyMeshes.length) {
  103036. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  103037. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  103038. if (mesh) {
  103039. serializationObject.includedMeshes.push(mesh.id);
  103040. }
  103041. }
  103042. }
  103043. // Excluded meshes
  103044. serializationObject.excludedMeshes = [];
  103045. if (this._excludedMeshes.length) {
  103046. for (index = 0; index < this._excludedMeshes.length; index++) {
  103047. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  103048. if (mesh) {
  103049. serializationObject.excludedMeshes.push(mesh.id);
  103050. }
  103051. }
  103052. }
  103053. return serializationObject;
  103054. };
  103055. /**
  103056. * Creates a Glow Layer from parsed glow layer data
  103057. * @param parsedGlowLayer defines glow layer data
  103058. * @param scene defines the current scene
  103059. * @param rootUrl defines the root URL containing the glow layer information
  103060. * @returns a parsed Glow Layer
  103061. */
  103062. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  103063. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  103064. var index;
  103065. // Excluded meshes
  103066. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  103067. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  103068. if (mesh) {
  103069. gl.addExcludedMesh(mesh);
  103070. }
  103071. }
  103072. // Included meshes
  103073. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  103074. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  103075. if (mesh) {
  103076. gl.addIncludedOnlyMesh(mesh);
  103077. }
  103078. }
  103079. return gl;
  103080. };
  103081. /**
  103082. * Effect Name of the layer.
  103083. */
  103084. GlowLayer.EffectName = "GlowLayer";
  103085. /**
  103086. * The default blur kernel size used for the glow.
  103087. */
  103088. GlowLayer.DefaultBlurKernelSize = 32;
  103089. /**
  103090. * The default texture size ratio used for the glow.
  103091. */
  103092. GlowLayer.DefaultTextureRatio = 0.5;
  103093. __decorate([
  103094. BABYLON.serialize()
  103095. ], GlowLayer.prototype, "blurKernelSize", null);
  103096. __decorate([
  103097. BABYLON.serialize()
  103098. ], GlowLayer.prototype, "intensity", null);
  103099. __decorate([
  103100. BABYLON.serialize("options")
  103101. ], GlowLayer.prototype, "_options", void 0);
  103102. return GlowLayer;
  103103. }(BABYLON.EffectLayer));
  103104. BABYLON.GlowLayer = GlowLayer;
  103105. })(BABYLON || (BABYLON = {}));
  103106. //# sourceMappingURL=babylon.glowLayer.js.map
  103107. var BABYLON;
  103108. (function (BABYLON) {
  103109. /**
  103110. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  103111. */
  103112. var AssetTaskState;
  103113. (function (AssetTaskState) {
  103114. /**
  103115. * Initialization
  103116. */
  103117. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  103118. /**
  103119. * Running
  103120. */
  103121. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  103122. /**
  103123. * Done
  103124. */
  103125. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  103126. /**
  103127. * Error
  103128. */
  103129. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  103130. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  103131. /**
  103132. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  103133. */
  103134. var AbstractAssetTask = /** @class */ (function () {
  103135. /**
  103136. * Creates a new {BABYLON.AssetsManager}
  103137. * @param name defines the name of the task
  103138. */
  103139. function AbstractAssetTask(
  103140. /**
  103141. * Task name
  103142. */ name) {
  103143. this.name = name;
  103144. this._isCompleted = false;
  103145. this._taskState = AssetTaskState.INIT;
  103146. }
  103147. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  103148. /**
  103149. * Get if the task is completed
  103150. */
  103151. get: function () {
  103152. return this._isCompleted;
  103153. },
  103154. enumerable: true,
  103155. configurable: true
  103156. });
  103157. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  103158. /**
  103159. * Gets the current state of the task
  103160. */
  103161. get: function () {
  103162. return this._taskState;
  103163. },
  103164. enumerable: true,
  103165. configurable: true
  103166. });
  103167. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  103168. /**
  103169. * Gets the current error object (if task is in error)
  103170. */
  103171. get: function () {
  103172. return this._errorObject;
  103173. },
  103174. enumerable: true,
  103175. configurable: true
  103176. });
  103177. /**
  103178. * Internal only
  103179. * @hidden
  103180. */
  103181. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  103182. if (this._errorObject) {
  103183. return;
  103184. }
  103185. this._errorObject = {
  103186. message: message,
  103187. exception: exception
  103188. };
  103189. };
  103190. /**
  103191. * Execute the current task
  103192. * @param scene defines the scene where you want your assets to be loaded
  103193. * @param onSuccess is a callback called when the task is successfully executed
  103194. * @param onError is a callback called if an error occurs
  103195. */
  103196. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  103197. var _this = this;
  103198. this._taskState = AssetTaskState.RUNNING;
  103199. this.runTask(scene, function () {
  103200. _this.onDoneCallback(onSuccess, onError);
  103201. }, function (msg, exception) {
  103202. _this.onErrorCallback(onError, msg, exception);
  103203. });
  103204. };
  103205. /**
  103206. * Execute the current task
  103207. * @param scene defines the scene where you want your assets to be loaded
  103208. * @param onSuccess is a callback called when the task is successfully executed
  103209. * @param onError is a callback called if an error occurs
  103210. */
  103211. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  103212. throw new Error("runTask is not implemented");
  103213. };
  103214. /**
  103215. * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.
  103216. * This can be used with failed tasks that have the reason for failure fixed.
  103217. */
  103218. AbstractAssetTask.prototype.reset = function () {
  103219. this._taskState = AssetTaskState.INIT;
  103220. };
  103221. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  103222. this._taskState = AssetTaskState.ERROR;
  103223. this._errorObject = {
  103224. message: message,
  103225. exception: exception
  103226. };
  103227. if (this.onError) {
  103228. this.onError(this, message, exception);
  103229. }
  103230. onError();
  103231. };
  103232. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  103233. try {
  103234. this._taskState = AssetTaskState.DONE;
  103235. this._isCompleted = true;
  103236. if (this.onSuccess) {
  103237. this.onSuccess(this);
  103238. }
  103239. onSuccess();
  103240. }
  103241. catch (e) {
  103242. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  103243. }
  103244. };
  103245. return AbstractAssetTask;
  103246. }());
  103247. BABYLON.AbstractAssetTask = AbstractAssetTask;
  103248. /**
  103249. * Class used to share progress information about assets loading
  103250. */
  103251. var AssetsProgressEvent = /** @class */ (function () {
  103252. /**
  103253. * Creates a {BABYLON.AssetsProgressEvent}
  103254. * @param remainingCount defines the number of remaining tasks to process
  103255. * @param totalCount defines the total number of tasks
  103256. * @param task defines the task that was just processed
  103257. */
  103258. function AssetsProgressEvent(remainingCount, totalCount, task) {
  103259. this.remainingCount = remainingCount;
  103260. this.totalCount = totalCount;
  103261. this.task = task;
  103262. }
  103263. return AssetsProgressEvent;
  103264. }());
  103265. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  103266. /**
  103267. * Define a task used by {BABYLON.AssetsManager} to load meshes
  103268. */
  103269. var MeshAssetTask = /** @class */ (function (_super) {
  103270. __extends(MeshAssetTask, _super);
  103271. /**
  103272. * Creates a new {BABYLON.MeshAssetTask}
  103273. * @param name defines the name of the task
  103274. * @param meshesNames defines the list of mesh's names you want to load
  103275. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  103276. * @param sceneFilename defines the filename of the scene to load from
  103277. */
  103278. function MeshAssetTask(
  103279. /**
  103280. * Defines the name of the task
  103281. */
  103282. name,
  103283. /**
  103284. * Defines the list of mesh's names you want to load
  103285. */
  103286. meshesNames,
  103287. /**
  103288. * Defines the root url to use as a base to load your meshes and associated resources
  103289. */
  103290. rootUrl,
  103291. /**
  103292. * Defines the filename of the scene to load from
  103293. */
  103294. sceneFilename) {
  103295. var _this = _super.call(this, name) || this;
  103296. _this.name = name;
  103297. _this.meshesNames = meshesNames;
  103298. _this.rootUrl = rootUrl;
  103299. _this.sceneFilename = sceneFilename;
  103300. return _this;
  103301. }
  103302. /**
  103303. * Execute the current task
  103304. * @param scene defines the scene where you want your assets to be loaded
  103305. * @param onSuccess is a callback called when the task is successfully executed
  103306. * @param onError is a callback called if an error occurs
  103307. */
  103308. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  103309. var _this = this;
  103310. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  103311. _this.loadedMeshes = meshes;
  103312. _this.loadedParticleSystems = particleSystems;
  103313. _this.loadedSkeletons = skeletons;
  103314. onSuccess();
  103315. }, null, function (scene, message, exception) {
  103316. onError(message, exception);
  103317. });
  103318. };
  103319. return MeshAssetTask;
  103320. }(AbstractAssetTask));
  103321. BABYLON.MeshAssetTask = MeshAssetTask;
  103322. /**
  103323. * Define a task used by {BABYLON.AssetsManager} to load text content
  103324. */
  103325. var TextFileAssetTask = /** @class */ (function (_super) {
  103326. __extends(TextFileAssetTask, _super);
  103327. /**
  103328. * Creates a new TextFileAssetTask object
  103329. * @param name defines the name of the task
  103330. * @param url defines the location of the file to load
  103331. */
  103332. function TextFileAssetTask(
  103333. /**
  103334. * Defines the name of the task
  103335. */
  103336. name,
  103337. /**
  103338. * Defines the location of the file to load
  103339. */
  103340. url) {
  103341. var _this = _super.call(this, name) || this;
  103342. _this.name = name;
  103343. _this.url = url;
  103344. return _this;
  103345. }
  103346. /**
  103347. * Execute the current task
  103348. * @param scene defines the scene where you want your assets to be loaded
  103349. * @param onSuccess is a callback called when the task is successfully executed
  103350. * @param onError is a callback called if an error occurs
  103351. */
  103352. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  103353. var _this = this;
  103354. scene._loadFile(this.url, function (data) {
  103355. _this.text = data;
  103356. onSuccess();
  103357. }, undefined, false, false, function (request, exception) {
  103358. if (request) {
  103359. onError(request.status + " " + request.statusText, exception);
  103360. }
  103361. });
  103362. };
  103363. return TextFileAssetTask;
  103364. }(AbstractAssetTask));
  103365. BABYLON.TextFileAssetTask = TextFileAssetTask;
  103366. /**
  103367. * Define a task used by {BABYLON.AssetsManager} to load binary data
  103368. */
  103369. var BinaryFileAssetTask = /** @class */ (function (_super) {
  103370. __extends(BinaryFileAssetTask, _super);
  103371. /**
  103372. * Creates a new BinaryFileAssetTask object
  103373. * @param name defines the name of the new task
  103374. * @param url defines the location of the file to load
  103375. */
  103376. function BinaryFileAssetTask(
  103377. /**
  103378. * Defines the name of the task
  103379. */
  103380. name,
  103381. /**
  103382. * Defines the location of the file to load
  103383. */
  103384. url) {
  103385. var _this = _super.call(this, name) || this;
  103386. _this.name = name;
  103387. _this.url = url;
  103388. return _this;
  103389. }
  103390. /**
  103391. * Execute the current task
  103392. * @param scene defines the scene where you want your assets to be loaded
  103393. * @param onSuccess is a callback called when the task is successfully executed
  103394. * @param onError is a callback called if an error occurs
  103395. */
  103396. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  103397. var _this = this;
  103398. scene._loadFile(this.url, function (data) {
  103399. _this.data = data;
  103400. onSuccess();
  103401. }, undefined, true, true, function (request, exception) {
  103402. if (request) {
  103403. onError(request.status + " " + request.statusText, exception);
  103404. }
  103405. });
  103406. };
  103407. return BinaryFileAssetTask;
  103408. }(AbstractAssetTask));
  103409. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  103410. /**
  103411. * Define a task used by {BABYLON.AssetsManager} to load images
  103412. */
  103413. var ImageAssetTask = /** @class */ (function (_super) {
  103414. __extends(ImageAssetTask, _super);
  103415. /**
  103416. * Creates a new ImageAssetTask
  103417. * @param name defines the name of the task
  103418. * @param url defines the location of the image to load
  103419. */
  103420. function ImageAssetTask(
  103421. /**
  103422. * Defines the name of the task
  103423. */
  103424. name,
  103425. /**
  103426. * Defines the location of the image to load
  103427. */
  103428. url) {
  103429. var _this = _super.call(this, name) || this;
  103430. _this.name = name;
  103431. _this.url = url;
  103432. return _this;
  103433. }
  103434. /**
  103435. * Execute the current task
  103436. * @param scene defines the scene where you want your assets to be loaded
  103437. * @param onSuccess is a callback called when the task is successfully executed
  103438. * @param onError is a callback called if an error occurs
  103439. */
  103440. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  103441. var _this = this;
  103442. var img = new Image();
  103443. BABYLON.Tools.SetCorsBehavior(this.url, img);
  103444. img.onload = function () {
  103445. _this.image = img;
  103446. onSuccess();
  103447. };
  103448. img.onerror = function (err) {
  103449. onError("Error loading image", err);
  103450. };
  103451. img.src = this.url;
  103452. };
  103453. return ImageAssetTask;
  103454. }(AbstractAssetTask));
  103455. BABYLON.ImageAssetTask = ImageAssetTask;
  103456. /**
  103457. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  103458. */
  103459. var TextureAssetTask = /** @class */ (function (_super) {
  103460. __extends(TextureAssetTask, _super);
  103461. /**
  103462. * Creates a new TextureAssetTask object
  103463. * @param name defines the name of the task
  103464. * @param url defines the location of the file to load
  103465. * @param noMipmap defines if mipmap should not be generated (default is false)
  103466. * @param invertY defines if texture must be inverted on Y axis (default is false)
  103467. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  103468. */
  103469. function TextureAssetTask(
  103470. /**
  103471. * Defines the name of the task
  103472. */
  103473. name,
  103474. /**
  103475. * Defines the location of the file to load
  103476. */
  103477. url,
  103478. /**
  103479. * Defines if mipmap should not be generated (default is false)
  103480. */
  103481. noMipmap,
  103482. /**
  103483. * Defines if texture must be inverted on Y axis (default is false)
  103484. */
  103485. invertY,
  103486. /**
  103487. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  103488. */
  103489. samplingMode) {
  103490. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  103491. var _this = _super.call(this, name) || this;
  103492. _this.name = name;
  103493. _this.url = url;
  103494. _this.noMipmap = noMipmap;
  103495. _this.invertY = invertY;
  103496. _this.samplingMode = samplingMode;
  103497. return _this;
  103498. }
  103499. /**
  103500. * Execute the current task
  103501. * @param scene defines the scene where you want your assets to be loaded
  103502. * @param onSuccess is a callback called when the task is successfully executed
  103503. * @param onError is a callback called if an error occurs
  103504. */
  103505. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  103506. var onload = function () {
  103507. onSuccess();
  103508. };
  103509. var onerror = function (message, exception) {
  103510. onError(message, exception);
  103511. };
  103512. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  103513. };
  103514. return TextureAssetTask;
  103515. }(AbstractAssetTask));
  103516. BABYLON.TextureAssetTask = TextureAssetTask;
  103517. /**
  103518. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  103519. */
  103520. var CubeTextureAssetTask = /** @class */ (function (_super) {
  103521. __extends(CubeTextureAssetTask, _super);
  103522. /**
  103523. * Creates a new CubeTextureAssetTask
  103524. * @param name defines the name of the task
  103525. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  103526. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  103527. * @param noMipmap defines if mipmaps should not be generated (default is false)
  103528. * @param files defines the explicit list of files (undefined by default)
  103529. */
  103530. function CubeTextureAssetTask(
  103531. /**
  103532. * Defines the name of the task
  103533. */
  103534. name,
  103535. /**
  103536. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  103537. */
  103538. url,
  103539. /**
  103540. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  103541. */
  103542. extensions,
  103543. /**
  103544. * Defines if mipmaps should not be generated (default is false)
  103545. */
  103546. noMipmap,
  103547. /**
  103548. * Defines the explicit list of files (undefined by default)
  103549. */
  103550. files) {
  103551. var _this = _super.call(this, name) || this;
  103552. _this.name = name;
  103553. _this.url = url;
  103554. _this.extensions = extensions;
  103555. _this.noMipmap = noMipmap;
  103556. _this.files = files;
  103557. return _this;
  103558. }
  103559. /**
  103560. * Execute the current task
  103561. * @param scene defines the scene where you want your assets to be loaded
  103562. * @param onSuccess is a callback called when the task is successfully executed
  103563. * @param onError is a callback called if an error occurs
  103564. */
  103565. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  103566. var onload = function () {
  103567. onSuccess();
  103568. };
  103569. var onerror = function (message, exception) {
  103570. onError(message, exception);
  103571. };
  103572. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  103573. };
  103574. return CubeTextureAssetTask;
  103575. }(AbstractAssetTask));
  103576. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  103577. /**
  103578. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  103579. */
  103580. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  103581. __extends(HDRCubeTextureAssetTask, _super);
  103582. /**
  103583. * Creates a new HDRCubeTextureAssetTask object
  103584. * @param name defines the name of the task
  103585. * @param url defines the location of the file to load
  103586. * @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.
  103587. * @param noMipmap defines if mipmaps should not be generated (default is false)
  103588. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  103589. * @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)
  103590. * @param reserved Internal use only
  103591. */
  103592. function HDRCubeTextureAssetTask(
  103593. /**
  103594. * Defines the name of the task
  103595. */
  103596. name,
  103597. /**
  103598. * Defines the location of the file to load
  103599. */
  103600. url,
  103601. /**
  103602. * Defines the desired size (the more it increases the longer the generation will be)
  103603. */
  103604. size,
  103605. /**
  103606. * Defines if mipmaps should not be generated (default is false)
  103607. */
  103608. noMipmap,
  103609. /**
  103610. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  103611. */
  103612. generateHarmonics,
  103613. /**
  103614. * 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)
  103615. */
  103616. gammaSpace,
  103617. /**
  103618. * Internal Use Only
  103619. */
  103620. reserved) {
  103621. if (noMipmap === void 0) { noMipmap = false; }
  103622. if (generateHarmonics === void 0) { generateHarmonics = true; }
  103623. if (gammaSpace === void 0) { gammaSpace = false; }
  103624. if (reserved === void 0) { reserved = false; }
  103625. var _this = _super.call(this, name) || this;
  103626. _this.name = name;
  103627. _this.url = url;
  103628. _this.size = size;
  103629. _this.noMipmap = noMipmap;
  103630. _this.generateHarmonics = generateHarmonics;
  103631. _this.gammaSpace = gammaSpace;
  103632. _this.reserved = reserved;
  103633. return _this;
  103634. }
  103635. /**
  103636. * Execute the current task
  103637. * @param scene defines the scene where you want your assets to be loaded
  103638. * @param onSuccess is a callback called when the task is successfully executed
  103639. * @param onError is a callback called if an error occurs
  103640. */
  103641. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  103642. var onload = function () {
  103643. onSuccess();
  103644. };
  103645. var onerror = function (message, exception) {
  103646. onError(message, exception);
  103647. };
  103648. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  103649. };
  103650. return HDRCubeTextureAssetTask;
  103651. }(AbstractAssetTask));
  103652. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  103653. /**
  103654. * This class can be used to easily import assets into a scene
  103655. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  103656. */
  103657. var AssetsManager = /** @class */ (function () {
  103658. /**
  103659. * Creates a new AssetsManager
  103660. * @param scene defines the scene to work on
  103661. */
  103662. function AssetsManager(scene) {
  103663. this._isLoading = false;
  103664. this._tasks = new Array();
  103665. this._waitingTasksCount = 0;
  103666. this._totalTasksCount = 0;
  103667. /**
  103668. * Observable called when all tasks are processed
  103669. */
  103670. this.onTaskSuccessObservable = new BABYLON.Observable();
  103671. /**
  103672. * Observable called when a task had an error
  103673. */
  103674. this.onTaskErrorObservable = new BABYLON.Observable();
  103675. /**
  103676. * Observable called when a task is successful
  103677. */
  103678. this.onTasksDoneObservable = new BABYLON.Observable();
  103679. /**
  103680. * Observable called when a task is done (whatever the result is)
  103681. */
  103682. this.onProgressObservable = new BABYLON.Observable();
  103683. /**
  103684. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  103685. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  103686. */
  103687. this.useDefaultLoadingScreen = true;
  103688. this._scene = scene;
  103689. }
  103690. /**
  103691. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  103692. * @param taskName defines the name of the new task
  103693. * @param meshesNames defines the name of meshes to load
  103694. * @param rootUrl defines the root url to use to locate files
  103695. * @param sceneFilename defines the filename of the scene file
  103696. * @returns a new {BABYLON.MeshAssetTask} object
  103697. */
  103698. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  103699. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  103700. this._tasks.push(task);
  103701. return task;
  103702. };
  103703. /**
  103704. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  103705. * @param taskName defines the name of the new task
  103706. * @param url defines the url of the file to load
  103707. * @returns a new {BABYLON.TextFileAssetTask} object
  103708. */
  103709. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  103710. var task = new TextFileAssetTask(taskName, url);
  103711. this._tasks.push(task);
  103712. return task;
  103713. };
  103714. /**
  103715. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  103716. * @param taskName defines the name of the new task
  103717. * @param url defines the url of the file to load
  103718. * @returns a new {BABYLON.BinaryFileAssetTask} object
  103719. */
  103720. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  103721. var task = new BinaryFileAssetTask(taskName, url);
  103722. this._tasks.push(task);
  103723. return task;
  103724. };
  103725. /**
  103726. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  103727. * @param taskName defines the name of the new task
  103728. * @param url defines the url of the file to load
  103729. * @returns a new {BABYLON.ImageAssetTask} object
  103730. */
  103731. AssetsManager.prototype.addImageTask = function (taskName, url) {
  103732. var task = new ImageAssetTask(taskName, url);
  103733. this._tasks.push(task);
  103734. return task;
  103735. };
  103736. /**
  103737. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  103738. * @param taskName defines the name of the new task
  103739. * @param url defines the url of the file to load
  103740. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  103741. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  103742. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  103743. * @returns a new {BABYLON.TextureAssetTask} object
  103744. */
  103745. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  103746. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  103747. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  103748. this._tasks.push(task);
  103749. return task;
  103750. };
  103751. /**
  103752. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  103753. * @param taskName defines the name of the new task
  103754. * @param url defines the url of the file to load
  103755. * @param extensions defines the extension to use to load the cube map (can be null)
  103756. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  103757. * @param files defines the list of files to load (can be null)
  103758. * @returns a new {BABYLON.CubeTextureAssetTask} object
  103759. */
  103760. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  103761. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  103762. this._tasks.push(task);
  103763. return task;
  103764. };
  103765. /**
  103766. *
  103767. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  103768. * @param taskName defines the name of the new task
  103769. * @param url defines the url of the file to load
  103770. * @param size defines the size you want for the cubemap (can be null)
  103771. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  103772. * @param generateHarmonics defines if you want to automatically generate (true by default)
  103773. * @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)
  103774. * @param reserved Internal use only
  103775. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  103776. */
  103777. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  103778. if (noMipmap === void 0) { noMipmap = false; }
  103779. if (generateHarmonics === void 0) { generateHarmonics = true; }
  103780. if (gammaSpace === void 0) { gammaSpace = false; }
  103781. if (reserved === void 0) { reserved = false; }
  103782. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  103783. this._tasks.push(task);
  103784. return task;
  103785. };
  103786. /**
  103787. * Remove a task from the assets manager.
  103788. * @param task the task to remove
  103789. */
  103790. AssetsManager.prototype.removeTask = function (task) {
  103791. var index = this._tasks.indexOf(task);
  103792. if (index > -1) {
  103793. this._tasks.splice(index, 1);
  103794. }
  103795. };
  103796. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  103797. this._waitingTasksCount--;
  103798. try {
  103799. if (this.onProgress) {
  103800. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  103801. }
  103802. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  103803. }
  103804. catch (e) {
  103805. BABYLON.Tools.Error("Error running progress callbacks.");
  103806. console.log(e);
  103807. }
  103808. if (this._waitingTasksCount === 0) {
  103809. try {
  103810. if (this.onFinish) {
  103811. this.onFinish(this._tasks);
  103812. }
  103813. // Let's remove successfull tasks
  103814. var currentTasks = this._tasks.slice();
  103815. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  103816. var task = currentTasks_1[_i];
  103817. if (task.taskState === AssetTaskState.DONE) {
  103818. var index = this._tasks.indexOf(task);
  103819. if (index > -1) {
  103820. this._tasks.splice(index, 1);
  103821. }
  103822. }
  103823. }
  103824. this.onTasksDoneObservable.notifyObservers(this._tasks);
  103825. }
  103826. catch (e) {
  103827. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  103828. console.log(e);
  103829. }
  103830. this._isLoading = false;
  103831. this._scene.getEngine().hideLoadingUI();
  103832. }
  103833. };
  103834. AssetsManager.prototype._runTask = function (task) {
  103835. var _this = this;
  103836. var done = function () {
  103837. try {
  103838. if (_this.onTaskSuccess) {
  103839. _this.onTaskSuccess(task);
  103840. }
  103841. _this.onTaskSuccessObservable.notifyObservers(task);
  103842. _this._decreaseWaitingTasksCount(task);
  103843. }
  103844. catch (e) {
  103845. error("Error executing task success callbacks", e);
  103846. }
  103847. };
  103848. var error = function (message, exception) {
  103849. task._setErrorObject(message, exception);
  103850. if (_this.onTaskError) {
  103851. _this.onTaskError(task);
  103852. }
  103853. _this.onTaskErrorObservable.notifyObservers(task);
  103854. _this._decreaseWaitingTasksCount(task);
  103855. };
  103856. task.run(this._scene, done, error);
  103857. };
  103858. /**
  103859. * Reset the {BABYLON.AssetsManager} and remove all tasks
  103860. * @return the current instance of the {BABYLON.AssetsManager}
  103861. */
  103862. AssetsManager.prototype.reset = function () {
  103863. this._isLoading = false;
  103864. this._tasks = new Array();
  103865. return this;
  103866. };
  103867. /**
  103868. * Start the loading process
  103869. * @return the current instance of the {BABYLON.AssetsManager}
  103870. */
  103871. AssetsManager.prototype.load = function () {
  103872. if (this._isLoading) {
  103873. return this;
  103874. }
  103875. this._isLoading = true;
  103876. this._waitingTasksCount = this._tasks.length;
  103877. this._totalTasksCount = this._tasks.length;
  103878. if (this._waitingTasksCount === 0) {
  103879. this._isLoading = false;
  103880. if (this.onFinish) {
  103881. this.onFinish(this._tasks);
  103882. }
  103883. this.onTasksDoneObservable.notifyObservers(this._tasks);
  103884. return this;
  103885. }
  103886. if (this.useDefaultLoadingScreen) {
  103887. this._scene.getEngine().displayLoadingUI();
  103888. }
  103889. for (var index = 0; index < this._tasks.length; index++) {
  103890. var task = this._tasks[index];
  103891. if (task.taskState === AssetTaskState.INIT) {
  103892. this._runTask(task);
  103893. }
  103894. }
  103895. return this;
  103896. };
  103897. return AssetsManager;
  103898. }());
  103899. BABYLON.AssetsManager = AssetsManager;
  103900. })(BABYLON || (BABYLON = {}));
  103901. //# sourceMappingURL=babylon.assetsManager.js.map
  103902. var BABYLON;
  103903. (function (BABYLON) {
  103904. var serializedGeometries = [];
  103905. var serializeGeometry = function (geometry, serializationGeometries) {
  103906. if (serializedGeometries[geometry.id]) {
  103907. return;
  103908. }
  103909. if (geometry.doNotSerialize) {
  103910. return;
  103911. }
  103912. if (geometry instanceof BABYLON.BoxGeometry) {
  103913. serializationGeometries.boxes.push(geometry.serialize());
  103914. }
  103915. else if (geometry instanceof BABYLON.SphereGeometry) {
  103916. serializationGeometries.spheres.push(geometry.serialize());
  103917. }
  103918. else if (geometry instanceof BABYLON.CylinderGeometry) {
  103919. serializationGeometries.cylinders.push(geometry.serialize());
  103920. }
  103921. else if (geometry instanceof BABYLON.TorusGeometry) {
  103922. serializationGeometries.toruses.push(geometry.serialize());
  103923. }
  103924. else if (geometry instanceof BABYLON.GroundGeometry) {
  103925. serializationGeometries.grounds.push(geometry.serialize());
  103926. }
  103927. else if (geometry instanceof BABYLON.Plane) {
  103928. serializationGeometries.planes.push(geometry.serialize());
  103929. }
  103930. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  103931. serializationGeometries.torusKnots.push(geometry.serialize());
  103932. }
  103933. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  103934. throw new Error("Unknown primitive type");
  103935. }
  103936. else {
  103937. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  103938. }
  103939. serializedGeometries[geometry.id] = true;
  103940. };
  103941. var serializeMesh = function (mesh, serializationScene) {
  103942. var serializationObject = {};
  103943. // Geometry
  103944. var geometry = mesh._geometry;
  103945. if (geometry) {
  103946. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  103947. // 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
  103948. serializeGeometry(geometry, serializationScene.geometries);
  103949. }
  103950. }
  103951. // Custom
  103952. if (mesh.serialize) {
  103953. mesh.serialize(serializationObject);
  103954. }
  103955. return serializationObject;
  103956. };
  103957. var finalizeSingleMesh = function (mesh, serializationObject) {
  103958. //only works if the mesh is already loaded
  103959. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  103960. //serialize material
  103961. if (mesh.material) {
  103962. if (mesh.material instanceof BABYLON.MultiMaterial) {
  103963. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  103964. serializationObject.materials = serializationObject.materials || [];
  103965. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  103966. serializationObject.multiMaterials.push(mesh.material.serialize());
  103967. var _loop_1 = function (submaterial) {
  103968. if (submaterial) {
  103969. if (!serializationObject.materials.some(function (mat) { return (mat.id === submaterial.id); })) {
  103970. serializationObject.materials.push(submaterial.serialize());
  103971. }
  103972. }
  103973. };
  103974. for (var _i = 0, _a = mesh.material.subMaterials; _i < _a.length; _i++) {
  103975. var submaterial = _a[_i];
  103976. _loop_1(submaterial);
  103977. }
  103978. }
  103979. }
  103980. else {
  103981. serializationObject.materials = serializationObject.materials || [];
  103982. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  103983. serializationObject.materials.push(mesh.material.serialize());
  103984. }
  103985. }
  103986. }
  103987. //serialize geometry
  103988. var geometry = mesh._geometry;
  103989. if (geometry) {
  103990. if (!serializationObject.geometries) {
  103991. serializationObject.geometries = {};
  103992. serializationObject.geometries.boxes = [];
  103993. serializationObject.geometries.spheres = [];
  103994. serializationObject.geometries.cylinders = [];
  103995. serializationObject.geometries.toruses = [];
  103996. serializationObject.geometries.grounds = [];
  103997. serializationObject.geometries.planes = [];
  103998. serializationObject.geometries.torusKnots = [];
  103999. serializationObject.geometries.vertexData = [];
  104000. }
  104001. serializeGeometry(geometry, serializationObject.geometries);
  104002. }
  104003. // Skeletons
  104004. if (mesh.skeleton) {
  104005. serializationObject.skeletons = serializationObject.skeletons || [];
  104006. serializationObject.skeletons.push(mesh.skeleton.serialize());
  104007. }
  104008. //serialize the actual mesh
  104009. serializationObject.meshes = serializationObject.meshes || [];
  104010. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  104011. }
  104012. };
  104013. var SceneSerializer = /** @class */ (function () {
  104014. function SceneSerializer() {
  104015. }
  104016. SceneSerializer.ClearCache = function () {
  104017. serializedGeometries = [];
  104018. };
  104019. SceneSerializer.Serialize = function (scene) {
  104020. var serializationObject = {};
  104021. SceneSerializer.ClearCache();
  104022. // Scene
  104023. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  104024. serializationObject.autoClear = scene.autoClear;
  104025. serializationObject.clearColor = scene.clearColor.asArray();
  104026. serializationObject.ambientColor = scene.ambientColor.asArray();
  104027. serializationObject.gravity = scene.gravity.asArray();
  104028. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  104029. serializationObject.workerCollisions = scene.workerCollisions;
  104030. // Fog
  104031. if (scene.fogMode && scene.fogMode !== 0) {
  104032. serializationObject.fogMode = scene.fogMode;
  104033. serializationObject.fogColor = scene.fogColor.asArray();
  104034. serializationObject.fogStart = scene.fogStart;
  104035. serializationObject.fogEnd = scene.fogEnd;
  104036. serializationObject.fogDensity = scene.fogDensity;
  104037. }
  104038. //Physics
  104039. if (scene.isPhysicsEnabled()) {
  104040. var physicEngine = scene.getPhysicsEngine();
  104041. if (physicEngine) {
  104042. serializationObject.physicsEnabled = true;
  104043. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  104044. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  104045. }
  104046. }
  104047. // Metadata
  104048. if (scene.metadata) {
  104049. serializationObject.metadata = scene.metadata;
  104050. }
  104051. // Morph targets
  104052. serializationObject.morphTargetManagers = [];
  104053. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  104054. var abstractMesh = _a[_i];
  104055. var manager = abstractMesh.morphTargetManager;
  104056. if (manager) {
  104057. serializationObject.morphTargetManagers.push(manager.serialize());
  104058. }
  104059. }
  104060. // Lights
  104061. serializationObject.lights = [];
  104062. var index;
  104063. var light;
  104064. for (index = 0; index < scene.lights.length; index++) {
  104065. light = scene.lights[index];
  104066. if (!light.doNotSerialize) {
  104067. serializationObject.lights.push(light.serialize());
  104068. }
  104069. }
  104070. // Cameras
  104071. serializationObject.cameras = [];
  104072. for (index = 0; index < scene.cameras.length; index++) {
  104073. var camera = scene.cameras[index];
  104074. if (!camera.doNotSerialize) {
  104075. serializationObject.cameras.push(camera.serialize());
  104076. }
  104077. }
  104078. if (scene.activeCamera) {
  104079. serializationObject.activeCameraID = scene.activeCamera.id;
  104080. }
  104081. // Animations
  104082. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  104083. // Materials
  104084. serializationObject.materials = [];
  104085. serializationObject.multiMaterials = [];
  104086. var material;
  104087. for (index = 0; index < scene.materials.length; index++) {
  104088. material = scene.materials[index];
  104089. if (!material.doNotSerialize) {
  104090. serializationObject.materials.push(material.serialize());
  104091. }
  104092. }
  104093. // MultiMaterials
  104094. serializationObject.multiMaterials = [];
  104095. for (index = 0; index < scene.multiMaterials.length; index++) {
  104096. var multiMaterial = scene.multiMaterials[index];
  104097. serializationObject.multiMaterials.push(multiMaterial.serialize());
  104098. }
  104099. // Environment texture
  104100. if (scene.environmentTexture) {
  104101. serializationObject.environmentTexture = scene.environmentTexture.name;
  104102. }
  104103. // Skeletons
  104104. serializationObject.skeletons = [];
  104105. for (index = 0; index < scene.skeletons.length; index++) {
  104106. var skeleton = scene.skeletons[index];
  104107. if (!skeleton.doNotSerialize) {
  104108. serializationObject.skeletons.push(skeleton.serialize());
  104109. }
  104110. }
  104111. // Transform nodes
  104112. serializationObject.transformNodes = [];
  104113. for (index = 0; index < scene.transformNodes.length; index++) {
  104114. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  104115. }
  104116. // Geometries
  104117. serializationObject.geometries = {};
  104118. serializationObject.geometries.boxes = [];
  104119. serializationObject.geometries.spheres = [];
  104120. serializationObject.geometries.cylinders = [];
  104121. serializationObject.geometries.toruses = [];
  104122. serializationObject.geometries.grounds = [];
  104123. serializationObject.geometries.planes = [];
  104124. serializationObject.geometries.torusKnots = [];
  104125. serializationObject.geometries.vertexData = [];
  104126. serializedGeometries = [];
  104127. var geometries = scene.getGeometries();
  104128. for (index = 0; index < geometries.length; index++) {
  104129. var geometry = geometries[index];
  104130. if (geometry.isReady()) {
  104131. serializeGeometry(geometry, serializationObject.geometries);
  104132. }
  104133. }
  104134. // Meshes
  104135. serializationObject.meshes = [];
  104136. for (index = 0; index < scene.meshes.length; index++) {
  104137. var abstractMesh = scene.meshes[index];
  104138. if (abstractMesh instanceof BABYLON.Mesh) {
  104139. var mesh = abstractMesh;
  104140. if (!mesh.doNotSerialize) {
  104141. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  104142. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  104143. }
  104144. }
  104145. }
  104146. }
  104147. // Particles Systems
  104148. serializationObject.particleSystems = [];
  104149. for (index = 0; index < scene.particleSystems.length; index++) {
  104150. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  104151. }
  104152. // Action Manager
  104153. if (scene.actionManager) {
  104154. serializationObject.actions = scene.actionManager.serialize("scene");
  104155. }
  104156. // Audio
  104157. serializationObject.sounds = [];
  104158. for (index = 0; index < scene.soundTracks.length; index++) {
  104159. var soundtrack = scene.soundTracks[index];
  104160. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  104161. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  104162. }
  104163. }
  104164. // Components
  104165. for (var _b = 0, _c = scene._serializableComponents; _b < _c.length; _b++) {
  104166. var component = _c[_b];
  104167. component.serialize(serializationObject);
  104168. }
  104169. return serializationObject;
  104170. };
  104171. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  104172. if (withParents === void 0) { withParents = false; }
  104173. if (withChildren === void 0) { withChildren = false; }
  104174. var serializationObject = {};
  104175. SceneSerializer.ClearCache();
  104176. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  104177. if (withParents || withChildren) {
  104178. //deliberate for loop! not for each, appended should be processed as well.
  104179. for (var i = 0; i < toSerialize.length; ++i) {
  104180. if (withChildren) {
  104181. toSerialize[i].getDescendants().forEach(function (node) {
  104182. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  104183. toSerialize.push(node);
  104184. }
  104185. });
  104186. }
  104187. //make sure the array doesn't contain the object already
  104188. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  104189. toSerialize.push(toSerialize[i].parent);
  104190. }
  104191. }
  104192. }
  104193. toSerialize.forEach(function (mesh) {
  104194. finalizeSingleMesh(mesh, serializationObject);
  104195. });
  104196. return serializationObject;
  104197. };
  104198. return SceneSerializer;
  104199. }());
  104200. BABYLON.SceneSerializer = SceneSerializer;
  104201. })(BABYLON || (BABYLON = {}));
  104202. //# sourceMappingURL=babylon.sceneSerializer.js.map
  104203. var BABYLON;
  104204. (function (BABYLON) {
  104205. /**
  104206. * Class used to generate realtime reflection / refraction cube textures
  104207. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  104208. */
  104209. var ReflectionProbe = /** @class */ (function () {
  104210. /**
  104211. * Creates a new reflection probe
  104212. * @param name defines the name of the probe
  104213. * @param size defines the texture resolution (for each face)
  104214. * @param scene defines the hosting scene
  104215. * @param generateMipMaps defines if mip maps should be generated automatically (true by default)
  104216. * @param useFloat defines if HDR data (flaot data) should be used to store colors (false by default)
  104217. */
  104218. function ReflectionProbe(
  104219. /** defines the name of the probe */
  104220. name, size, scene, generateMipMaps, useFloat) {
  104221. if (generateMipMaps === void 0) { generateMipMaps = true; }
  104222. if (useFloat === void 0) { useFloat = false; }
  104223. var _this = this;
  104224. this.name = name;
  104225. this._viewMatrix = BABYLON.Matrix.Identity();
  104226. this._target = BABYLON.Vector3.Zero();
  104227. this._add = BABYLON.Vector3.Zero();
  104228. this._invertYAxis = false;
  104229. /** Gets or sets probe position (center of the cube map) */
  104230. this.position = BABYLON.Vector3.Zero();
  104231. this._scene = scene;
  104232. // Create the scene field if not exist.
  104233. if (!this._scene.reflectionProbes) {
  104234. this._scene.reflectionProbes = new Array();
  104235. }
  104236. this._scene.reflectionProbes.push(this);
  104237. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, useFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  104238. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  104239. switch (faceIndex) {
  104240. case 0:
  104241. _this._add.copyFromFloats(1, 0, 0);
  104242. break;
  104243. case 1:
  104244. _this._add.copyFromFloats(-1, 0, 0);
  104245. break;
  104246. case 2:
  104247. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  104248. break;
  104249. case 3:
  104250. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  104251. break;
  104252. case 4:
  104253. _this._add.copyFromFloats(0, 0, 1);
  104254. break;
  104255. case 5:
  104256. _this._add.copyFromFloats(0, 0, -1);
  104257. break;
  104258. }
  104259. if (_this._attachedMesh) {
  104260. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  104261. }
  104262. _this.position.addToRef(_this._add, _this._target);
  104263. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  104264. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  104265. scene._forcedViewPosition = _this.position;
  104266. });
  104267. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  104268. scene._forcedViewPosition = null;
  104269. scene.updateTransformMatrix(true);
  104270. });
  104271. if (scene.activeCamera) {
  104272. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  104273. }
  104274. }
  104275. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  104276. /** Gets or sets the number of samples to use for multi-sampling (0 by default). Required WebGL2 */
  104277. get: function () {
  104278. return this._renderTargetTexture.samples;
  104279. },
  104280. set: function (value) {
  104281. this._renderTargetTexture.samples = value;
  104282. },
  104283. enumerable: true,
  104284. configurable: true
  104285. });
  104286. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  104287. /** Gets or sets the refresh rate to use (on every frame by default) */
  104288. get: function () {
  104289. return this._renderTargetTexture.refreshRate;
  104290. },
  104291. set: function (value) {
  104292. this._renderTargetTexture.refreshRate = value;
  104293. },
  104294. enumerable: true,
  104295. configurable: true
  104296. });
  104297. /**
  104298. * Gets the hosting scene
  104299. * @returns a Scene
  104300. */
  104301. ReflectionProbe.prototype.getScene = function () {
  104302. return this._scene;
  104303. };
  104304. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  104305. /** Gets the internal CubeTexture used to render to */
  104306. get: function () {
  104307. return this._renderTargetTexture;
  104308. },
  104309. enumerable: true,
  104310. configurable: true
  104311. });
  104312. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  104313. /** Gets the list of meshes to render */
  104314. get: function () {
  104315. return this._renderTargetTexture.renderList;
  104316. },
  104317. enumerable: true,
  104318. configurable: true
  104319. });
  104320. /**
  104321. * Attach the probe to a specific mesh (Rendering will be done from attached mesh's position)
  104322. * @param mesh defines the mesh to attach to
  104323. */
  104324. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  104325. this._attachedMesh = mesh;
  104326. };
  104327. /**
  104328. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups
  104329. * @param renderingGroupId The rendering group id corresponding to its index
  104330. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  104331. */
  104332. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  104333. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  104334. };
  104335. /**
  104336. * Clean all associated resources
  104337. */
  104338. ReflectionProbe.prototype.dispose = function () {
  104339. var index = this._scene.reflectionProbes.indexOf(this);
  104340. if (index !== -1) {
  104341. // Remove from the scene if found
  104342. this._scene.reflectionProbes.splice(index, 1);
  104343. }
  104344. if (this._renderTargetTexture) {
  104345. this._renderTargetTexture.dispose();
  104346. this._renderTargetTexture = null;
  104347. }
  104348. };
  104349. return ReflectionProbe;
  104350. }());
  104351. BABYLON.ReflectionProbe = ReflectionProbe;
  104352. })(BABYLON || (BABYLON = {}));
  104353. //# sourceMappingURL=babylon.reflectionProbe.js.map
  104354. var BABYLON;
  104355. (function (BABYLON) {
  104356. /**
  104357. * Defines the layer scene component responsible to manage any layers
  104358. * in a given scene.
  104359. */
  104360. var LayerSceneComponent = /** @class */ (function () {
  104361. /**
  104362. * Creates a new instance of the component for the given scene
  104363. * @param scene Defines the scene to register the component in
  104364. */
  104365. function LayerSceneComponent(scene) {
  104366. /**
  104367. * The component name helpfull to identify the component in the list of scene components.
  104368. */
  104369. this.name = BABYLON.SceneComponentConstants.NAME_LAYER;
  104370. this.scene = scene;
  104371. this._engine = scene.getEngine();
  104372. scene.layers = new Array();
  104373. }
  104374. /**
  104375. * Registers the component in a given scene
  104376. */
  104377. LayerSceneComponent.prototype.register = function () {
  104378. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER, this, this._drawBackground);
  104379. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER, this, this._drawForeground);
  104380. };
  104381. /**
  104382. * Rebuilds the elements related to this component in case of
  104383. * context lost for instance.
  104384. */
  104385. LayerSceneComponent.prototype.rebuild = function () {
  104386. var layers = this.scene.layers;
  104387. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  104388. var layer = layers_1[_i];
  104389. layer._rebuild();
  104390. }
  104391. };
  104392. /**
  104393. * Disposes the component and the associated ressources.
  104394. */
  104395. LayerSceneComponent.prototype.dispose = function () {
  104396. var layers = this.scene.layers;
  104397. while (layers.length) {
  104398. layers[0].dispose();
  104399. }
  104400. };
  104401. LayerSceneComponent.prototype._draw = function (camera, isBackground) {
  104402. var layers = this.scene.layers;
  104403. if (layers.length) {
  104404. this._engine.setDepthBuffer(false);
  104405. var cameraLayerMask = camera.layerMask;
  104406. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  104407. var layer = layers_2[_i];
  104408. if (layer.isBackground === isBackground && ((layer.layerMask & cameraLayerMask) !== 0)) {
  104409. layer.render();
  104410. }
  104411. }
  104412. this._engine.setDepthBuffer(true);
  104413. }
  104414. };
  104415. LayerSceneComponent.prototype._drawBackground = function (camera) {
  104416. this._draw(camera, true);
  104417. };
  104418. LayerSceneComponent.prototype._drawForeground = function (camera) {
  104419. this._draw(camera, false);
  104420. };
  104421. return LayerSceneComponent;
  104422. }());
  104423. BABYLON.LayerSceneComponent = LayerSceneComponent;
  104424. })(BABYLON || (BABYLON = {}));
  104425. //# sourceMappingURL=babylon.layerSceneComponent.js.map
  104426. var BABYLON;
  104427. (function (BABYLON) {
  104428. var Layer = /** @class */ (function () {
  104429. function Layer(name, imgUrl, scene, isBackground, color) {
  104430. this.name = name;
  104431. this.scale = new BABYLON.Vector2(1, 1);
  104432. this.offset = new BABYLON.Vector2(0, 0);
  104433. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  104434. this.layerMask = 0x0FFFFFFF;
  104435. this._vertexBuffers = {};
  104436. // Events
  104437. /**
  104438. * An event triggered when the layer is disposed.
  104439. */
  104440. this.onDisposeObservable = new BABYLON.Observable();
  104441. /**
  104442. * An event triggered before rendering the scene
  104443. */
  104444. this.onBeforeRenderObservable = new BABYLON.Observable();
  104445. /**
  104446. * An event triggered after rendering the scene
  104447. */
  104448. this.onAfterRenderObservable = new BABYLON.Observable();
  104449. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  104450. this.isBackground = isBackground === undefined ? true : isBackground;
  104451. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  104452. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  104453. var layerComponent = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LAYER);
  104454. if (!layerComponent) {
  104455. layerComponent = new BABYLON.LayerSceneComponent(this._scene);
  104456. this._scene._addComponent(layerComponent);
  104457. }
  104458. this._scene.layers.push(this);
  104459. var engine = this._scene.getEngine();
  104460. // VBO
  104461. var vertices = [];
  104462. vertices.push(1, 1);
  104463. vertices.push(-1, 1);
  104464. vertices.push(-1, -1);
  104465. vertices.push(1, -1);
  104466. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  104467. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  104468. this._createIndexBuffer();
  104469. // Effects
  104470. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  104471. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  104472. }
  104473. Object.defineProperty(Layer.prototype, "onDispose", {
  104474. set: function (callback) {
  104475. if (this._onDisposeObserver) {
  104476. this.onDisposeObservable.remove(this._onDisposeObserver);
  104477. }
  104478. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  104479. },
  104480. enumerable: true,
  104481. configurable: true
  104482. });
  104483. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  104484. set: function (callback) {
  104485. if (this._onBeforeRenderObserver) {
  104486. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  104487. }
  104488. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  104489. },
  104490. enumerable: true,
  104491. configurable: true
  104492. });
  104493. Object.defineProperty(Layer.prototype, "onAfterRender", {
  104494. set: function (callback) {
  104495. if (this._onAfterRenderObserver) {
  104496. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  104497. }
  104498. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  104499. },
  104500. enumerable: true,
  104501. configurable: true
  104502. });
  104503. Layer.prototype._createIndexBuffer = function () {
  104504. var engine = this._scene.getEngine();
  104505. // Indices
  104506. var indices = [];
  104507. indices.push(0);
  104508. indices.push(1);
  104509. indices.push(2);
  104510. indices.push(0);
  104511. indices.push(2);
  104512. indices.push(3);
  104513. this._indexBuffer = engine.createIndexBuffer(indices);
  104514. };
  104515. /** @hidden */
  104516. Layer.prototype._rebuild = function () {
  104517. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  104518. if (vb) {
  104519. vb._rebuild();
  104520. }
  104521. this._createIndexBuffer();
  104522. };
  104523. Layer.prototype.render = function () {
  104524. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  104525. // Check
  104526. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  104527. return;
  104528. var engine = this._scene.getEngine();
  104529. this.onBeforeRenderObservable.notifyObservers(this);
  104530. // Render
  104531. engine.enableEffect(currentEffect);
  104532. engine.setState(false);
  104533. // Texture
  104534. currentEffect.setTexture("textureSampler", this.texture);
  104535. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  104536. // Color
  104537. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  104538. // Scale / offset
  104539. currentEffect.setVector2("offset", this.offset);
  104540. currentEffect.setVector2("scale", this.scale);
  104541. // VBOs
  104542. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  104543. // Draw order
  104544. if (!this.alphaTest) {
  104545. engine.setAlphaMode(this.alphaBlendingMode);
  104546. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  104547. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  104548. }
  104549. else {
  104550. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  104551. }
  104552. this.onAfterRenderObservable.notifyObservers(this);
  104553. };
  104554. Layer.prototype.dispose = function () {
  104555. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  104556. if (vertexBuffer) {
  104557. vertexBuffer.dispose();
  104558. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  104559. }
  104560. if (this._indexBuffer) {
  104561. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  104562. this._indexBuffer = null;
  104563. }
  104564. if (this.texture) {
  104565. this.texture.dispose();
  104566. this.texture = null;
  104567. }
  104568. // Remove from scene
  104569. var index = this._scene.layers.indexOf(this);
  104570. this._scene.layers.splice(index, 1);
  104571. // Callback
  104572. this.onDisposeObservable.notifyObservers(this);
  104573. this.onDisposeObservable.clear();
  104574. this.onAfterRenderObservable.clear();
  104575. this.onBeforeRenderObservable.clear();
  104576. };
  104577. return Layer;
  104578. }());
  104579. BABYLON.Layer = Layer;
  104580. })(BABYLON || (BABYLON = {}));
  104581. //# sourceMappingURL=babylon.layer.js.map
  104582. var BABYLON;
  104583. (function (BABYLON) {
  104584. var TextureTools = /** @class */ (function () {
  104585. function TextureTools() {
  104586. }
  104587. /**
  104588. * Uses the GPU to create a copy texture rescaled at a given size
  104589. * @param texture Texture to copy from
  104590. * @param width Desired width
  104591. * @param height Desired height
  104592. * @return Generated texture
  104593. */
  104594. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  104595. if (useBilinearMode === void 0) { useBilinearMode = true; }
  104596. var scene = texture.getScene();
  104597. var engine = scene.getEngine();
  104598. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  104599. rtt.wrapU = texture.wrapU;
  104600. rtt.wrapV = texture.wrapV;
  104601. rtt.uOffset = texture.uOffset;
  104602. rtt.vOffset = texture.vOffset;
  104603. rtt.uScale = texture.uScale;
  104604. rtt.vScale = texture.vScale;
  104605. rtt.uAng = texture.uAng;
  104606. rtt.vAng = texture.vAng;
  104607. rtt.wAng = texture.wAng;
  104608. rtt.coordinatesIndex = texture.coordinatesIndex;
  104609. rtt.level = texture.level;
  104610. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  104611. rtt._texture.isReady = false;
  104612. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  104613. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  104614. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  104615. passPostProcess.getEffect().executeWhenCompiled(function () {
  104616. passPostProcess.onApply = function (effect) {
  104617. effect.setTexture("textureSampler", texture);
  104618. };
  104619. var internalTexture = rtt.getInternalTexture();
  104620. if (internalTexture) {
  104621. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  104622. engine.unBindFramebuffer(internalTexture);
  104623. rtt.disposeFramebufferObjects();
  104624. passPostProcess.dispose();
  104625. internalTexture.isReady = true;
  104626. }
  104627. });
  104628. return rtt;
  104629. };
  104630. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  104631. if (!scene._environmentBRDFTexture) {
  104632. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  104633. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  104634. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  104635. scene._environmentBRDFTexture = texture;
  104636. }
  104637. return scene._environmentBRDFTexture;
  104638. };
  104639. 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=";
  104640. return TextureTools;
  104641. }());
  104642. BABYLON.TextureTools = TextureTools;
  104643. })(BABYLON || (BABYLON = {}));
  104644. //# sourceMappingURL=babylon.textureTools.js.map
  104645. var BABYLON;
  104646. (function (BABYLON) {
  104647. var FramingBehavior = /** @class */ (function () {
  104648. function FramingBehavior() {
  104649. this._mode = FramingBehavior.FitFrustumSidesMode;
  104650. this._radiusScale = 1.0;
  104651. this._positionScale = 0.5;
  104652. this._defaultElevation = 0.3;
  104653. this._elevationReturnTime = 1500;
  104654. this._elevationReturnWaitTime = 1000;
  104655. this._zoomStopsAnimation = false;
  104656. this._framingTime = 1500;
  104657. this._isPointerDown = false;
  104658. this._lastInteractionTime = -Infinity;
  104659. // Framing control
  104660. this._animatables = new Array();
  104661. this._betaIsAnimating = false;
  104662. }
  104663. Object.defineProperty(FramingBehavior.prototype, "name", {
  104664. get: function () {
  104665. return "Framing";
  104666. },
  104667. enumerable: true,
  104668. configurable: true
  104669. });
  104670. Object.defineProperty(FramingBehavior.prototype, "mode", {
  104671. /**
  104672. * Gets current mode used by the behavior.
  104673. */
  104674. get: function () {
  104675. return this._mode;
  104676. },
  104677. /**
  104678. * Sets the current mode used by the behavior
  104679. */
  104680. set: function (mode) {
  104681. this._mode = mode;
  104682. },
  104683. enumerable: true,
  104684. configurable: true
  104685. });
  104686. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  104687. /**
  104688. * Gets the scale applied to the radius
  104689. */
  104690. get: function () {
  104691. return this._radiusScale;
  104692. },
  104693. /**
  104694. * Sets the scale applied to the radius (1 by default)
  104695. */
  104696. set: function (radius) {
  104697. this._radiusScale = radius;
  104698. },
  104699. enumerable: true,
  104700. configurable: true
  104701. });
  104702. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  104703. /**
  104704. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  104705. */
  104706. get: function () {
  104707. return this._positionScale;
  104708. },
  104709. /**
  104710. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  104711. */
  104712. set: function (scale) {
  104713. this._positionScale = scale;
  104714. },
  104715. enumerable: true,
  104716. configurable: true
  104717. });
  104718. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  104719. /**
  104720. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  104721. * behaviour is triggered, in radians.
  104722. */
  104723. get: function () {
  104724. return this._defaultElevation;
  104725. },
  104726. /**
  104727. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  104728. * behaviour is triggered, in radians.
  104729. */
  104730. set: function (elevation) {
  104731. this._defaultElevation = elevation;
  104732. },
  104733. enumerable: true,
  104734. configurable: true
  104735. });
  104736. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  104737. /**
  104738. * Gets the time (in milliseconds) taken to return to the default beta position.
  104739. * Negative value indicates camera should not return to default.
  104740. */
  104741. get: function () {
  104742. return this._elevationReturnTime;
  104743. },
  104744. /**
  104745. * Sets the time (in milliseconds) taken to return to the default beta position.
  104746. * Negative value indicates camera should not return to default.
  104747. */
  104748. set: function (speed) {
  104749. this._elevationReturnTime = speed;
  104750. },
  104751. enumerable: true,
  104752. configurable: true
  104753. });
  104754. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  104755. /**
  104756. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  104757. */
  104758. get: function () {
  104759. return this._elevationReturnWaitTime;
  104760. },
  104761. /**
  104762. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  104763. */
  104764. set: function (time) {
  104765. this._elevationReturnWaitTime = time;
  104766. },
  104767. enumerable: true,
  104768. configurable: true
  104769. });
  104770. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  104771. /**
  104772. * Gets the flag that indicates if user zooming should stop animation.
  104773. */
  104774. get: function () {
  104775. return this._zoomStopsAnimation;
  104776. },
  104777. /**
  104778. * Sets the flag that indicates if user zooming should stop animation.
  104779. */
  104780. set: function (flag) {
  104781. this._zoomStopsAnimation = flag;
  104782. },
  104783. enumerable: true,
  104784. configurable: true
  104785. });
  104786. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  104787. /**
  104788. * Gets the transition time when framing the mesh, in milliseconds
  104789. */
  104790. get: function () {
  104791. return this._framingTime;
  104792. },
  104793. /**
  104794. * Sets the transition time when framing the mesh, in milliseconds
  104795. */
  104796. set: function (time) {
  104797. this._framingTime = time;
  104798. },
  104799. enumerable: true,
  104800. configurable: true
  104801. });
  104802. FramingBehavior.prototype.init = function () {
  104803. // Do notihng
  104804. };
  104805. FramingBehavior.prototype.attach = function (camera) {
  104806. var _this = this;
  104807. this._attachedCamera = camera;
  104808. var scene = this._attachedCamera.getScene();
  104809. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  104810. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  104811. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  104812. _this._isPointerDown = true;
  104813. return;
  104814. }
  104815. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  104816. _this._isPointerDown = false;
  104817. }
  104818. });
  104819. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  104820. if (mesh) {
  104821. _this.zoomOnMesh(mesh);
  104822. }
  104823. });
  104824. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  104825. // Stop the animation if there is user interaction and the animation should stop for this interaction
  104826. _this._applyUserInteraction();
  104827. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  104828. // back to the default position after a given timeout
  104829. _this._maintainCameraAboveGround();
  104830. });
  104831. };
  104832. FramingBehavior.prototype.detach = function () {
  104833. if (!this._attachedCamera) {
  104834. return;
  104835. }
  104836. var scene = this._attachedCamera.getScene();
  104837. if (this._onPrePointerObservableObserver) {
  104838. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  104839. }
  104840. if (this._onAfterCheckInputsObserver) {
  104841. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  104842. }
  104843. if (this._onMeshTargetChangedObserver) {
  104844. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  104845. }
  104846. this._attachedCamera = null;
  104847. };
  104848. /**
  104849. * Targets the given mesh and updates zoom level accordingly.
  104850. * @param mesh The mesh to target.
  104851. * @param radius Optional. If a cached radius position already exists, overrides default.
  104852. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  104853. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  104854. * @param onAnimationEnd Callback triggered at the end of the framing animation
  104855. */
  104856. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  104857. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  104858. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  104859. mesh.computeWorldMatrix(true);
  104860. var boundingBox = mesh.getBoundingInfo().boundingBox;
  104861. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  104862. };
  104863. /**
  104864. * Targets the given mesh with its children and updates zoom level accordingly.
  104865. * @param mesh The mesh to target.
  104866. * @param radius Optional. If a cached radius position already exists, overrides default.
  104867. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  104868. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  104869. * @param onAnimationEnd Callback triggered at the end of the framing animation
  104870. */
  104871. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  104872. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  104873. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  104874. mesh.computeWorldMatrix(true);
  104875. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  104876. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  104877. };
  104878. /**
  104879. * Targets the given meshes with their children and updates zoom level accordingly.
  104880. * @param meshes The mesh to target.
  104881. * @param radius Optional. If a cached radius position already exists, overrides default.
  104882. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  104883. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  104884. * @param onAnimationEnd Callback triggered at the end of the framing animation
  104885. */
  104886. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  104887. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  104888. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  104889. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  104890. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  104891. for (var i = 0; i < meshes.length; i++) {
  104892. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  104893. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  104894. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  104895. }
  104896. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  104897. };
  104898. /**
  104899. * Targets the given mesh and updates zoom level accordingly.
  104900. * @param mesh The mesh to target.
  104901. * @param radius Optional. If a cached radius position already exists, overrides default.
  104902. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  104903. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  104904. * @param onAnimationEnd Callback triggered at the end of the framing animation
  104905. */
  104906. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  104907. var _this = this;
  104908. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  104909. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  104910. var zoomTarget;
  104911. if (!this._attachedCamera) {
  104912. return;
  104913. }
  104914. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  104915. var bottom = minimumWorld.y;
  104916. var top = maximumWorld.y;
  104917. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  104918. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  104919. if (focusOnOriginXZ) {
  104920. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  104921. }
  104922. else {
  104923. var centerWorld = minimumWorld.add(radiusWorld);
  104924. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  104925. }
  104926. if (!this._vectorTransition) {
  104927. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  104928. }
  104929. this._betaIsAnimating = true;
  104930. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  104931. if (animatable) {
  104932. this._animatables.push(animatable);
  104933. }
  104934. // sets the radius and lower radius bounds
  104935. // Small delta ensures camera is not always at lower zoom limit.
  104936. var radius = 0;
  104937. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  104938. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  104939. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  104940. radius = position;
  104941. }
  104942. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  104943. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  104944. if (this._attachedCamera.lowerRadiusLimit === null) {
  104945. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  104946. }
  104947. }
  104948. // Set sensibilities
  104949. var extend = maximumWorld.subtract(minimumWorld).length();
  104950. this._attachedCamera.panningSensibility = 5000 / extend;
  104951. this._attachedCamera.wheelPrecision = 100 / radius;
  104952. // transition to new radius
  104953. if (!this._radiusTransition) {
  104954. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  104955. }
  104956. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  104957. _this.stopAllAnimations();
  104958. if (onAnimationEnd) {
  104959. onAnimationEnd();
  104960. }
  104961. if (_this._attachedCamera) {
  104962. _this._attachedCamera.storeState();
  104963. }
  104964. });
  104965. if (animatable) {
  104966. this._animatables.push(animatable);
  104967. }
  104968. };
  104969. /**
  104970. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  104971. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  104972. * frustum width.
  104973. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  104974. * to fully enclose the mesh in the viewing frustum.
  104975. */
  104976. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  104977. var size = maximumWorld.subtract(minimumWorld);
  104978. var boxVectorGlobalDiagonal = size.length();
  104979. var frustumSlope = this._getFrustumSlope();
  104980. // Formula for setting distance
  104981. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  104982. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  104983. // Horizon distance
  104984. var radius = radiusWithoutFraming * this._radiusScale;
  104985. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  104986. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  104987. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  104988. var camera = this._attachedCamera;
  104989. if (!camera) {
  104990. return 0;
  104991. }
  104992. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  104993. // Don't exceed the requested limit
  104994. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  104995. }
  104996. // Don't exceed the upper radius limit
  104997. if (camera.upperRadiusLimit) {
  104998. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  104999. }
  105000. return distance;
  105001. };
  105002. /**
  105003. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  105004. * is automatically returned to its default position (expected to be above ground plane).
  105005. */
  105006. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  105007. var _this = this;
  105008. if (this._elevationReturnTime < 0) {
  105009. return;
  105010. }
  105011. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  105012. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  105013. var limitBeta = Math.PI * 0.5;
  105014. // Bring the camera back up if below the ground plane
  105015. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  105016. this._betaIsAnimating = true;
  105017. //Transition to new position
  105018. this.stopAllAnimations();
  105019. if (!this._betaTransition) {
  105020. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  105021. }
  105022. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  105023. _this._clearAnimationLocks();
  105024. _this.stopAllAnimations();
  105025. });
  105026. if (animatabe) {
  105027. this._animatables.push(animatabe);
  105028. }
  105029. }
  105030. };
  105031. /**
  105032. * Returns the frustum slope based on the canvas ratio and camera FOV
  105033. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  105034. */
  105035. FramingBehavior.prototype._getFrustumSlope = function () {
  105036. // Calculate the viewport ratio
  105037. // Aspect Ratio is Height/Width.
  105038. var camera = this._attachedCamera;
  105039. if (!camera) {
  105040. return BABYLON.Vector2.Zero();
  105041. }
  105042. var engine = camera.getScene().getEngine();
  105043. var aspectRatio = engine.getAspectRatio(camera);
  105044. // Camera FOV is the vertical field of view (top-bottom) in radians.
  105045. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  105046. var frustumSlopeY = Math.tan(camera.fov / 2);
  105047. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  105048. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  105049. // along the forward vector.
  105050. var frustumSlopeX = frustumSlopeY * aspectRatio;
  105051. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  105052. };
  105053. /**
  105054. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  105055. */
  105056. FramingBehavior.prototype._clearAnimationLocks = function () {
  105057. this._betaIsAnimating = false;
  105058. };
  105059. /**
  105060. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  105061. */
  105062. FramingBehavior.prototype._applyUserInteraction = function () {
  105063. if (this.isUserIsMoving) {
  105064. this._lastInteractionTime = BABYLON.Tools.Now;
  105065. this.stopAllAnimations();
  105066. this._clearAnimationLocks();
  105067. }
  105068. };
  105069. /**
  105070. * Stops and removes all animations that have been applied to the camera
  105071. */
  105072. FramingBehavior.prototype.stopAllAnimations = function () {
  105073. if (this._attachedCamera) {
  105074. this._attachedCamera.animations = [];
  105075. }
  105076. while (this._animatables.length) {
  105077. if (this._animatables[0]) {
  105078. this._animatables[0].onAnimationEnd = null;
  105079. this._animatables[0].stop();
  105080. }
  105081. this._animatables.shift();
  105082. }
  105083. };
  105084. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  105085. /**
  105086. * Gets a value indicating if the user is moving the camera
  105087. */
  105088. get: function () {
  105089. if (!this._attachedCamera) {
  105090. return false;
  105091. }
  105092. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  105093. this._attachedCamera.inertialBetaOffset !== 0 ||
  105094. this._attachedCamera.inertialRadiusOffset !== 0 ||
  105095. this._attachedCamera.inertialPanningX !== 0 ||
  105096. this._attachedCamera.inertialPanningY !== 0 ||
  105097. this._isPointerDown;
  105098. },
  105099. enumerable: true,
  105100. configurable: true
  105101. });
  105102. /**
  105103. * The easing function used by animations
  105104. */
  105105. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  105106. /**
  105107. * The easing mode used by animations
  105108. */
  105109. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  105110. // Statics
  105111. /**
  105112. * The camera can move all the way towards the mesh.
  105113. */
  105114. FramingBehavior.IgnoreBoundsSizeMode = 0;
  105115. /**
  105116. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  105117. */
  105118. FramingBehavior.FitFrustumSidesMode = 1;
  105119. return FramingBehavior;
  105120. }());
  105121. BABYLON.FramingBehavior = FramingBehavior;
  105122. })(BABYLON || (BABYLON = {}));
  105123. //# sourceMappingURL=babylon.framingBehavior.js.map
  105124. var BABYLON;
  105125. (function (BABYLON) {
  105126. /**
  105127. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  105128. */
  105129. var BouncingBehavior = /** @class */ (function () {
  105130. function BouncingBehavior() {
  105131. /**
  105132. * The duration of the animation, in milliseconds
  105133. */
  105134. this.transitionDuration = 450;
  105135. /**
  105136. * Length of the distance animated by the transition when lower radius is reached
  105137. */
  105138. this.lowerRadiusTransitionRange = 2;
  105139. /**
  105140. * Length of the distance animated by the transition when upper radius is reached
  105141. */
  105142. this.upperRadiusTransitionRange = -2;
  105143. this._autoTransitionRange = false;
  105144. // Animations
  105145. this._radiusIsAnimating = false;
  105146. this._radiusBounceTransition = null;
  105147. this._animatables = new Array();
  105148. }
  105149. Object.defineProperty(BouncingBehavior.prototype, "name", {
  105150. get: function () {
  105151. return "Bouncing";
  105152. },
  105153. enumerable: true,
  105154. configurable: true
  105155. });
  105156. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  105157. /**
  105158. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  105159. */
  105160. get: function () {
  105161. return this._autoTransitionRange;
  105162. },
  105163. /**
  105164. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  105165. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  105166. */
  105167. set: function (value) {
  105168. var _this = this;
  105169. if (this._autoTransitionRange === value) {
  105170. return;
  105171. }
  105172. this._autoTransitionRange = value;
  105173. var camera = this._attachedCamera;
  105174. if (!camera) {
  105175. return;
  105176. }
  105177. if (value) {
  105178. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  105179. if (!mesh) {
  105180. return;
  105181. }
  105182. mesh.computeWorldMatrix(true);
  105183. var diagonal = mesh.getBoundingInfo().diagonalLength;
  105184. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  105185. _this.upperRadiusTransitionRange = diagonal * 0.05;
  105186. });
  105187. }
  105188. else if (this._onMeshTargetChangedObserver) {
  105189. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  105190. }
  105191. },
  105192. enumerable: true,
  105193. configurable: true
  105194. });
  105195. BouncingBehavior.prototype.init = function () {
  105196. // Do notihng
  105197. };
  105198. BouncingBehavior.prototype.attach = function (camera) {
  105199. var _this = this;
  105200. this._attachedCamera = camera;
  105201. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  105202. if (!_this._attachedCamera) {
  105203. return;
  105204. }
  105205. // Add the bounce animation to the lower radius limit
  105206. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  105207. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  105208. }
  105209. // Add the bounce animation to the upper radius limit
  105210. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  105211. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  105212. }
  105213. });
  105214. };
  105215. BouncingBehavior.prototype.detach = function () {
  105216. if (!this._attachedCamera) {
  105217. return;
  105218. }
  105219. if (this._onAfterCheckInputsObserver) {
  105220. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  105221. }
  105222. if (this._onMeshTargetChangedObserver) {
  105223. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  105224. }
  105225. this._attachedCamera = null;
  105226. };
  105227. /**
  105228. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  105229. * @param radiusLimit The limit to check against.
  105230. * @return Bool to indicate if at limit.
  105231. */
  105232. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  105233. if (!this._attachedCamera) {
  105234. return false;
  105235. }
  105236. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  105237. return true;
  105238. }
  105239. return false;
  105240. };
  105241. /**
  105242. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  105243. * @param radiusDelta The delta by which to animate to. Can be negative.
  105244. */
  105245. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  105246. var _this = this;
  105247. if (!this._attachedCamera) {
  105248. return;
  105249. }
  105250. if (!this._radiusBounceTransition) {
  105251. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  105252. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  105253. }
  105254. // Prevent zoom until bounce has completed
  105255. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  105256. this._attachedCamera.wheelPrecision = Infinity;
  105257. this._attachedCamera.inertialRadiusOffset = 0;
  105258. // Animate to the radius limit
  105259. this.stopAllAnimations();
  105260. this._radiusIsAnimating = true;
  105261. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  105262. if (animatable) {
  105263. this._animatables.push(animatable);
  105264. }
  105265. };
  105266. /**
  105267. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  105268. */
  105269. BouncingBehavior.prototype._clearAnimationLocks = function () {
  105270. this._radiusIsAnimating = false;
  105271. if (this._attachedCamera) {
  105272. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  105273. }
  105274. };
  105275. /**
  105276. * Stops and removes all animations that have been applied to the camera
  105277. */
  105278. BouncingBehavior.prototype.stopAllAnimations = function () {
  105279. if (this._attachedCamera) {
  105280. this._attachedCamera.animations = [];
  105281. }
  105282. while (this._animatables.length) {
  105283. this._animatables[0].onAnimationEnd = null;
  105284. this._animatables[0].stop();
  105285. this._animatables.shift();
  105286. }
  105287. };
  105288. /**
  105289. * The easing function used by animations
  105290. */
  105291. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  105292. /**
  105293. * The easing mode used by animations
  105294. */
  105295. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  105296. return BouncingBehavior;
  105297. }());
  105298. BABYLON.BouncingBehavior = BouncingBehavior;
  105299. })(BABYLON || (BABYLON = {}));
  105300. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  105301. var BABYLON;
  105302. (function (BABYLON) {
  105303. var AutoRotationBehavior = /** @class */ (function () {
  105304. function AutoRotationBehavior() {
  105305. this._zoomStopsAnimation = false;
  105306. this._idleRotationSpeed = 0.05;
  105307. this._idleRotationWaitTime = 2000;
  105308. this._idleRotationSpinupTime = 2000;
  105309. this._isPointerDown = false;
  105310. this._lastFrameTime = null;
  105311. this._lastInteractionTime = -Infinity;
  105312. this._cameraRotationSpeed = 0;
  105313. this._lastFrameRadius = 0;
  105314. }
  105315. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  105316. get: function () {
  105317. return "AutoRotation";
  105318. },
  105319. enumerable: true,
  105320. configurable: true
  105321. });
  105322. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  105323. /**
  105324. * Gets the flag that indicates if user zooming should stop animation.
  105325. */
  105326. get: function () {
  105327. return this._zoomStopsAnimation;
  105328. },
  105329. /**
  105330. * Sets the flag that indicates if user zooming should stop animation.
  105331. */
  105332. set: function (flag) {
  105333. this._zoomStopsAnimation = flag;
  105334. },
  105335. enumerable: true,
  105336. configurable: true
  105337. });
  105338. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  105339. /**
  105340. * Gets the default speed at which the camera rotates around the model.
  105341. */
  105342. get: function () {
  105343. return this._idleRotationSpeed;
  105344. },
  105345. /**
  105346. * Sets the default speed at which the camera rotates around the model.
  105347. */
  105348. set: function (speed) {
  105349. this._idleRotationSpeed = speed;
  105350. },
  105351. enumerable: true,
  105352. configurable: true
  105353. });
  105354. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  105355. /**
  105356. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  105357. */
  105358. get: function () {
  105359. return this._idleRotationWaitTime;
  105360. },
  105361. /**
  105362. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  105363. */
  105364. set: function (time) {
  105365. this._idleRotationWaitTime = time;
  105366. },
  105367. enumerable: true,
  105368. configurable: true
  105369. });
  105370. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  105371. /**
  105372. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  105373. */
  105374. get: function () {
  105375. return this._idleRotationSpinupTime;
  105376. },
  105377. /**
  105378. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  105379. */
  105380. set: function (time) {
  105381. this._idleRotationSpinupTime = time;
  105382. },
  105383. enumerable: true,
  105384. configurable: true
  105385. });
  105386. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  105387. /**
  105388. * Gets a value indicating if the camera is currently rotating because of this behavior
  105389. */
  105390. get: function () {
  105391. return Math.abs(this._cameraRotationSpeed) > 0;
  105392. },
  105393. enumerable: true,
  105394. configurable: true
  105395. });
  105396. AutoRotationBehavior.prototype.init = function () {
  105397. // Do notihng
  105398. };
  105399. AutoRotationBehavior.prototype.attach = function (camera) {
  105400. var _this = this;
  105401. this._attachedCamera = camera;
  105402. var scene = this._attachedCamera.getScene();
  105403. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  105404. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  105405. _this._isPointerDown = true;
  105406. return;
  105407. }
  105408. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  105409. _this._isPointerDown = false;
  105410. }
  105411. });
  105412. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  105413. var now = BABYLON.Tools.Now;
  105414. var dt = 0;
  105415. if (_this._lastFrameTime != null) {
  105416. dt = now - _this._lastFrameTime;
  105417. }
  105418. _this._lastFrameTime = now;
  105419. // Stop the animation if there is user interaction and the animation should stop for this interaction
  105420. _this._applyUserInteraction();
  105421. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  105422. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  105423. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  105424. // Step camera rotation by rotation speed
  105425. if (_this._attachedCamera) {
  105426. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  105427. }
  105428. });
  105429. };
  105430. AutoRotationBehavior.prototype.detach = function () {
  105431. if (!this._attachedCamera) {
  105432. return;
  105433. }
  105434. var scene = this._attachedCamera.getScene();
  105435. if (this._onPrePointerObservableObserver) {
  105436. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  105437. }
  105438. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  105439. this._attachedCamera = null;
  105440. };
  105441. /**
  105442. * Returns true if user is scrolling.
  105443. * @return true if user is scrolling.
  105444. */
  105445. AutoRotationBehavior.prototype._userIsZooming = function () {
  105446. if (!this._attachedCamera) {
  105447. return false;
  105448. }
  105449. return this._attachedCamera.inertialRadiusOffset !== 0;
  105450. };
  105451. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  105452. if (!this._attachedCamera) {
  105453. return false;
  105454. }
  105455. var zoomHasHitLimit = false;
  105456. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  105457. zoomHasHitLimit = true;
  105458. }
  105459. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  105460. this._lastFrameRadius = this._attachedCamera.radius;
  105461. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  105462. };
  105463. /**
  105464. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  105465. */
  105466. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  105467. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  105468. this._lastInteractionTime = BABYLON.Tools.Now;
  105469. }
  105470. };
  105471. // Tools
  105472. AutoRotationBehavior.prototype._userIsMoving = function () {
  105473. if (!this._attachedCamera) {
  105474. return false;
  105475. }
  105476. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  105477. this._attachedCamera.inertialBetaOffset !== 0 ||
  105478. this._attachedCamera.inertialRadiusOffset !== 0 ||
  105479. this._attachedCamera.inertialPanningX !== 0 ||
  105480. this._attachedCamera.inertialPanningY !== 0 ||
  105481. this._isPointerDown;
  105482. };
  105483. return AutoRotationBehavior;
  105484. }());
  105485. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  105486. })(BABYLON || (BABYLON = {}));
  105487. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  105488. var BABYLON;
  105489. (function (BABYLON) {
  105490. var NullEngineOptions = /** @class */ (function () {
  105491. function NullEngineOptions() {
  105492. this.renderWidth = 512;
  105493. this.renderHeight = 256;
  105494. this.textureSize = 512;
  105495. this.deterministicLockstep = false;
  105496. this.lockstepMaxSteps = 4;
  105497. }
  105498. return NullEngineOptions;
  105499. }());
  105500. BABYLON.NullEngineOptions = NullEngineOptions;
  105501. /**
  105502. * The null engine class provides support for headless version of babylon.js.
  105503. * This can be used in server side scenario or for testing purposes
  105504. */
  105505. var NullEngine = /** @class */ (function (_super) {
  105506. __extends(NullEngine, _super);
  105507. function NullEngine(options) {
  105508. if (options === void 0) { options = new NullEngineOptions(); }
  105509. var _this = _super.call(this, null) || this;
  105510. if (options.deterministicLockstep === undefined) {
  105511. options.deterministicLockstep = false;
  105512. }
  105513. if (options.lockstepMaxSteps === undefined) {
  105514. options.lockstepMaxSteps = 4;
  105515. }
  105516. _this._options = options;
  105517. // Init caps
  105518. // We consider we are on a webgl1 capable device
  105519. _this._caps = new BABYLON.EngineCapabilities();
  105520. _this._caps.maxTexturesImageUnits = 16;
  105521. _this._caps.maxVertexTextureImageUnits = 16;
  105522. _this._caps.maxTextureSize = 512;
  105523. _this._caps.maxCubemapTextureSize = 512;
  105524. _this._caps.maxRenderTextureSize = 512;
  105525. _this._caps.maxVertexAttribs = 16;
  105526. _this._caps.maxVaryingVectors = 16;
  105527. _this._caps.maxFragmentUniformVectors = 16;
  105528. _this._caps.maxVertexUniformVectors = 16;
  105529. // Extensions
  105530. _this._caps.standardDerivatives = false;
  105531. _this._caps.astc = null;
  105532. _this._caps.s3tc = null;
  105533. _this._caps.pvrtc = null;
  105534. _this._caps.etc1 = null;
  105535. _this._caps.etc2 = null;
  105536. _this._caps.textureAnisotropicFilterExtension = null;
  105537. _this._caps.maxAnisotropy = 0;
  105538. _this._caps.uintIndices = false;
  105539. _this._caps.fragmentDepthSupported = false;
  105540. _this._caps.highPrecisionShaderSupported = true;
  105541. _this._caps.colorBufferFloat = false;
  105542. _this._caps.textureFloat = false;
  105543. _this._caps.textureFloatLinearFiltering = false;
  105544. _this._caps.textureFloatRender = false;
  105545. _this._caps.textureHalfFloat = false;
  105546. _this._caps.textureHalfFloatLinearFiltering = false;
  105547. _this._caps.textureHalfFloatRender = false;
  105548. _this._caps.textureLOD = false;
  105549. _this._caps.drawBuffersExtension = false;
  105550. _this._caps.depthTextureExtension = false;
  105551. _this._caps.vertexArrayObject = false;
  105552. _this._caps.instancedArrays = false;
  105553. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  105554. // Wrappers
  105555. if (typeof URL === "undefined") {
  105556. URL = {
  105557. createObjectURL: function () { },
  105558. revokeObjectURL: function () { }
  105559. };
  105560. }
  105561. if (typeof Blob === "undefined") {
  105562. Blob = function () { };
  105563. }
  105564. return _this;
  105565. }
  105566. NullEngine.prototype.isDeterministicLockStep = function () {
  105567. return this._options.deterministicLockstep;
  105568. };
  105569. NullEngine.prototype.getLockstepMaxSteps = function () {
  105570. return this._options.lockstepMaxSteps;
  105571. };
  105572. NullEngine.prototype.getHardwareScalingLevel = function () {
  105573. return 1.0;
  105574. };
  105575. NullEngine.prototype.createVertexBuffer = function (vertices) {
  105576. return {
  105577. capacity: 0,
  105578. references: 1,
  105579. is32Bits: false
  105580. };
  105581. };
  105582. NullEngine.prototype.createIndexBuffer = function (indices) {
  105583. return {
  105584. capacity: 0,
  105585. references: 1,
  105586. is32Bits: false
  105587. };
  105588. };
  105589. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  105590. if (stencil === void 0) { stencil = false; }
  105591. };
  105592. NullEngine.prototype.getRenderWidth = function (useScreen) {
  105593. if (useScreen === void 0) { useScreen = false; }
  105594. if (!useScreen && this._currentRenderTarget) {
  105595. return this._currentRenderTarget.width;
  105596. }
  105597. return this._options.renderWidth;
  105598. };
  105599. NullEngine.prototype.getRenderHeight = function (useScreen) {
  105600. if (useScreen === void 0) { useScreen = false; }
  105601. if (!useScreen && this._currentRenderTarget) {
  105602. return this._currentRenderTarget.height;
  105603. }
  105604. return this._options.renderHeight;
  105605. };
  105606. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  105607. this._cachedViewport = viewport;
  105608. };
  105609. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  105610. return {
  105611. transformFeedback: null,
  105612. __SPECTOR_rebuildProgram: null
  105613. };
  105614. };
  105615. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  105616. return [];
  105617. };
  105618. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  105619. return [];
  105620. };
  105621. NullEngine.prototype.bindSamplers = function (effect) {
  105622. this._currentEffect = null;
  105623. };
  105624. NullEngine.prototype.enableEffect = function (effect) {
  105625. this._currentEffect = effect;
  105626. if (effect.onBind) {
  105627. effect.onBind(effect);
  105628. }
  105629. if (effect._onBindObservable) {
  105630. effect._onBindObservable.notifyObservers(effect);
  105631. }
  105632. };
  105633. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  105634. if (zOffset === void 0) { zOffset = 0; }
  105635. if (reverseSide === void 0) { reverseSide = false; }
  105636. };
  105637. NullEngine.prototype.setIntArray = function (uniform, array) {
  105638. };
  105639. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  105640. };
  105641. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  105642. };
  105643. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  105644. };
  105645. NullEngine.prototype.setFloatArray = function (uniform, array) {
  105646. };
  105647. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  105648. };
  105649. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  105650. };
  105651. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  105652. };
  105653. NullEngine.prototype.setArray = function (uniform, array) {
  105654. };
  105655. NullEngine.prototype.setArray2 = function (uniform, array) {
  105656. };
  105657. NullEngine.prototype.setArray3 = function (uniform, array) {
  105658. };
  105659. NullEngine.prototype.setArray4 = function (uniform, array) {
  105660. };
  105661. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  105662. };
  105663. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  105664. };
  105665. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  105666. };
  105667. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  105668. };
  105669. NullEngine.prototype.setFloat = function (uniform, value) {
  105670. };
  105671. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  105672. };
  105673. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  105674. };
  105675. NullEngine.prototype.setBool = function (uniform, bool) {
  105676. };
  105677. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  105678. };
  105679. NullEngine.prototype.setColor3 = function (uniform, color3) {
  105680. };
  105681. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  105682. };
  105683. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  105684. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  105685. if (this._alphaMode === mode) {
  105686. return;
  105687. }
  105688. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  105689. if (!noDepthWriteChange) {
  105690. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  105691. }
  105692. this._alphaMode = mode;
  105693. };
  105694. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  105695. };
  105696. NullEngine.prototype.wipeCaches = function (bruteForce) {
  105697. if (this.preventCacheWipeBetweenFrames) {
  105698. return;
  105699. }
  105700. this.resetTextureCache();
  105701. this._currentEffect = null;
  105702. if (bruteForce) {
  105703. this._currentProgram = null;
  105704. this._stencilState.reset();
  105705. this._depthCullingState.reset();
  105706. this._alphaState.reset();
  105707. }
  105708. this._cachedVertexBuffers = null;
  105709. this._cachedIndexBuffer = null;
  105710. this._cachedEffectForVertexBuffers = null;
  105711. };
  105712. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  105713. };
  105714. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  105715. };
  105716. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  105717. };
  105718. /** @hidden */
  105719. NullEngine.prototype._createTexture = function () {
  105720. return {};
  105721. };
  105722. /** @hidden */
  105723. NullEngine.prototype._releaseTexture = function (texture) {
  105724. };
  105725. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  105726. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  105727. if (onLoad === void 0) { onLoad = null; }
  105728. if (onError === void 0) { onError = null; }
  105729. if (buffer === void 0) { buffer = null; }
  105730. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  105731. var url = String(urlArg);
  105732. texture.url = url;
  105733. texture.generateMipMaps = !noMipmap;
  105734. texture.samplingMode = samplingMode;
  105735. texture.invertY = invertY;
  105736. texture.baseWidth = this._options.textureSize;
  105737. texture.baseHeight = this._options.textureSize;
  105738. texture.width = this._options.textureSize;
  105739. texture.height = this._options.textureSize;
  105740. if (format) {
  105741. texture.format = format;
  105742. }
  105743. texture.isReady = true;
  105744. if (onLoad) {
  105745. onLoad();
  105746. }
  105747. this._internalTexturesCache.push(texture);
  105748. return texture;
  105749. };
  105750. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  105751. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  105752. if (options !== undefined && typeof options === "object") {
  105753. fullOptions.generateMipMaps = options.generateMipMaps;
  105754. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  105755. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  105756. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  105757. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  105758. }
  105759. else {
  105760. fullOptions.generateMipMaps = options;
  105761. fullOptions.generateDepthBuffer = true;
  105762. fullOptions.generateStencilBuffer = false;
  105763. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  105764. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  105765. }
  105766. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  105767. var width = size.width || size;
  105768. var height = size.height || size;
  105769. texture._depthStencilBuffer = {};
  105770. texture._framebuffer = {};
  105771. texture.baseWidth = width;
  105772. texture.baseHeight = height;
  105773. texture.width = width;
  105774. texture.height = height;
  105775. texture.isReady = true;
  105776. texture.samples = 1;
  105777. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  105778. texture.samplingMode = fullOptions.samplingMode;
  105779. texture.type = fullOptions.type;
  105780. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  105781. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  105782. this._internalTexturesCache.push(texture);
  105783. return texture;
  105784. };
  105785. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  105786. texture.samplingMode = samplingMode;
  105787. };
  105788. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  105789. if (this._currentRenderTarget) {
  105790. this.unBindFramebuffer(this._currentRenderTarget);
  105791. }
  105792. this._currentRenderTarget = texture;
  105793. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  105794. if (this._cachedViewport && !forceFullscreenViewport) {
  105795. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  105796. }
  105797. };
  105798. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  105799. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  105800. this._currentRenderTarget = null;
  105801. if (onBeforeUnbind) {
  105802. if (texture._MSAAFramebuffer) {
  105803. this._currentFramebuffer = texture._framebuffer;
  105804. }
  105805. onBeforeUnbind();
  105806. }
  105807. this._currentFramebuffer = null;
  105808. };
  105809. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  105810. var vbo = {
  105811. capacity: 1,
  105812. references: 1,
  105813. is32Bits: false
  105814. };
  105815. return vbo;
  105816. };
  105817. NullEngine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  105818. if (premulAlpha === void 0) { premulAlpha = false; }
  105819. };
  105820. /**
  105821. * @hidden
  105822. * Get the current error code of the webGL context
  105823. * @returns the error code
  105824. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  105825. */
  105826. NullEngine.prototype.getError = function () {
  105827. return 0;
  105828. };
  105829. /** @hidden */
  105830. NullEngine.prototype._getUnpackAlignement = function () {
  105831. return 1;
  105832. };
  105833. /** @hidden */
  105834. NullEngine.prototype._unpackFlipY = function (value) {
  105835. };
  105836. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  105837. if (offset === void 0) { offset = 0; }
  105838. };
  105839. /**
  105840. * Updates a dynamic vertex buffer.
  105841. * @param vertexBuffer the vertex buffer to update
  105842. * @param data the data used to update the vertex buffer
  105843. * @param byteOffset the byte offset of the data (optional)
  105844. * @param byteLength the byte length of the data (optional)
  105845. */
  105846. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  105847. };
  105848. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  105849. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  105850. this._boundTexturesCache[this._activeChannel] = texture;
  105851. return true;
  105852. }
  105853. return false;
  105854. };
  105855. /** @hidden */
  105856. NullEngine.prototype._bindTexture = function (channel, texture) {
  105857. if (channel < 0) {
  105858. return;
  105859. }
  105860. this._bindTextureDirectly(0, texture);
  105861. };
  105862. /** @hidden */
  105863. NullEngine.prototype._releaseBuffer = function (buffer) {
  105864. buffer.references--;
  105865. if (buffer.references === 0) {
  105866. return true;
  105867. }
  105868. return false;
  105869. };
  105870. NullEngine.prototype.releaseEffects = function () {
  105871. };
  105872. NullEngine.prototype.displayLoadingUI = function () {
  105873. };
  105874. NullEngine.prototype.hideLoadingUI = function () {
  105875. };
  105876. /** @hidden */
  105877. NullEngine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  105878. if (faceIndex === void 0) { faceIndex = 0; }
  105879. if (lod === void 0) { lod = 0; }
  105880. };
  105881. /** @hidden */
  105882. NullEngine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  105883. if (faceIndex === void 0) { faceIndex = 0; }
  105884. if (lod === void 0) { lod = 0; }
  105885. };
  105886. /** @hidden */
  105887. NullEngine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  105888. if (faceIndex === void 0) { faceIndex = 0; }
  105889. if (lod === void 0) { lod = 0; }
  105890. };
  105891. /** @hidden */
  105892. NullEngine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  105893. if (faceIndex === void 0) { faceIndex = 0; }
  105894. if (lod === void 0) { lod = 0; }
  105895. };
  105896. return NullEngine;
  105897. }(BABYLON.Engine));
  105898. BABYLON.NullEngine = NullEngine;
  105899. })(BABYLON || (BABYLON = {}));
  105900. //# sourceMappingURL=babylon.nullEngine.js.map
  105901. var BABYLON;
  105902. (function (BABYLON) {
  105903. /**
  105904. * This class can be used to get instrumentation data from a Babylon engine
  105905. */
  105906. var EngineInstrumentation = /** @class */ (function () {
  105907. function EngineInstrumentation(engine) {
  105908. this.engine = engine;
  105909. this._captureGPUFrameTime = false;
  105910. this._gpuFrameTime = new BABYLON.PerfCounter();
  105911. this._captureShaderCompilationTime = false;
  105912. this._shaderCompilationTime = new BABYLON.PerfCounter();
  105913. // Observers
  105914. this._onBeginFrameObserver = null;
  105915. this._onEndFrameObserver = null;
  105916. this._onBeforeShaderCompilationObserver = null;
  105917. this._onAfterShaderCompilationObserver = null;
  105918. }
  105919. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  105920. // Properties
  105921. /**
  105922. * Gets the perf counter used for GPU frame time
  105923. */
  105924. get: function () {
  105925. return this._gpuFrameTime;
  105926. },
  105927. enumerable: true,
  105928. configurable: true
  105929. });
  105930. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  105931. /**
  105932. * Gets the GPU frame time capture status
  105933. */
  105934. get: function () {
  105935. return this._captureGPUFrameTime;
  105936. },
  105937. /**
  105938. * Enable or disable the GPU frame time capture
  105939. */
  105940. set: function (value) {
  105941. var _this = this;
  105942. if (value === this._captureGPUFrameTime) {
  105943. return;
  105944. }
  105945. this._captureGPUFrameTime = value;
  105946. if (value) {
  105947. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  105948. if (!_this._gpuFrameTimeToken) {
  105949. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  105950. }
  105951. });
  105952. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  105953. if (!_this._gpuFrameTimeToken) {
  105954. return;
  105955. }
  105956. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  105957. if (time > -1) {
  105958. _this._gpuFrameTimeToken = null;
  105959. _this._gpuFrameTime.fetchNewFrame();
  105960. _this._gpuFrameTime.addCount(time, true);
  105961. }
  105962. });
  105963. }
  105964. else {
  105965. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  105966. this._onBeginFrameObserver = null;
  105967. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  105968. this._onEndFrameObserver = null;
  105969. }
  105970. },
  105971. enumerable: true,
  105972. configurable: true
  105973. });
  105974. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  105975. /**
  105976. * Gets the perf counter used for shader compilation time
  105977. */
  105978. get: function () {
  105979. return this._shaderCompilationTime;
  105980. },
  105981. enumerable: true,
  105982. configurable: true
  105983. });
  105984. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  105985. /**
  105986. * Gets the shader compilation time capture status
  105987. */
  105988. get: function () {
  105989. return this._captureShaderCompilationTime;
  105990. },
  105991. /**
  105992. * Enable or disable the shader compilation time capture
  105993. */
  105994. set: function (value) {
  105995. var _this = this;
  105996. if (value === this._captureShaderCompilationTime) {
  105997. return;
  105998. }
  105999. this._captureShaderCompilationTime = value;
  106000. if (value) {
  106001. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  106002. _this._shaderCompilationTime.fetchNewFrame();
  106003. _this._shaderCompilationTime.beginMonitoring();
  106004. });
  106005. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  106006. _this._shaderCompilationTime.endMonitoring();
  106007. });
  106008. }
  106009. else {
  106010. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  106011. this._onBeforeShaderCompilationObserver = null;
  106012. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  106013. this._onAfterShaderCompilationObserver = null;
  106014. }
  106015. },
  106016. enumerable: true,
  106017. configurable: true
  106018. });
  106019. EngineInstrumentation.prototype.dispose = function () {
  106020. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  106021. this._onBeginFrameObserver = null;
  106022. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  106023. this._onEndFrameObserver = null;
  106024. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  106025. this._onBeforeShaderCompilationObserver = null;
  106026. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  106027. this._onAfterShaderCompilationObserver = null;
  106028. this.engine = null;
  106029. };
  106030. return EngineInstrumentation;
  106031. }());
  106032. BABYLON.EngineInstrumentation = EngineInstrumentation;
  106033. })(BABYLON || (BABYLON = {}));
  106034. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  106035. var BABYLON;
  106036. (function (BABYLON) {
  106037. /**
  106038. * This class can be used to get instrumentation data from a Babylon engine
  106039. */
  106040. var SceneInstrumentation = /** @class */ (function () {
  106041. function SceneInstrumentation(scene) {
  106042. var _this = this;
  106043. this.scene = scene;
  106044. this._captureActiveMeshesEvaluationTime = false;
  106045. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  106046. this._captureRenderTargetsRenderTime = false;
  106047. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  106048. this._captureFrameTime = false;
  106049. this._frameTime = new BABYLON.PerfCounter();
  106050. this._captureRenderTime = false;
  106051. this._renderTime = new BABYLON.PerfCounter();
  106052. this._captureInterFrameTime = false;
  106053. this._interFrameTime = new BABYLON.PerfCounter();
  106054. this._captureParticlesRenderTime = false;
  106055. this._particlesRenderTime = new BABYLON.PerfCounter();
  106056. this._captureSpritesRenderTime = false;
  106057. this._spritesRenderTime = new BABYLON.PerfCounter();
  106058. this._capturePhysicsTime = false;
  106059. this._physicsTime = new BABYLON.PerfCounter();
  106060. this._captureAnimationsTime = false;
  106061. this._animationsTime = new BABYLON.PerfCounter();
  106062. this._captureCameraRenderTime = false;
  106063. this._cameraRenderTime = new BABYLON.PerfCounter();
  106064. // Observers
  106065. this._onBeforeActiveMeshesEvaluationObserver = null;
  106066. this._onAfterActiveMeshesEvaluationObserver = null;
  106067. this._onBeforeRenderTargetsRenderObserver = null;
  106068. this._onAfterRenderTargetsRenderObserver = null;
  106069. this._onAfterRenderObserver = null;
  106070. this._onBeforeDrawPhaseObserver = null;
  106071. this._onAfterDrawPhaseObserver = null;
  106072. this._onBeforeAnimationsObserver = null;
  106073. this._onBeforeParticlesRenderingObserver = null;
  106074. this._onAfterParticlesRenderingObserver = null;
  106075. this._onBeforeSpritesRenderingObserver = null;
  106076. this._onAfterSpritesRenderingObserver = null;
  106077. this._onBeforePhysicsObserver = null;
  106078. this._onAfterPhysicsObserver = null;
  106079. this._onAfterAnimationsObserver = null;
  106080. this._onBeforeCameraRenderObserver = null;
  106081. this._onAfterCameraRenderObserver = null;
  106082. // Before render
  106083. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  106084. if (_this._captureActiveMeshesEvaluationTime) {
  106085. _this._activeMeshesEvaluationTime.fetchNewFrame();
  106086. }
  106087. if (_this._captureRenderTargetsRenderTime) {
  106088. _this._renderTargetsRenderTime.fetchNewFrame();
  106089. }
  106090. if (_this._captureFrameTime) {
  106091. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  106092. _this._frameTime.beginMonitoring();
  106093. }
  106094. if (_this._captureInterFrameTime) {
  106095. _this._interFrameTime.endMonitoring();
  106096. }
  106097. if (_this._captureParticlesRenderTime) {
  106098. _this._particlesRenderTime.fetchNewFrame();
  106099. }
  106100. if (_this._captureSpritesRenderTime) {
  106101. _this._spritesRenderTime.fetchNewFrame();
  106102. }
  106103. if (_this._captureAnimationsTime) {
  106104. _this._animationsTime.beginMonitoring();
  106105. }
  106106. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  106107. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  106108. });
  106109. // After render
  106110. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  106111. if (_this._captureFrameTime) {
  106112. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  106113. _this._frameTime.endMonitoring();
  106114. }
  106115. if (_this._captureRenderTime) {
  106116. _this._renderTime.endMonitoring(false);
  106117. }
  106118. if (_this._captureInterFrameTime) {
  106119. _this._interFrameTime.beginMonitoring();
  106120. }
  106121. });
  106122. }
  106123. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  106124. // Properties
  106125. /**
  106126. * Gets the perf counter used for active meshes evaluation time
  106127. */
  106128. get: function () {
  106129. return this._activeMeshesEvaluationTime;
  106130. },
  106131. enumerable: true,
  106132. configurable: true
  106133. });
  106134. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  106135. /**
  106136. * Gets the active meshes evaluation time capture status
  106137. */
  106138. get: function () {
  106139. return this._captureActiveMeshesEvaluationTime;
  106140. },
  106141. /**
  106142. * Enable or disable the active meshes evaluation time capture
  106143. */
  106144. set: function (value) {
  106145. var _this = this;
  106146. if (value === this._captureActiveMeshesEvaluationTime) {
  106147. return;
  106148. }
  106149. this._captureActiveMeshesEvaluationTime = value;
  106150. if (value) {
  106151. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  106152. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  106153. _this._activeMeshesEvaluationTime.beginMonitoring();
  106154. });
  106155. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  106156. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  106157. _this._activeMeshesEvaluationTime.endMonitoring();
  106158. });
  106159. }
  106160. else {
  106161. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  106162. this._onBeforeActiveMeshesEvaluationObserver = null;
  106163. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  106164. this._onAfterActiveMeshesEvaluationObserver = null;
  106165. }
  106166. },
  106167. enumerable: true,
  106168. configurable: true
  106169. });
  106170. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  106171. /**
  106172. * Gets the perf counter used for render targets render time
  106173. */
  106174. get: function () {
  106175. return this._renderTargetsRenderTime;
  106176. },
  106177. enumerable: true,
  106178. configurable: true
  106179. });
  106180. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  106181. /**
  106182. * Gets the render targets render time capture status
  106183. */
  106184. get: function () {
  106185. return this._captureRenderTargetsRenderTime;
  106186. },
  106187. /**
  106188. * Enable or disable the render targets render time capture
  106189. */
  106190. set: function (value) {
  106191. var _this = this;
  106192. if (value === this._captureRenderTargetsRenderTime) {
  106193. return;
  106194. }
  106195. this._captureRenderTargetsRenderTime = value;
  106196. if (value) {
  106197. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  106198. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  106199. _this._renderTargetsRenderTime.beginMonitoring();
  106200. });
  106201. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  106202. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  106203. _this._renderTargetsRenderTime.endMonitoring(false);
  106204. });
  106205. }
  106206. else {
  106207. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  106208. this._onBeforeRenderTargetsRenderObserver = null;
  106209. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  106210. this._onAfterRenderTargetsRenderObserver = null;
  106211. }
  106212. },
  106213. enumerable: true,
  106214. configurable: true
  106215. });
  106216. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  106217. /**
  106218. * Gets the perf counter used for particles render time
  106219. */
  106220. get: function () {
  106221. return this._particlesRenderTime;
  106222. },
  106223. enumerable: true,
  106224. configurable: true
  106225. });
  106226. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  106227. /**
  106228. * Gets the particles render time capture status
  106229. */
  106230. get: function () {
  106231. return this._captureParticlesRenderTime;
  106232. },
  106233. /**
  106234. * Enable or disable the particles render time capture
  106235. */
  106236. set: function (value) {
  106237. var _this = this;
  106238. if (value === this._captureParticlesRenderTime) {
  106239. return;
  106240. }
  106241. this._captureParticlesRenderTime = value;
  106242. if (value) {
  106243. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  106244. BABYLON.Tools.StartPerformanceCounter("Particles");
  106245. _this._particlesRenderTime.beginMonitoring();
  106246. });
  106247. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  106248. BABYLON.Tools.EndPerformanceCounter("Particles");
  106249. _this._particlesRenderTime.endMonitoring(false);
  106250. });
  106251. }
  106252. else {
  106253. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  106254. this._onBeforeParticlesRenderingObserver = null;
  106255. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  106256. this._onAfterParticlesRenderingObserver = null;
  106257. }
  106258. },
  106259. enumerable: true,
  106260. configurable: true
  106261. });
  106262. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  106263. /**
  106264. * Gets the perf counter used for sprites render time
  106265. */
  106266. get: function () {
  106267. return this._spritesRenderTime;
  106268. },
  106269. enumerable: true,
  106270. configurable: true
  106271. });
  106272. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  106273. /**
  106274. * Gets the sprites render time capture status
  106275. */
  106276. get: function () {
  106277. return this._captureSpritesRenderTime;
  106278. },
  106279. /**
  106280. * Enable or disable the sprites render time capture
  106281. */
  106282. set: function (value) {
  106283. var _this = this;
  106284. if (value === this._captureSpritesRenderTime) {
  106285. return;
  106286. }
  106287. this._captureSpritesRenderTime = value;
  106288. if (!this.scene.spriteManagers) {
  106289. return;
  106290. }
  106291. if (value) {
  106292. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  106293. BABYLON.Tools.StartPerformanceCounter("Sprites");
  106294. _this._spritesRenderTime.beginMonitoring();
  106295. });
  106296. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  106297. BABYLON.Tools.EndPerformanceCounter("Sprites");
  106298. _this._spritesRenderTime.endMonitoring(false);
  106299. });
  106300. }
  106301. else {
  106302. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  106303. this._onBeforeSpritesRenderingObserver = null;
  106304. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  106305. this._onAfterSpritesRenderingObserver = null;
  106306. }
  106307. },
  106308. enumerable: true,
  106309. configurable: true
  106310. });
  106311. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  106312. /**
  106313. * Gets the perf counter used for physics time
  106314. */
  106315. get: function () {
  106316. return this._physicsTime;
  106317. },
  106318. enumerable: true,
  106319. configurable: true
  106320. });
  106321. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  106322. /**
  106323. * Gets the physics time capture status
  106324. */
  106325. get: function () {
  106326. return this._capturePhysicsTime;
  106327. },
  106328. /**
  106329. * Enable or disable the physics time capture
  106330. */
  106331. set: function (value) {
  106332. var _this = this;
  106333. if (value === this._capturePhysicsTime) {
  106334. return;
  106335. }
  106336. this._capturePhysicsTime = value;
  106337. if (value) {
  106338. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  106339. BABYLON.Tools.StartPerformanceCounter("Physics");
  106340. _this._physicsTime.beginMonitoring();
  106341. });
  106342. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  106343. BABYLON.Tools.EndPerformanceCounter("Physics");
  106344. _this._physicsTime.endMonitoring();
  106345. });
  106346. }
  106347. else {
  106348. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  106349. this._onBeforePhysicsObserver = null;
  106350. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  106351. this._onAfterPhysicsObserver = null;
  106352. }
  106353. },
  106354. enumerable: true,
  106355. configurable: true
  106356. });
  106357. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  106358. /**
  106359. * Gets the perf counter used for animations time
  106360. */
  106361. get: function () {
  106362. return this._animationsTime;
  106363. },
  106364. enumerable: true,
  106365. configurable: true
  106366. });
  106367. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  106368. /**
  106369. * Gets the animations time capture status
  106370. */
  106371. get: function () {
  106372. return this._captureAnimationsTime;
  106373. },
  106374. /**
  106375. * Enable or disable the animations time capture
  106376. */
  106377. set: function (value) {
  106378. var _this = this;
  106379. if (value === this._captureAnimationsTime) {
  106380. return;
  106381. }
  106382. this._captureAnimationsTime = value;
  106383. if (value) {
  106384. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  106385. _this._animationsTime.endMonitoring();
  106386. });
  106387. }
  106388. else {
  106389. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  106390. this._onAfterAnimationsObserver = null;
  106391. }
  106392. },
  106393. enumerable: true,
  106394. configurable: true
  106395. });
  106396. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  106397. /**
  106398. * Gets the perf counter used for frame time capture
  106399. */
  106400. get: function () {
  106401. return this._frameTime;
  106402. },
  106403. enumerable: true,
  106404. configurable: true
  106405. });
  106406. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  106407. /**
  106408. * Gets the frame time capture status
  106409. */
  106410. get: function () {
  106411. return this._captureFrameTime;
  106412. },
  106413. /**
  106414. * Enable or disable the frame time capture
  106415. */
  106416. set: function (value) {
  106417. this._captureFrameTime = value;
  106418. },
  106419. enumerable: true,
  106420. configurable: true
  106421. });
  106422. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  106423. /**
  106424. * Gets the perf counter used for inter-frames time capture
  106425. */
  106426. get: function () {
  106427. return this._interFrameTime;
  106428. },
  106429. enumerable: true,
  106430. configurable: true
  106431. });
  106432. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  106433. /**
  106434. * Gets the inter-frames time capture status
  106435. */
  106436. get: function () {
  106437. return this._captureInterFrameTime;
  106438. },
  106439. /**
  106440. * Enable or disable the inter-frames time capture
  106441. */
  106442. set: function (value) {
  106443. this._captureInterFrameTime = value;
  106444. },
  106445. enumerable: true,
  106446. configurable: true
  106447. });
  106448. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  106449. /**
  106450. * Gets the perf counter used for render time capture
  106451. */
  106452. get: function () {
  106453. return this._renderTime;
  106454. },
  106455. enumerable: true,
  106456. configurable: true
  106457. });
  106458. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  106459. /**
  106460. * Gets the render time capture status
  106461. */
  106462. get: function () {
  106463. return this._captureRenderTime;
  106464. },
  106465. /**
  106466. * Enable or disable the render time capture
  106467. */
  106468. set: function (value) {
  106469. var _this = this;
  106470. if (value === this._captureRenderTime) {
  106471. return;
  106472. }
  106473. this._captureRenderTime = value;
  106474. if (value) {
  106475. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  106476. _this._renderTime.beginMonitoring();
  106477. BABYLON.Tools.StartPerformanceCounter("Main render");
  106478. });
  106479. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  106480. _this._renderTime.endMonitoring(false);
  106481. BABYLON.Tools.EndPerformanceCounter("Main render");
  106482. });
  106483. }
  106484. else {
  106485. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  106486. this._onBeforeDrawPhaseObserver = null;
  106487. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  106488. this._onAfterDrawPhaseObserver = null;
  106489. }
  106490. },
  106491. enumerable: true,
  106492. configurable: true
  106493. });
  106494. Object.defineProperty(SceneInstrumentation.prototype, "cameraRenderTimeCounter", {
  106495. /**
  106496. * Gets the perf counter used for camera render time capture
  106497. */
  106498. get: function () {
  106499. return this._cameraRenderTime;
  106500. },
  106501. enumerable: true,
  106502. configurable: true
  106503. });
  106504. Object.defineProperty(SceneInstrumentation.prototype, "captureCameraRenderTime", {
  106505. /**
  106506. * Gets the camera render time capture status
  106507. */
  106508. get: function () {
  106509. return this._captureCameraRenderTime;
  106510. },
  106511. /**
  106512. * Enable or disable the camera render time capture
  106513. */
  106514. set: function (value) {
  106515. var _this = this;
  106516. if (value === this._captureCameraRenderTime) {
  106517. return;
  106518. }
  106519. this._captureCameraRenderTime = value;
  106520. if (value) {
  106521. this._onBeforeCameraRenderObserver = this.scene.onBeforeCameraRenderObservable.add(function (camera) {
  106522. _this._cameraRenderTime.beginMonitoring();
  106523. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + camera.name);
  106524. });
  106525. this._onAfterCameraRenderObserver = this.scene.onAfterCameraRenderObservable.add(function (camera) {
  106526. _this._cameraRenderTime.endMonitoring(false);
  106527. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + camera.name);
  106528. });
  106529. }
  106530. else {
  106531. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  106532. this._onBeforeCameraRenderObserver = null;
  106533. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  106534. this._onAfterCameraRenderObserver = null;
  106535. }
  106536. },
  106537. enumerable: true,
  106538. configurable: true
  106539. });
  106540. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  106541. /**
  106542. * Gets the perf counter used for draw calls
  106543. */
  106544. get: function () {
  106545. return this.scene.getEngine()._drawCalls;
  106546. },
  106547. enumerable: true,
  106548. configurable: true
  106549. });
  106550. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  106551. /**
  106552. * Gets the perf counter used for texture collisions
  106553. */
  106554. get: function () {
  106555. return this.scene.getEngine()._textureCollisions;
  106556. },
  106557. enumerable: true,
  106558. configurable: true
  106559. });
  106560. SceneInstrumentation.prototype.dispose = function () {
  106561. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  106562. this._onAfterRenderObserver = null;
  106563. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  106564. this._onBeforeActiveMeshesEvaluationObserver = null;
  106565. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  106566. this._onAfterActiveMeshesEvaluationObserver = null;
  106567. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  106568. this._onBeforeRenderTargetsRenderObserver = null;
  106569. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  106570. this._onAfterRenderTargetsRenderObserver = null;
  106571. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  106572. this._onBeforeAnimationsObserver = null;
  106573. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  106574. this._onBeforeParticlesRenderingObserver = null;
  106575. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  106576. this._onAfterParticlesRenderingObserver = null;
  106577. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  106578. this._onBeforeSpritesRenderingObserver = null;
  106579. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  106580. this._onAfterSpritesRenderingObserver = null;
  106581. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  106582. this._onBeforeDrawPhaseObserver = null;
  106583. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  106584. this._onAfterDrawPhaseObserver = null;
  106585. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  106586. this._onBeforePhysicsObserver = null;
  106587. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  106588. this._onAfterPhysicsObserver = null;
  106589. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  106590. this._onAfterAnimationsObserver = null;
  106591. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  106592. this._onBeforeCameraRenderObserver = null;
  106593. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  106594. this._onAfterCameraRenderObserver = null;
  106595. this.scene = null;
  106596. };
  106597. return SceneInstrumentation;
  106598. }());
  106599. BABYLON.SceneInstrumentation = SceneInstrumentation;
  106600. })(BABYLON || (BABYLON = {}));
  106601. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  106602. var BABYLON;
  106603. (function (BABYLON) {
  106604. /**
  106605. * @hidden
  106606. **/
  106607. var _TimeToken = /** @class */ (function () {
  106608. function _TimeToken() {
  106609. this._timeElapsedQueryEnded = false;
  106610. }
  106611. return _TimeToken;
  106612. }());
  106613. BABYLON._TimeToken = _TimeToken;
  106614. })(BABYLON || (BABYLON = {}));
  106615. //# sourceMappingURL=babylon.timeToken.js.map
  106616. var BABYLON;
  106617. (function (BABYLON) {
  106618. /**
  106619. * Background material defines definition.
  106620. * @hidden Mainly internal Use
  106621. */
  106622. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  106623. __extends(BackgroundMaterialDefines, _super);
  106624. /**
  106625. * Constructor of the defines.
  106626. */
  106627. function BackgroundMaterialDefines() {
  106628. var _this = _super.call(this) || this;
  106629. /**
  106630. * True if the diffuse texture is in use.
  106631. */
  106632. _this.DIFFUSE = false;
  106633. /**
  106634. * The direct UV channel to use.
  106635. */
  106636. _this.DIFFUSEDIRECTUV = 0;
  106637. /**
  106638. * True if the diffuse texture is in gamma space.
  106639. */
  106640. _this.GAMMADIFFUSE = false;
  106641. /**
  106642. * True if the diffuse texture has opacity in the alpha channel.
  106643. */
  106644. _this.DIFFUSEHASALPHA = false;
  106645. /**
  106646. * True if you want the material to fade to transparent at grazing angle.
  106647. */
  106648. _this.OPACITYFRESNEL = false;
  106649. /**
  106650. * True if an extra blur needs to be added in the reflection.
  106651. */
  106652. _this.REFLECTIONBLUR = false;
  106653. /**
  106654. * True if you want the material to fade to reflection at grazing angle.
  106655. */
  106656. _this.REFLECTIONFRESNEL = false;
  106657. /**
  106658. * True if you want the material to falloff as far as you move away from the scene center.
  106659. */
  106660. _this.REFLECTIONFALLOFF = false;
  106661. /**
  106662. * False if the current Webgl implementation does not support the texture lod extension.
  106663. */
  106664. _this.TEXTURELODSUPPORT = false;
  106665. /**
  106666. * True to ensure the data are premultiplied.
  106667. */
  106668. _this.PREMULTIPLYALPHA = false;
  106669. /**
  106670. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  106671. */
  106672. _this.USERGBCOLOR = false;
  106673. /**
  106674. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  106675. * stays aligned with the desired configuration.
  106676. */
  106677. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  106678. /**
  106679. * True to add noise in order to reduce the banding effect.
  106680. */
  106681. _this.NOISE = false;
  106682. /**
  106683. * is the reflection texture in BGR color scheme?
  106684. * Mainly used to solve a bug in ios10 video tag
  106685. */
  106686. _this.REFLECTIONBGR = false;
  106687. _this.IMAGEPROCESSING = false;
  106688. _this.VIGNETTE = false;
  106689. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  106690. _this.VIGNETTEBLENDMODEOPAQUE = false;
  106691. _this.TONEMAPPING = false;
  106692. _this.TONEMAPPING_ACES = false;
  106693. _this.CONTRAST = false;
  106694. _this.COLORCURVES = false;
  106695. _this.COLORGRADING = false;
  106696. _this.COLORGRADING3D = false;
  106697. _this.SAMPLER3DGREENDEPTH = false;
  106698. _this.SAMPLER3DBGRMAP = false;
  106699. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  106700. _this.EXPOSURE = false;
  106701. // Reflection.
  106702. _this.REFLECTION = false;
  106703. _this.REFLECTIONMAP_3D = false;
  106704. _this.REFLECTIONMAP_SPHERICAL = false;
  106705. _this.REFLECTIONMAP_PLANAR = false;
  106706. _this.REFLECTIONMAP_CUBIC = false;
  106707. _this.REFLECTIONMAP_PROJECTION = false;
  106708. _this.REFLECTIONMAP_SKYBOX = false;
  106709. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  106710. _this.REFLECTIONMAP_EXPLICIT = false;
  106711. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  106712. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  106713. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  106714. _this.INVERTCUBICMAP = false;
  106715. _this.REFLECTIONMAP_OPPOSITEZ = false;
  106716. _this.LODINREFLECTIONALPHA = false;
  106717. _this.GAMMAREFLECTION = false;
  106718. _this.RGBDREFLECTION = false;
  106719. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  106720. // Default BJS.
  106721. _this.MAINUV1 = false;
  106722. _this.MAINUV2 = false;
  106723. _this.UV1 = false;
  106724. _this.UV2 = false;
  106725. _this.CLIPPLANE = false;
  106726. _this.CLIPPLANE2 = false;
  106727. _this.CLIPPLANE3 = false;
  106728. _this.CLIPPLANE4 = false;
  106729. _this.POINTSIZE = false;
  106730. _this.FOG = false;
  106731. _this.NORMAL = false;
  106732. _this.NUM_BONE_INFLUENCERS = 0;
  106733. _this.BonesPerMesh = 0;
  106734. _this.INSTANCES = false;
  106735. _this.SHADOWFLOAT = false;
  106736. _this.rebuild();
  106737. return _this;
  106738. }
  106739. return BackgroundMaterialDefines;
  106740. }(BABYLON.MaterialDefines));
  106741. /**
  106742. * Background material used to create an efficient environement around your scene.
  106743. */
  106744. var BackgroundMaterial = /** @class */ (function (_super) {
  106745. __extends(BackgroundMaterial, _super);
  106746. /**
  106747. * Instantiates a Background Material in the given scene
  106748. * @param name The friendly name of the material
  106749. * @param scene The scene to add the material to
  106750. */
  106751. function BackgroundMaterial(name, scene) {
  106752. var _this = _super.call(this, name, scene) || this;
  106753. /**
  106754. * Key light Color (multiply against the environement texture)
  106755. */
  106756. _this.primaryColor = BABYLON.Color3.White();
  106757. _this._primaryColorShadowLevel = 0;
  106758. _this._primaryColorHighlightLevel = 0;
  106759. /**
  106760. * Reflection Texture used in the material.
  106761. * Should be author in a specific way for the best result (refer to the documentation).
  106762. */
  106763. _this.reflectionTexture = null;
  106764. /**
  106765. * Reflection Texture level of blur.
  106766. *
  106767. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  106768. * texture twice.
  106769. */
  106770. _this.reflectionBlur = 0;
  106771. /**
  106772. * Diffuse Texture used in the material.
  106773. * Should be author in a specific way for the best result (refer to the documentation).
  106774. */
  106775. _this.diffuseTexture = null;
  106776. _this._shadowLights = null;
  106777. /**
  106778. * Specify the list of lights casting shadow on the material.
  106779. * All scene shadow lights will be included if null.
  106780. */
  106781. _this.shadowLights = null;
  106782. /**
  106783. * Helps adjusting the shadow to a softer level if required.
  106784. * 0 means black shadows and 1 means no shadows.
  106785. */
  106786. _this.shadowLevel = 0;
  106787. /**
  106788. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  106789. * It is usually zero but might be interesting to modify according to your setup.
  106790. */
  106791. _this.sceneCenter = BABYLON.Vector3.Zero();
  106792. /**
  106793. * This helps specifying that the material is falling off to the sky box at grazing angle.
  106794. * This helps ensuring a nice transition when the camera goes under the ground.
  106795. */
  106796. _this.opacityFresnel = true;
  106797. /**
  106798. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  106799. * This helps adding a mirror texture on the ground.
  106800. */
  106801. _this.reflectionFresnel = false;
  106802. /**
  106803. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  106804. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  106805. */
  106806. _this.reflectionFalloffDistance = 0.0;
  106807. /**
  106808. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  106809. */
  106810. _this.reflectionAmount = 1.0;
  106811. /**
  106812. * This specifies the weight of the reflection at grazing angle.
  106813. */
  106814. _this.reflectionReflectance0 = 0.05;
  106815. /**
  106816. * This specifies the weight of the reflection at a perpendicular point of view.
  106817. */
  106818. _this.reflectionReflectance90 = 0.5;
  106819. /**
  106820. * Helps to directly use the maps channels instead of their level.
  106821. */
  106822. _this.useRGBColor = true;
  106823. /**
  106824. * This helps reducing the banding effect that could occur on the background.
  106825. */
  106826. _this.enableNoise = false;
  106827. _this._fovMultiplier = 1.0;
  106828. /**
  106829. * Enable the FOV adjustment feature controlled by fovMultiplier.
  106830. */
  106831. _this.useEquirectangularFOV = false;
  106832. _this._maxSimultaneousLights = 4;
  106833. /**
  106834. * Number of Simultaneous lights allowed on the material.
  106835. */
  106836. _this.maxSimultaneousLights = 4;
  106837. /**
  106838. * Keep track of the image processing observer to allow dispose and replace.
  106839. */
  106840. _this._imageProcessingObserver = null;
  106841. /**
  106842. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  106843. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  106844. */
  106845. _this.switchToBGR = false;
  106846. // Temp values kept as cache in the material.
  106847. _this._renderTargets = new BABYLON.SmartArray(16);
  106848. _this._reflectionControls = BABYLON.Vector4.Zero();
  106849. _this._white = BABYLON.Color3.White();
  106850. _this._primaryShadowColor = BABYLON.Color3.Black();
  106851. _this._primaryHighlightColor = BABYLON.Color3.Black();
  106852. // Setup the default processing configuration to the scene.
  106853. _this._attachImageProcessingConfiguration(null);
  106854. _this.getRenderTargetTextures = function () {
  106855. _this._renderTargets.reset();
  106856. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  106857. _this._renderTargets.push(_this._diffuseTexture);
  106858. }
  106859. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  106860. _this._renderTargets.push(_this._reflectionTexture);
  106861. }
  106862. return _this._renderTargets;
  106863. };
  106864. return _this;
  106865. }
  106866. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  106867. /**
  106868. * Experimental Internal Use Only.
  106869. *
  106870. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  106871. * This acts as a helper to set the primary color to a more "human friendly" value.
  106872. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  106873. * output color as close as possible from the chosen value.
  106874. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  106875. * part of lighting setup.)
  106876. */
  106877. get: function () {
  106878. return this.__perceptualColor;
  106879. },
  106880. set: function (value) {
  106881. this.__perceptualColor = value;
  106882. this._computePrimaryColorFromPerceptualColor();
  106883. this._markAllSubMeshesAsLightsDirty();
  106884. },
  106885. enumerable: true,
  106886. configurable: true
  106887. });
  106888. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  106889. /**
  106890. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  106891. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  106892. */
  106893. get: function () {
  106894. return this._primaryColorShadowLevel;
  106895. },
  106896. set: function (value) {
  106897. this._primaryColorShadowLevel = value;
  106898. this._computePrimaryColors();
  106899. this._markAllSubMeshesAsLightsDirty();
  106900. },
  106901. enumerable: true,
  106902. configurable: true
  106903. });
  106904. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  106905. /**
  106906. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  106907. * The primary color is used at the level chosen to define what the white area would look.
  106908. */
  106909. get: function () {
  106910. return this._primaryColorHighlightLevel;
  106911. },
  106912. set: function (value) {
  106913. this._primaryColorHighlightLevel = value;
  106914. this._computePrimaryColors();
  106915. this._markAllSubMeshesAsLightsDirty();
  106916. },
  106917. enumerable: true,
  106918. configurable: true
  106919. });
  106920. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  106921. /**
  106922. * Sets the reflection reflectance fresnel values according to the default standard
  106923. * empirically know to work well :-)
  106924. */
  106925. set: function (value) {
  106926. var reflectionWeight = value;
  106927. if (reflectionWeight < 0.5) {
  106928. reflectionWeight = reflectionWeight * 2.0;
  106929. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  106930. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  106931. }
  106932. else {
  106933. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  106934. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  106935. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  106936. }
  106937. },
  106938. enumerable: true,
  106939. configurable: true
  106940. });
  106941. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  106942. /**
  106943. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  106944. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  106945. * Recommended to be keep at 1.0 except for special cases.
  106946. */
  106947. get: function () {
  106948. return this._fovMultiplier;
  106949. },
  106950. set: function (value) {
  106951. if (isNaN(value)) {
  106952. value = 1.0;
  106953. }
  106954. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  106955. },
  106956. enumerable: true,
  106957. configurable: true
  106958. });
  106959. /**
  106960. * Attaches a new image processing configuration to the PBR Material.
  106961. * @param configuration (if null the scene configuration will be use)
  106962. */
  106963. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  106964. var _this = this;
  106965. if (configuration === this._imageProcessingConfiguration) {
  106966. return;
  106967. }
  106968. // Detaches observer.
  106969. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  106970. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  106971. }
  106972. // Pick the scene configuration if needed.
  106973. if (!configuration) {
  106974. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  106975. }
  106976. else {
  106977. this._imageProcessingConfiguration = configuration;
  106978. }
  106979. // Attaches observer.
  106980. if (this._imageProcessingConfiguration) {
  106981. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  106982. _this._computePrimaryColorFromPerceptualColor();
  106983. _this._markAllSubMeshesAsImageProcessingDirty();
  106984. });
  106985. }
  106986. };
  106987. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  106988. /**
  106989. * Gets the image processing configuration used either in this material.
  106990. */
  106991. get: function () {
  106992. return this._imageProcessingConfiguration;
  106993. },
  106994. /**
  106995. * Sets the Default image processing configuration used either in the this material.
  106996. *
  106997. * If sets to null, the scene one is in use.
  106998. */
  106999. set: function (value) {
  107000. this._attachImageProcessingConfiguration(value);
  107001. // Ensure the effect will be rebuilt.
  107002. this._markAllSubMeshesAsTexturesDirty();
  107003. },
  107004. enumerable: true,
  107005. configurable: true
  107006. });
  107007. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  107008. /**
  107009. * Gets wether the color curves effect is enabled.
  107010. */
  107011. get: function () {
  107012. return this.imageProcessingConfiguration.colorCurvesEnabled;
  107013. },
  107014. /**
  107015. * Sets wether the color curves effect is enabled.
  107016. */
  107017. set: function (value) {
  107018. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  107019. },
  107020. enumerable: true,
  107021. configurable: true
  107022. });
  107023. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  107024. /**
  107025. * Gets wether the color grading effect is enabled.
  107026. */
  107027. get: function () {
  107028. return this.imageProcessingConfiguration.colorGradingEnabled;
  107029. },
  107030. /**
  107031. * Gets wether the color grading effect is enabled.
  107032. */
  107033. set: function (value) {
  107034. this.imageProcessingConfiguration.colorGradingEnabled = value;
  107035. },
  107036. enumerable: true,
  107037. configurable: true
  107038. });
  107039. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  107040. /**
  107041. * Gets wether tonemapping is enabled or not.
  107042. */
  107043. get: function () {
  107044. return this._imageProcessingConfiguration.toneMappingEnabled;
  107045. },
  107046. /**
  107047. * Sets wether tonemapping is enabled or not
  107048. */
  107049. set: function (value) {
  107050. this._imageProcessingConfiguration.toneMappingEnabled = value;
  107051. },
  107052. enumerable: true,
  107053. configurable: true
  107054. });
  107055. ;
  107056. ;
  107057. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  107058. /**
  107059. * The camera exposure used on this material.
  107060. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  107061. * This corresponds to a photographic exposure.
  107062. */
  107063. get: function () {
  107064. return this._imageProcessingConfiguration.exposure;
  107065. },
  107066. /**
  107067. * The camera exposure used on this material.
  107068. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  107069. * This corresponds to a photographic exposure.
  107070. */
  107071. set: function (value) {
  107072. this._imageProcessingConfiguration.exposure = value;
  107073. },
  107074. enumerable: true,
  107075. configurable: true
  107076. });
  107077. ;
  107078. ;
  107079. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  107080. /**
  107081. * Gets The camera contrast used on this material.
  107082. */
  107083. get: function () {
  107084. return this._imageProcessingConfiguration.contrast;
  107085. },
  107086. /**
  107087. * Sets The camera contrast used on this material.
  107088. */
  107089. set: function (value) {
  107090. this._imageProcessingConfiguration.contrast = value;
  107091. },
  107092. enumerable: true,
  107093. configurable: true
  107094. });
  107095. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  107096. /**
  107097. * Gets the Color Grading 2D Lookup Texture.
  107098. */
  107099. get: function () {
  107100. return this._imageProcessingConfiguration.colorGradingTexture;
  107101. },
  107102. /**
  107103. * Sets the Color Grading 2D Lookup Texture.
  107104. */
  107105. set: function (value) {
  107106. this.imageProcessingConfiguration.colorGradingTexture = value;
  107107. },
  107108. enumerable: true,
  107109. configurable: true
  107110. });
  107111. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  107112. /**
  107113. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  107114. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  107115. * 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;
  107116. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  107117. */
  107118. get: function () {
  107119. return this.imageProcessingConfiguration.colorCurves;
  107120. },
  107121. /**
  107122. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  107123. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  107124. * 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;
  107125. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  107126. */
  107127. set: function (value) {
  107128. this.imageProcessingConfiguration.colorCurves = value;
  107129. },
  107130. enumerable: true,
  107131. configurable: true
  107132. });
  107133. Object.defineProperty(BackgroundMaterial.prototype, "hasRenderTargetTextures", {
  107134. /**
  107135. * Gets a boolean indicating that current material needs to register RTT
  107136. */
  107137. get: function () {
  107138. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  107139. return true;
  107140. }
  107141. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  107142. return true;
  107143. }
  107144. return false;
  107145. },
  107146. enumerable: true,
  107147. configurable: true
  107148. });
  107149. /**
  107150. * The entire material has been created in order to prevent overdraw.
  107151. * @returns false
  107152. */
  107153. BackgroundMaterial.prototype.needAlphaTesting = function () {
  107154. return true;
  107155. };
  107156. /**
  107157. * The entire material has been created in order to prevent overdraw.
  107158. * @returns true if blending is enable
  107159. */
  107160. BackgroundMaterial.prototype.needAlphaBlending = function () {
  107161. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  107162. };
  107163. /**
  107164. * Checks wether the material is ready to be rendered for a given mesh.
  107165. * @param mesh The mesh to render
  107166. * @param subMesh The submesh to check against
  107167. * @param useInstances Specify wether or not the material is used with instances
  107168. * @returns true if all the dependencies are ready (Textures, Effects...)
  107169. */
  107170. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  107171. var _this = this;
  107172. if (useInstances === void 0) { useInstances = false; }
  107173. if (subMesh.effect && this.isFrozen) {
  107174. if (this._wasPreviouslyReady) {
  107175. return true;
  107176. }
  107177. }
  107178. if (!subMesh._materialDefines) {
  107179. subMesh._materialDefines = new BackgroundMaterialDefines();
  107180. }
  107181. var scene = this.getScene();
  107182. var defines = subMesh._materialDefines;
  107183. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  107184. if (defines._renderId === scene.getRenderId()) {
  107185. return true;
  107186. }
  107187. }
  107188. var engine = scene.getEngine();
  107189. // Lights
  107190. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  107191. defines._needNormals = true;
  107192. // Textures
  107193. if (defines._areTexturesDirty) {
  107194. defines._needUVs = false;
  107195. if (scene.texturesEnabled) {
  107196. if (scene.getEngine().getCaps().textureLOD) {
  107197. defines.TEXTURELODSUPPORT = true;
  107198. }
  107199. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  107200. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  107201. return false;
  107202. }
  107203. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  107204. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  107205. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  107206. defines.OPACITYFRESNEL = this._opacityFresnel;
  107207. }
  107208. else {
  107209. defines.DIFFUSE = false;
  107210. defines.DIFFUSEHASALPHA = false;
  107211. defines.GAMMADIFFUSE = false;
  107212. defines.OPACITYFRESNEL = false;
  107213. }
  107214. var reflectionTexture = this._reflectionTexture;
  107215. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  107216. if (!reflectionTexture.isReadyOrNotBlocking()) {
  107217. return false;
  107218. }
  107219. defines.REFLECTION = true;
  107220. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  107221. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  107222. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  107223. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  107224. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  107225. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  107226. defines.REFLECTIONBGR = this.switchToBGR;
  107227. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  107228. defines.INVERTCUBICMAP = true;
  107229. }
  107230. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  107231. switch (reflectionTexture.coordinatesMode) {
  107232. case BABYLON.Texture.EXPLICIT_MODE:
  107233. defines.REFLECTIONMAP_EXPLICIT = true;
  107234. break;
  107235. case BABYLON.Texture.PLANAR_MODE:
  107236. defines.REFLECTIONMAP_PLANAR = true;
  107237. break;
  107238. case BABYLON.Texture.PROJECTION_MODE:
  107239. defines.REFLECTIONMAP_PROJECTION = true;
  107240. break;
  107241. case BABYLON.Texture.SKYBOX_MODE:
  107242. defines.REFLECTIONMAP_SKYBOX = true;
  107243. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
  107244. break;
  107245. case BABYLON.Texture.SPHERICAL_MODE:
  107246. defines.REFLECTIONMAP_SPHERICAL = true;
  107247. break;
  107248. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  107249. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  107250. break;
  107251. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  107252. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  107253. break;
  107254. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  107255. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  107256. break;
  107257. case BABYLON.Texture.CUBIC_MODE:
  107258. case BABYLON.Texture.INVCUBIC_MODE:
  107259. default:
  107260. defines.REFLECTIONMAP_CUBIC = true;
  107261. break;
  107262. }
  107263. if (this.reflectionFresnel) {
  107264. defines.REFLECTIONFRESNEL = true;
  107265. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  107266. this._reflectionControls.x = this.reflectionAmount;
  107267. this._reflectionControls.y = this.reflectionReflectance0;
  107268. this._reflectionControls.z = this.reflectionReflectance90;
  107269. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  107270. }
  107271. else {
  107272. defines.REFLECTIONFRESNEL = false;
  107273. defines.REFLECTIONFALLOFF = false;
  107274. }
  107275. }
  107276. else {
  107277. defines.REFLECTION = false;
  107278. defines.REFLECTIONFRESNEL = false;
  107279. defines.REFLECTIONFALLOFF = false;
  107280. defines.REFLECTIONBLUR = false;
  107281. defines.REFLECTIONMAP_3D = false;
  107282. defines.REFLECTIONMAP_SPHERICAL = false;
  107283. defines.REFLECTIONMAP_PLANAR = false;
  107284. defines.REFLECTIONMAP_CUBIC = false;
  107285. defines.REFLECTIONMAP_PROJECTION = false;
  107286. defines.REFLECTIONMAP_SKYBOX = false;
  107287. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  107288. defines.REFLECTIONMAP_EXPLICIT = false;
  107289. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  107290. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  107291. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  107292. defines.INVERTCUBICMAP = false;
  107293. defines.REFLECTIONMAP_OPPOSITEZ = false;
  107294. defines.LODINREFLECTIONALPHA = false;
  107295. defines.GAMMAREFLECTION = false;
  107296. defines.RGBDREFLECTION = false;
  107297. }
  107298. }
  107299. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  107300. defines.USERGBCOLOR = this._useRGBColor;
  107301. defines.NOISE = this._enableNoise;
  107302. }
  107303. if (defines._areLightsDirty) {
  107304. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  107305. }
  107306. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  107307. if (!this._imageProcessingConfiguration.isReady()) {
  107308. return false;
  107309. }
  107310. this._imageProcessingConfiguration.prepareDefines(defines);
  107311. }
  107312. // Misc.
  107313. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  107314. // Values that need to be evaluated on every frame
  107315. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  107316. // Attribs
  107317. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  107318. if (mesh) {
  107319. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  107320. mesh.createNormals(true);
  107321. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  107322. }
  107323. }
  107324. }
  107325. // Get correct effect
  107326. if (defines.isDirty) {
  107327. defines.markAsProcessed();
  107328. scene.resetCachedMaterial();
  107329. // Fallbacks
  107330. var fallbacks = new BABYLON.EffectFallbacks();
  107331. if (defines.FOG) {
  107332. fallbacks.addFallback(0, "FOG");
  107333. }
  107334. if (defines.POINTSIZE) {
  107335. fallbacks.addFallback(1, "POINTSIZE");
  107336. }
  107337. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  107338. if (defines.NUM_BONE_INFLUENCERS > 0) {
  107339. fallbacks.addCPUSkinningFallback(0, mesh);
  107340. }
  107341. //Attributes
  107342. var attribs = [BABYLON.VertexBuffer.PositionKind];
  107343. if (defines.NORMAL) {
  107344. attribs.push(BABYLON.VertexBuffer.NormalKind);
  107345. }
  107346. if (defines.UV1) {
  107347. attribs.push(BABYLON.VertexBuffer.UVKind);
  107348. }
  107349. if (defines.UV2) {
  107350. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  107351. }
  107352. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  107353. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  107354. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  107355. "vFogInfos", "vFogColor", "pointSize",
  107356. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "mBones",
  107357. "vPrimaryColor", "vPrimaryColorShadow",
  107358. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  107359. "shadowLevel", "alpha",
  107360. "vBackgroundCenter", "vReflectionControl",
  107361. "vDiffuseInfos", "diffuseMatrix",
  107362. ];
  107363. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  107364. var uniformBuffers = ["Material", "Scene"];
  107365. if (BABYLON.ImageProcessingConfiguration) {
  107366. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  107367. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  107368. }
  107369. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  107370. uniformsNames: uniforms,
  107371. uniformBuffersNames: uniformBuffers,
  107372. samplers: samplers,
  107373. defines: defines,
  107374. maxSimultaneousLights: this._maxSimultaneousLights
  107375. });
  107376. var onCompiled = function (effect) {
  107377. if (_this.onCompiled) {
  107378. _this.onCompiled(effect);
  107379. }
  107380. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  107381. };
  107382. var join = defines.toString();
  107383. subMesh.setEffect(scene.getEngine().createEffect("background", {
  107384. attributes: attribs,
  107385. uniformsNames: uniforms,
  107386. uniformBuffersNames: uniformBuffers,
  107387. samplers: samplers,
  107388. defines: join,
  107389. fallbacks: fallbacks,
  107390. onCompiled: onCompiled,
  107391. onError: this.onError,
  107392. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  107393. }, engine), defines);
  107394. this.buildUniformLayout();
  107395. }
  107396. if (!subMesh.effect || !subMesh.effect.isReady()) {
  107397. return false;
  107398. }
  107399. defines._renderId = scene.getRenderId();
  107400. this._wasPreviouslyReady = true;
  107401. return true;
  107402. };
  107403. /**
  107404. * Compute the primary color according to the chosen perceptual color.
  107405. */
  107406. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  107407. if (!this.__perceptualColor) {
  107408. return;
  107409. }
  107410. this._primaryColor.copyFrom(this.__perceptualColor);
  107411. // Revert gamma space.
  107412. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  107413. // Revert image processing configuration.
  107414. if (this._imageProcessingConfiguration) {
  107415. // Revert Exposure.
  107416. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  107417. }
  107418. this._computePrimaryColors();
  107419. };
  107420. /**
  107421. * Compute the highlights and shadow colors according to their chosen levels.
  107422. */
  107423. BackgroundMaterial.prototype._computePrimaryColors = function () {
  107424. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  107425. return;
  107426. }
  107427. // Find the highlight color based on the configuration.
  107428. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  107429. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  107430. // Find the shadow color based on the configuration.
  107431. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  107432. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  107433. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  107434. };
  107435. /**
  107436. * Build the uniform buffer used in the material.
  107437. */
  107438. BackgroundMaterial.prototype.buildUniformLayout = function () {
  107439. // Order is important !
  107440. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  107441. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  107442. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  107443. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  107444. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  107445. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  107446. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  107447. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  107448. this._uniformBuffer.addUniform("pointSize", 1);
  107449. this._uniformBuffer.addUniform("shadowLevel", 1);
  107450. this._uniformBuffer.addUniform("alpha", 1);
  107451. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  107452. this._uniformBuffer.addUniform("vReflectionControl", 4);
  107453. this._uniformBuffer.create();
  107454. };
  107455. /**
  107456. * Unbind the material.
  107457. */
  107458. BackgroundMaterial.prototype.unbind = function () {
  107459. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  107460. this._uniformBuffer.setTexture("diffuseSampler", null);
  107461. }
  107462. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  107463. this._uniformBuffer.setTexture("reflectionSampler", null);
  107464. }
  107465. _super.prototype.unbind.call(this);
  107466. };
  107467. /**
  107468. * Bind only the world matrix to the material.
  107469. * @param world The world matrix to bind.
  107470. */
  107471. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  107472. this._activeEffect.setMatrix("world", world);
  107473. };
  107474. /**
  107475. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  107476. * @param world The world matrix to bind.
  107477. * @param subMesh The submesh to bind for.
  107478. */
  107479. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  107480. var scene = this.getScene();
  107481. var defines = subMesh._materialDefines;
  107482. if (!defines) {
  107483. return;
  107484. }
  107485. var effect = subMesh.effect;
  107486. if (!effect) {
  107487. return;
  107488. }
  107489. this._activeEffect = effect;
  107490. // Matrices
  107491. this.bindOnlyWorldMatrix(world);
  107492. // Bones
  107493. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  107494. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  107495. if (mustRebind) {
  107496. this._uniformBuffer.bindToEffect(effect, "Material");
  107497. this.bindViewProjection(effect);
  107498. var reflectionTexture = this._reflectionTexture;
  107499. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  107500. // Texture uniforms
  107501. if (scene.texturesEnabled) {
  107502. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  107503. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  107504. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  107505. }
  107506. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  107507. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  107508. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  107509. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  107510. }
  107511. }
  107512. if (this.shadowLevel > 0) {
  107513. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  107514. }
  107515. this._uniformBuffer.updateFloat("alpha", this.alpha);
  107516. // Point size
  107517. if (this.pointsCloud) {
  107518. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  107519. }
  107520. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  107521. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  107522. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  107523. }
  107524. else {
  107525. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  107526. }
  107527. }
  107528. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  107529. // Textures
  107530. if (scene.texturesEnabled) {
  107531. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  107532. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  107533. }
  107534. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  107535. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  107536. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  107537. }
  107538. else if (!defines.REFLECTIONBLUR) {
  107539. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  107540. }
  107541. else {
  107542. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  107543. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  107544. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  107545. }
  107546. if (defines.REFLECTIONFRESNEL) {
  107547. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  107548. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  107549. }
  107550. }
  107551. }
  107552. // Clip plane
  107553. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  107554. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  107555. }
  107556. if (mustRebind || !this.isFrozen) {
  107557. if (scene.lightsEnabled) {
  107558. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  107559. }
  107560. // View
  107561. this.bindView(effect);
  107562. // Fog
  107563. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  107564. // image processing
  107565. if (this._imageProcessingConfiguration) {
  107566. this._imageProcessingConfiguration.bind(this._activeEffect);
  107567. }
  107568. }
  107569. this._uniformBuffer.update();
  107570. this._afterBind(mesh, this._activeEffect);
  107571. };
  107572. /**
  107573. * Dispose the material.
  107574. * @param forceDisposeEffect Force disposal of the associated effect.
  107575. * @param forceDisposeTextures Force disposal of the associated textures.
  107576. */
  107577. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  107578. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  107579. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  107580. if (forceDisposeTextures) {
  107581. if (this.diffuseTexture) {
  107582. this.diffuseTexture.dispose();
  107583. }
  107584. if (this.reflectionTexture) {
  107585. this.reflectionTexture.dispose();
  107586. }
  107587. }
  107588. this._renderTargets.dispose();
  107589. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  107590. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  107591. }
  107592. _super.prototype.dispose.call(this, forceDisposeEffect);
  107593. };
  107594. /**
  107595. * Clones the material.
  107596. * @param name The cloned name.
  107597. * @returns The cloned material.
  107598. */
  107599. BackgroundMaterial.prototype.clone = function (name) {
  107600. var _this = this;
  107601. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  107602. };
  107603. /**
  107604. * Serializes the current material to its JSON representation.
  107605. * @returns The JSON representation.
  107606. */
  107607. BackgroundMaterial.prototype.serialize = function () {
  107608. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  107609. serializationObject.customType = "BABYLON.BackgroundMaterial";
  107610. return serializationObject;
  107611. };
  107612. /**
  107613. * Gets the class name of the material
  107614. * @returns "BackgroundMaterial"
  107615. */
  107616. BackgroundMaterial.prototype.getClassName = function () {
  107617. return "BackgroundMaterial";
  107618. };
  107619. /**
  107620. * Parse a JSON input to create back a background material.
  107621. * @param source The JSON data to parse
  107622. * @param scene The scene to create the parsed material in
  107623. * @param rootUrl The root url of the assets the material depends upon
  107624. * @returns the instantiated BackgroundMaterial.
  107625. */
  107626. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  107627. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  107628. };
  107629. /**
  107630. * Standard reflectance value at parallel view angle.
  107631. */
  107632. BackgroundMaterial.StandardReflectance0 = 0.05;
  107633. /**
  107634. * Standard reflectance value at grazing angle.
  107635. */
  107636. BackgroundMaterial.StandardReflectance90 = 0.5;
  107637. __decorate([
  107638. BABYLON.serializeAsColor3()
  107639. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  107640. __decorate([
  107641. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  107642. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  107643. __decorate([
  107644. BABYLON.serializeAsColor3()
  107645. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  107646. __decorate([
  107647. BABYLON.serialize()
  107648. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  107649. __decorate([
  107650. BABYLON.serialize()
  107651. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  107652. __decorate([
  107653. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  107654. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  107655. __decorate([
  107656. BABYLON.serializeAsTexture()
  107657. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  107658. __decorate([
  107659. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  107660. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  107661. __decorate([
  107662. BABYLON.serialize()
  107663. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  107664. __decorate([
  107665. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  107666. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  107667. __decorate([
  107668. BABYLON.serializeAsTexture()
  107669. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  107670. __decorate([
  107671. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  107672. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  107673. __decorate([
  107674. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  107675. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  107676. __decorate([
  107677. BABYLON.serialize()
  107678. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  107679. __decorate([
  107680. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  107681. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  107682. __decorate([
  107683. BABYLON.serializeAsVector3()
  107684. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  107685. __decorate([
  107686. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  107687. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  107688. __decorate([
  107689. BABYLON.serialize()
  107690. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  107691. __decorate([
  107692. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  107693. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  107694. __decorate([
  107695. BABYLON.serialize()
  107696. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  107697. __decorate([
  107698. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  107699. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  107700. __decorate([
  107701. BABYLON.serialize()
  107702. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  107703. __decorate([
  107704. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  107705. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  107706. __decorate([
  107707. BABYLON.serialize()
  107708. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  107709. __decorate([
  107710. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  107711. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  107712. __decorate([
  107713. BABYLON.serialize()
  107714. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  107715. __decorate([
  107716. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  107717. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  107718. __decorate([
  107719. BABYLON.serialize()
  107720. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  107721. __decorate([
  107722. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  107723. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  107724. __decorate([
  107725. BABYLON.serialize()
  107726. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  107727. __decorate([
  107728. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  107729. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  107730. __decorate([
  107731. BABYLON.serialize()
  107732. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  107733. __decorate([
  107734. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  107735. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  107736. __decorate([
  107737. BABYLON.serialize()
  107738. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  107739. __decorate([
  107740. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  107741. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  107742. __decorate([
  107743. BABYLON.serializeAsImageProcessingConfiguration()
  107744. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  107745. return BackgroundMaterial;
  107746. }(BABYLON.PushMaterial));
  107747. BABYLON.BackgroundMaterial = BackgroundMaterial;
  107748. })(BABYLON || (BABYLON = {}));
  107749. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  107750. var __assign = (this && this.__assign) || function () {
  107751. __assign = Object.assign || function(t) {
  107752. for (var s, i = 1, n = arguments.length; i < n; i++) {
  107753. s = arguments[i];
  107754. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  107755. t[p] = s[p];
  107756. }
  107757. return t;
  107758. };
  107759. return __assign.apply(this, arguments);
  107760. };
  107761. var BABYLON;
  107762. (function (BABYLON) {
  107763. /**
  107764. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  107765. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  107766. * It also helps with the default setup of your imageProcessing configuration.
  107767. */
  107768. var EnvironmentHelper = /** @class */ (function () {
  107769. /**
  107770. * constructor
  107771. * @param options
  107772. * @param scene The scene to add the material to
  107773. */
  107774. function EnvironmentHelper(options, scene) {
  107775. var _this = this;
  107776. this._errorHandler = function (message, exception) {
  107777. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  107778. };
  107779. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  107780. this._scene = scene;
  107781. this.onErrorObservable = new BABYLON.Observable();
  107782. this._setupBackground();
  107783. this._setupImageProcessing();
  107784. }
  107785. /**
  107786. * Creates the default options for the helper.
  107787. */
  107788. EnvironmentHelper._getDefaultOptions = function () {
  107789. return {
  107790. createGround: true,
  107791. groundSize: 15,
  107792. groundTexture: this._groundTextureCDNUrl,
  107793. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  107794. groundOpacity: 0.9,
  107795. enableGroundShadow: true,
  107796. groundShadowLevel: 0.5,
  107797. enableGroundMirror: false,
  107798. groundMirrorSizeRatio: 0.3,
  107799. groundMirrorBlurKernel: 64,
  107800. groundMirrorAmount: 1,
  107801. groundMirrorFresnelWeight: 1,
  107802. groundMirrorFallOffDistance: 0,
  107803. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  107804. groundYBias: 0.00001,
  107805. createSkybox: true,
  107806. skyboxSize: 20,
  107807. skyboxTexture: this._skyboxTextureCDNUrl,
  107808. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  107809. backgroundYRotation: 0,
  107810. sizeAuto: true,
  107811. rootPosition: BABYLON.Vector3.Zero(),
  107812. setupImageProcessing: true,
  107813. environmentTexture: this._environmentTextureCDNUrl,
  107814. cameraExposure: 0.8,
  107815. cameraContrast: 1.2,
  107816. toneMappingEnabled: true,
  107817. };
  107818. };
  107819. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  107820. /**
  107821. * Gets the root mesh created by the helper.
  107822. */
  107823. get: function () {
  107824. return this._rootMesh;
  107825. },
  107826. enumerable: true,
  107827. configurable: true
  107828. });
  107829. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  107830. /**
  107831. * Gets the skybox created by the helper.
  107832. */
  107833. get: function () {
  107834. return this._skybox;
  107835. },
  107836. enumerable: true,
  107837. configurable: true
  107838. });
  107839. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  107840. /**
  107841. * Gets the skybox texture created by the helper.
  107842. */
  107843. get: function () {
  107844. return this._skyboxTexture;
  107845. },
  107846. enumerable: true,
  107847. configurable: true
  107848. });
  107849. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  107850. /**
  107851. * Gets the skybox material created by the helper.
  107852. */
  107853. get: function () {
  107854. return this._skyboxMaterial;
  107855. },
  107856. enumerable: true,
  107857. configurable: true
  107858. });
  107859. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  107860. /**
  107861. * Gets the ground mesh created by the helper.
  107862. */
  107863. get: function () {
  107864. return this._ground;
  107865. },
  107866. enumerable: true,
  107867. configurable: true
  107868. });
  107869. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  107870. /**
  107871. * Gets the ground texture created by the helper.
  107872. */
  107873. get: function () {
  107874. return this._groundTexture;
  107875. },
  107876. enumerable: true,
  107877. configurable: true
  107878. });
  107879. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  107880. /**
  107881. * Gets the ground mirror created by the helper.
  107882. */
  107883. get: function () {
  107884. return this._groundMirror;
  107885. },
  107886. enumerable: true,
  107887. configurable: true
  107888. });
  107889. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  107890. /**
  107891. * Gets the ground mirror render list to helps pushing the meshes
  107892. * you wish in the ground reflection.
  107893. */
  107894. get: function () {
  107895. if (this._groundMirror) {
  107896. return this._groundMirror.renderList;
  107897. }
  107898. return null;
  107899. },
  107900. enumerable: true,
  107901. configurable: true
  107902. });
  107903. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  107904. /**
  107905. * Gets the ground material created by the helper.
  107906. */
  107907. get: function () {
  107908. return this._groundMaterial;
  107909. },
  107910. enumerable: true,
  107911. configurable: true
  107912. });
  107913. /**
  107914. * Updates the background according to the new options
  107915. * @param options
  107916. */
  107917. EnvironmentHelper.prototype.updateOptions = function (options) {
  107918. var newOptions = __assign({}, this._options, options);
  107919. if (this._ground && !newOptions.createGround) {
  107920. this._ground.dispose();
  107921. this._ground = null;
  107922. }
  107923. if (this._groundMaterial && !newOptions.createGround) {
  107924. this._groundMaterial.dispose();
  107925. this._groundMaterial = null;
  107926. }
  107927. if (this._groundTexture) {
  107928. if (this._options.groundTexture != newOptions.groundTexture) {
  107929. this._groundTexture.dispose();
  107930. this._groundTexture = null;
  107931. }
  107932. }
  107933. if (this._skybox && !newOptions.createSkybox) {
  107934. this._skybox.dispose();
  107935. this._skybox = null;
  107936. }
  107937. if (this._skyboxMaterial && !newOptions.createSkybox) {
  107938. this._skyboxMaterial.dispose();
  107939. this._skyboxMaterial = null;
  107940. }
  107941. if (this._skyboxTexture) {
  107942. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  107943. this._skyboxTexture.dispose();
  107944. this._skyboxTexture = null;
  107945. }
  107946. }
  107947. if (this._groundMirror && !newOptions.enableGroundMirror) {
  107948. this._groundMirror.dispose();
  107949. this._groundMirror = null;
  107950. }
  107951. if (this._scene.environmentTexture) {
  107952. if (this._options.environmentTexture != newOptions.environmentTexture) {
  107953. this._scene.environmentTexture.dispose();
  107954. }
  107955. }
  107956. this._options = newOptions;
  107957. this._setupBackground();
  107958. this._setupImageProcessing();
  107959. };
  107960. /**
  107961. * Sets the primary color of all the available elements.
  107962. * @param color the main color to affect to the ground and the background
  107963. */
  107964. EnvironmentHelper.prototype.setMainColor = function (color) {
  107965. if (this.groundMaterial) {
  107966. this.groundMaterial.primaryColor = color;
  107967. }
  107968. if (this.skyboxMaterial) {
  107969. this.skyboxMaterial.primaryColor = color;
  107970. }
  107971. if (this.groundMirror) {
  107972. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  107973. }
  107974. };
  107975. /**
  107976. * Setup the image processing according to the specified options.
  107977. */
  107978. EnvironmentHelper.prototype._setupImageProcessing = function () {
  107979. if (this._options.setupImageProcessing) {
  107980. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  107981. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  107982. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  107983. this._setupEnvironmentTexture();
  107984. }
  107985. };
  107986. /**
  107987. * Setup the environment texture according to the specified options.
  107988. */
  107989. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  107990. if (this._scene.environmentTexture) {
  107991. return;
  107992. }
  107993. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  107994. this._scene.environmentTexture = this._options.environmentTexture;
  107995. return;
  107996. }
  107997. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  107998. this._scene.environmentTexture = environmentTexture;
  107999. };
  108000. /**
  108001. * Setup the background according to the specified options.
  108002. */
  108003. EnvironmentHelper.prototype._setupBackground = function () {
  108004. if (!this._rootMesh) {
  108005. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  108006. }
  108007. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  108008. var sceneSize = this._getSceneSize();
  108009. if (this._options.createGround) {
  108010. this._setupGround(sceneSize);
  108011. this._setupGroundMaterial();
  108012. this._setupGroundDiffuseTexture();
  108013. if (this._options.enableGroundMirror) {
  108014. this._setupGroundMirrorTexture(sceneSize);
  108015. }
  108016. this._setupMirrorInGroundMaterial();
  108017. }
  108018. if (this._options.createSkybox) {
  108019. this._setupSkybox(sceneSize);
  108020. this._setupSkyboxMaterial();
  108021. this._setupSkyboxReflectionTexture();
  108022. }
  108023. this._rootMesh.position.x = sceneSize.rootPosition.x;
  108024. this._rootMesh.position.z = sceneSize.rootPosition.z;
  108025. this._rootMesh.position.y = sceneSize.rootPosition.y;
  108026. };
  108027. /**
  108028. * Get the scene sizes according to the setup.
  108029. */
  108030. EnvironmentHelper.prototype._getSceneSize = function () {
  108031. var _this = this;
  108032. var groundSize = this._options.groundSize;
  108033. var skyboxSize = this._options.skyboxSize;
  108034. var rootPosition = this._options.rootPosition;
  108035. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  108036. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  108037. }
  108038. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  108039. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  108040. });
  108041. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  108042. if (this._options.sizeAuto) {
  108043. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  108044. this._scene.activeCamera.upperRadiusLimit) {
  108045. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  108046. skyboxSize = groundSize;
  108047. }
  108048. var sceneDiagonalLenght = sceneDiagonal.length();
  108049. if (sceneDiagonalLenght > groundSize) {
  108050. groundSize = sceneDiagonalLenght * 2;
  108051. skyboxSize = groundSize;
  108052. }
  108053. // 10 % bigger.
  108054. groundSize *= 1.1;
  108055. skyboxSize *= 1.5;
  108056. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  108057. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  108058. }
  108059. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  108060. };
  108061. /**
  108062. * Setup the ground according to the specified options.
  108063. */
  108064. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  108065. var _this = this;
  108066. if (!this._ground || this._ground.isDisposed()) {
  108067. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  108068. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  108069. this._ground.parent = this._rootMesh;
  108070. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  108071. }
  108072. this._ground.receiveShadows = this._options.enableGroundShadow;
  108073. };
  108074. /**
  108075. * Setup the ground material according to the specified options.
  108076. */
  108077. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  108078. if (!this._groundMaterial) {
  108079. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  108080. }
  108081. this._groundMaterial.alpha = this._options.groundOpacity;
  108082. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  108083. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  108084. this._groundMaterial.primaryColor = this._options.groundColor;
  108085. this._groundMaterial.useRGBColor = false;
  108086. this._groundMaterial.enableNoise = true;
  108087. if (this._ground) {
  108088. this._ground.material = this._groundMaterial;
  108089. }
  108090. };
  108091. /**
  108092. * Setup the ground diffuse texture according to the specified options.
  108093. */
  108094. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  108095. if (!this._groundMaterial) {
  108096. return;
  108097. }
  108098. if (this._groundTexture) {
  108099. return;
  108100. }
  108101. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  108102. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  108103. return;
  108104. }
  108105. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  108106. diffuseTexture.gammaSpace = false;
  108107. diffuseTexture.hasAlpha = true;
  108108. this._groundMaterial.diffuseTexture = diffuseTexture;
  108109. };
  108110. /**
  108111. * Setup the ground mirror texture according to the specified options.
  108112. */
  108113. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  108114. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  108115. if (!this._groundMirror) {
  108116. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  108117. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  108118. this._groundMirror.anisotropicFilteringLevel = 1;
  108119. this._groundMirror.wrapU = wrapping;
  108120. this._groundMirror.wrapV = wrapping;
  108121. this._groundMirror.gammaSpace = false;
  108122. if (this._groundMirror.renderList) {
  108123. for (var i = 0; i < this._scene.meshes.length; i++) {
  108124. var mesh = this._scene.meshes[i];
  108125. if (mesh !== this._ground &&
  108126. mesh !== this._skybox &&
  108127. mesh !== this._rootMesh) {
  108128. this._groundMirror.renderList.push(mesh);
  108129. }
  108130. }
  108131. }
  108132. }
  108133. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  108134. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  108135. };
  108136. /**
  108137. * Setup the ground to receive the mirror texture.
  108138. */
  108139. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  108140. if (this._groundMaterial) {
  108141. this._groundMaterial.reflectionTexture = this._groundMirror;
  108142. this._groundMaterial.reflectionFresnel = true;
  108143. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  108144. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  108145. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  108146. }
  108147. };
  108148. /**
  108149. * Setup the skybox according to the specified options.
  108150. */
  108151. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  108152. var _this = this;
  108153. if (!this._skybox || this._skybox.isDisposed()) {
  108154. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  108155. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  108156. }
  108157. this._skybox.parent = this._rootMesh;
  108158. };
  108159. /**
  108160. * Setup the skybox material according to the specified options.
  108161. */
  108162. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  108163. if (!this._skybox) {
  108164. return;
  108165. }
  108166. if (!this._skyboxMaterial) {
  108167. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  108168. }
  108169. this._skyboxMaterial.useRGBColor = false;
  108170. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  108171. this._skyboxMaterial.enableNoise = true;
  108172. this._skybox.material = this._skyboxMaterial;
  108173. };
  108174. /**
  108175. * Setup the skybox reflection texture according to the specified options.
  108176. */
  108177. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  108178. if (!this._skyboxMaterial) {
  108179. return;
  108180. }
  108181. if (this._skyboxTexture) {
  108182. return;
  108183. }
  108184. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  108185. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  108186. return;
  108187. }
  108188. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  108189. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  108190. this._skyboxTexture.gammaSpace = false;
  108191. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  108192. };
  108193. /**
  108194. * Dispose all the elements created by the Helper.
  108195. */
  108196. EnvironmentHelper.prototype.dispose = function () {
  108197. if (this._groundMaterial) {
  108198. this._groundMaterial.dispose(true, true);
  108199. }
  108200. if (this._skyboxMaterial) {
  108201. this._skyboxMaterial.dispose(true, true);
  108202. }
  108203. this._rootMesh.dispose(false);
  108204. };
  108205. /**
  108206. * Default ground texture URL.
  108207. */
  108208. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  108209. /**
  108210. * Default skybox texture URL.
  108211. */
  108212. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  108213. /**
  108214. * Default environment texture URL.
  108215. */
  108216. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env";
  108217. return EnvironmentHelper;
  108218. }());
  108219. BABYLON.EnvironmentHelper = EnvironmentHelper;
  108220. })(BABYLON || (BABYLON = {}));
  108221. //# sourceMappingURL=babylon.environmentHelper.js.map
  108222. var BABYLON;
  108223. (function (BABYLON) {
  108224. /** Internal class used to store shapes for emitters */
  108225. var ParticleSystemSetEmitterCreationOptions = /** @class */ (function () {
  108226. function ParticleSystemSetEmitterCreationOptions() {
  108227. }
  108228. return ParticleSystemSetEmitterCreationOptions;
  108229. }());
  108230. /**
  108231. * Represents a set of particle systems working together to create a specific effect
  108232. */
  108233. var ParticleSystemSet = /** @class */ (function () {
  108234. function ParticleSystemSet() {
  108235. /**
  108236. * Gets the particle system list
  108237. */
  108238. this.systems = new Array();
  108239. }
  108240. Object.defineProperty(ParticleSystemSet.prototype, "emitterNode", {
  108241. /**
  108242. * Gets the emitter node used with this set
  108243. */
  108244. get: function () {
  108245. return this._emitterNode;
  108246. },
  108247. enumerable: true,
  108248. configurable: true
  108249. });
  108250. /**
  108251. * Creates a new emitter mesh as a sphere
  108252. * @param options defines the options used to create the sphere
  108253. * @param renderingGroupId defines the renderingGroupId to use for the sphere
  108254. * @param scene defines the hosting scene
  108255. */
  108256. ParticleSystemSet.prototype.setEmitterAsSphere = function (options, renderingGroupId, scene) {
  108257. if (this._emitterNode) {
  108258. this._emitterNode.dispose();
  108259. }
  108260. this._emitterCreationOptions = {
  108261. kind: "Sphere",
  108262. options: options,
  108263. renderingGroupId: renderingGroupId
  108264. };
  108265. var emitterMesh = BABYLON.MeshBuilder.CreateSphere("emitterSphere", { diameter: options.diameter, segments: options.segments }, scene);
  108266. emitterMesh.renderingGroupId = renderingGroupId;
  108267. var material = new BABYLON.StandardMaterial("emitterSphereMaterial", scene);
  108268. material.emissiveColor = options.color;
  108269. emitterMesh.material = material;
  108270. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  108271. var system = _a[_i];
  108272. system.emitter = emitterMesh;
  108273. }
  108274. this._emitterNode = emitterMesh;
  108275. };
  108276. /**
  108277. * Starts all particle systems of the set
  108278. * @param emitter defines an optional mesh to use as emitter for the particle systems
  108279. */
  108280. ParticleSystemSet.prototype.start = function (emitter) {
  108281. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  108282. var system = _a[_i];
  108283. if (emitter) {
  108284. system.emitter = emitter;
  108285. }
  108286. system.start();
  108287. }
  108288. };
  108289. /**
  108290. * Release all associated resources
  108291. */
  108292. ParticleSystemSet.prototype.dispose = function () {
  108293. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  108294. var system = _a[_i];
  108295. system.dispose();
  108296. }
  108297. this.systems = [];
  108298. if (this._emitterNode) {
  108299. this._emitterNode.dispose();
  108300. this._emitterNode = null;
  108301. }
  108302. };
  108303. /**
  108304. * Serialize the set into a JSON compatible object
  108305. * @returns a JSON compatible representation of the set
  108306. */
  108307. ParticleSystemSet.prototype.serialize = function () {
  108308. var result = {};
  108309. result.systems = [];
  108310. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  108311. var system = _a[_i];
  108312. result.systems.push(system.serialize());
  108313. }
  108314. if (this._emitterNode) {
  108315. result.emitter = this._emitterCreationOptions;
  108316. }
  108317. return result;
  108318. };
  108319. /**
  108320. * Parse a new ParticleSystemSet from a serialized source
  108321. * @param data defines a JSON compatible representation of the set
  108322. * @param scene defines the hosting scene
  108323. * @param gpu defines if we want GPU particles or CPU particles
  108324. * @returns a new ParticleSystemSet
  108325. */
  108326. ParticleSystemSet.Parse = function (data, scene, gpu) {
  108327. if (gpu === void 0) { gpu = false; }
  108328. var result = new ParticleSystemSet();
  108329. var rootUrl = BABYLON.ParticleHelper.BaseAssetsUrl + "/textures/";
  108330. scene = scene || BABYLON.Engine.LastCreatedScene;
  108331. for (var _i = 0, _a = data.systems; _i < _a.length; _i++) {
  108332. var system = _a[_i];
  108333. result.systems.push(gpu ? BABYLON.GPUParticleSystem.Parse(system, scene, rootUrl) : BABYLON.ParticleSystem.Parse(system, scene, rootUrl));
  108334. }
  108335. if (data.emitter) {
  108336. var options = data.emitter.options;
  108337. switch (data.emitter.kind) {
  108338. case "Sphere":
  108339. result.setEmitterAsSphere({
  108340. diameter: options.diameter,
  108341. segments: options.segments,
  108342. color: BABYLON.Color3.FromArray(options.color)
  108343. }, data.emitter.renderingGroupId, scene);
  108344. break;
  108345. }
  108346. }
  108347. return result;
  108348. };
  108349. return ParticleSystemSet;
  108350. }());
  108351. BABYLON.ParticleSystemSet = ParticleSystemSet;
  108352. })(BABYLON || (BABYLON = {}));
  108353. //# sourceMappingURL=babylon.particleSystemSet.js.map
  108354. var BABYLON;
  108355. (function (BABYLON) {
  108356. /**
  108357. * This class is made for on one-liner static method to help creating particle system set.
  108358. */
  108359. var ParticleHelper = /** @class */ (function () {
  108360. function ParticleHelper() {
  108361. }
  108362. /**
  108363. * Create a default particle system that you can tweak
  108364. * @param emitter defines the emitter to use
  108365. * @param capacity defines the system capacity (default is 500 particles)
  108366. * @param scene defines the hosting scene
  108367. * @param useGPU defines if a GPUParticleSystem must be created (default is false)
  108368. * @returns the new Particle system
  108369. */
  108370. ParticleHelper.CreateDefault = function (emitter, capacity, scene, useGPU) {
  108371. if (capacity === void 0) { capacity = 500; }
  108372. if (useGPU === void 0) { useGPU = false; }
  108373. var system;
  108374. if (useGPU) {
  108375. system = new BABYLON.GPUParticleSystem("default system", { capacity: capacity }, scene);
  108376. }
  108377. else {
  108378. system = new BABYLON.ParticleSystem("default system", capacity, scene);
  108379. }
  108380. system.emitter = emitter;
  108381. system.particleTexture = new BABYLON.Texture("https://www.babylonjs.com/assets/Flare.png", system.getScene());
  108382. system.createConeEmitter(0.1, Math.PI / 4);
  108383. // Particle color
  108384. system.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  108385. system.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  108386. system.colorDead = new BABYLON.Color4(1.0, 1.0, 1.0, 0.0);
  108387. // Particle Size
  108388. system.minSize = 0.1;
  108389. system.maxSize = 0.1;
  108390. // Emission speed
  108391. system.minEmitPower = 2;
  108392. system.maxEmitPower = 2;
  108393. // Update speed
  108394. system.updateSpeed = 1 / 60;
  108395. system.emitRate = 30;
  108396. return system;
  108397. };
  108398. /**
  108399. * This is the main static method (one-liner) of this helper to create different particle systems
  108400. * @param type This string represents the type to the particle system to create
  108401. * @param scene The scene where the particle system should live
  108402. * @param gpu If the system will use gpu
  108403. * @returns the ParticleSystemSet created
  108404. */
  108405. ParticleHelper.CreateAsync = function (type, scene, gpu) {
  108406. if (gpu === void 0) { gpu = false; }
  108407. if (!scene) {
  108408. scene = BABYLON.Engine.LastCreatedScene;
  108409. ;
  108410. }
  108411. var token = {};
  108412. scene._addPendingData(token);
  108413. return new Promise(function (resolve, reject) {
  108414. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  108415. scene._removePendingData(token);
  108416. return reject("Particle system with GPU is not supported.");
  108417. }
  108418. BABYLON.Tools.LoadFile(ParticleHelper.BaseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  108419. scene._removePendingData(token);
  108420. var newData = JSON.parse(data.toString());
  108421. return resolve(BABYLON.ParticleSystemSet.Parse(newData, scene, gpu));
  108422. }, undefined, undefined, undefined, function (req, exception) {
  108423. scene._removePendingData(token);
  108424. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  108425. });
  108426. });
  108427. };
  108428. /**
  108429. * Static function used to export a particle system to a ParticleSystemSet variable.
  108430. * Please note that the emitter shape is not exported
  108431. * @param system defines the particle systems to export
  108432. */
  108433. ParticleHelper.ExportSet = function (systems) {
  108434. var set = new BABYLON.ParticleSystemSet();
  108435. for (var _i = 0, systems_1 = systems; _i < systems_1.length; _i++) {
  108436. var system = systems_1[_i];
  108437. set.systems.push(system);
  108438. }
  108439. return set;
  108440. };
  108441. /**
  108442. * Gets or sets base Assets URL
  108443. */
  108444. ParticleHelper.BaseAssetsUrl = "https://assets.babylonjs.com/particles";
  108445. return ParticleHelper;
  108446. }());
  108447. BABYLON.ParticleHelper = ParticleHelper;
  108448. })(BABYLON || (BABYLON = {}));
  108449. //# sourceMappingURL=babylon.particleHelper.js.map
  108450. var BABYLON;
  108451. (function (BABYLON) {
  108452. /**
  108453. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  108454. * As a subclass of TransformNode, this allow parenting to the camera or multiple videos with different locations in the scene.
  108455. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  108456. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  108457. */
  108458. var VideoDome = /** @class */ (function (_super) {
  108459. __extends(VideoDome, _super);
  108460. /**
  108461. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  108462. * @param name Element's name, child elements will append suffixes for their own names.
  108463. * @param urlsOrVideo defines the url(s) or the video element to use
  108464. * @param options An object containing optional or exposed sub element properties
  108465. */
  108466. function VideoDome(name, urlsOrVideo, options, scene) {
  108467. var _this = _super.call(this, name, scene) || this;
  108468. _this._useDirectMapping = false;
  108469. // set defaults and manage values
  108470. name = name || "videoDome";
  108471. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  108472. options.clickToPlay = Boolean(options.clickToPlay);
  108473. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  108474. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  108475. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  108476. if (options.useDirectMapping === undefined) {
  108477. _this._useDirectMapping = true;
  108478. }
  108479. else {
  108480. _this._useDirectMapping = options.useDirectMapping;
  108481. }
  108482. _this._setReady(false);
  108483. // create
  108484. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true, poster: options.poster };
  108485. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  108486. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, _this._useDirectMapping, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  108487. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  108488. texture.onLoadObservable.addOnce(function () {
  108489. _this._setReady(true);
  108490. });
  108491. // configure material
  108492. material.useEquirectangularFOV = true;
  108493. material.fovMultiplier = 1.0;
  108494. material.opacityFresnel = false;
  108495. if (_this._useDirectMapping) {
  108496. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  108497. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  108498. material.diffuseTexture = texture;
  108499. }
  108500. else {
  108501. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  108502. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  108503. material.reflectionTexture = texture;
  108504. }
  108505. // configure mesh
  108506. _this._mesh.material = material;
  108507. _this._mesh.parent = _this;
  108508. // optional configuration
  108509. if (options.clickToPlay) {
  108510. scene.onPointerUp = function () {
  108511. _this._videoTexture.video.play();
  108512. };
  108513. }
  108514. return _this;
  108515. }
  108516. Object.defineProperty(VideoDome.prototype, "videoTexture", {
  108517. /**
  108518. * Gets the video texture being displayed on the sphere
  108519. */
  108520. get: function () {
  108521. return this._videoTexture;
  108522. },
  108523. enumerable: true,
  108524. configurable: true
  108525. });
  108526. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  108527. /**
  108528. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  108529. * Also see the options.resolution property.
  108530. */
  108531. get: function () {
  108532. return this._material.fovMultiplier;
  108533. },
  108534. set: function (value) {
  108535. this._material.fovMultiplier = value;
  108536. },
  108537. enumerable: true,
  108538. configurable: true
  108539. });
  108540. /**
  108541. * Releases resources associated with this node.
  108542. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  108543. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  108544. */
  108545. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  108546. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  108547. this._videoTexture.dispose();
  108548. this._mesh.dispose();
  108549. this._material.dispose();
  108550. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  108551. };
  108552. return VideoDome;
  108553. }(BABYLON.TransformNode));
  108554. BABYLON.VideoDome = VideoDome;
  108555. })(BABYLON || (BABYLON = {}));
  108556. //# sourceMappingURL=babylon.videoDome.js.map
  108557. var BABYLON;
  108558. (function (BABYLON) {
  108559. /**
  108560. * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.
  108561. * As a subclass of TransformNode, this allow parenting to the camera with different locations in the scene.
  108562. * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.
  108563. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  108564. */
  108565. var PhotoDome = /** @class */ (function (_super) {
  108566. __extends(PhotoDome, _super);
  108567. /**
  108568. * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh.
  108569. * @param name Element's name, child elements will append suffixes for their own names.
  108570. * @param urlsOfPhoto defines the url of the photo to display
  108571. * @param options defines an object containing optional or exposed sub element properties
  108572. * @param onError defines a callback called when an error occured while loading the texture
  108573. */
  108574. function PhotoDome(name, urlOfPhoto, options, scene, onError) {
  108575. if (onError === void 0) { onError = null; }
  108576. var _this = _super.call(this, name, scene) || this;
  108577. _this._useDirectMapping = false;
  108578. /**
  108579. * Observable raised when an error occured while loading the 360 image
  108580. */
  108581. _this.onLoadErrorObservable = new BABYLON.Observable();
  108582. // set defaults and manage values
  108583. name = name || "photoDome";
  108584. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  108585. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  108586. if (options.useDirectMapping === undefined) {
  108587. _this._useDirectMapping = true;
  108588. }
  108589. else {
  108590. _this._useDirectMapping = options.useDirectMapping;
  108591. }
  108592. _this._setReady(false);
  108593. // create
  108594. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  108595. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  108596. // configure material
  108597. material.opacityFresnel = false;
  108598. material.useEquirectangularFOV = true;
  108599. material.fovMultiplier = 1.0;
  108600. _this.photoTexture = new BABYLON.Texture(urlOfPhoto, scene, true, !_this._useDirectMapping, undefined, undefined, function (message, exception) {
  108601. _this.onLoadErrorObservable.notifyObservers(message || "Unknown error occured");
  108602. if (onError) {
  108603. onError(message, exception);
  108604. }
  108605. });
  108606. _this.photoTexture.onLoadObservable.addOnce(function () {
  108607. _this._setReady(true);
  108608. });
  108609. // configure mesh
  108610. _this._mesh.material = material;
  108611. _this._mesh.parent = _this;
  108612. return _this;
  108613. }
  108614. Object.defineProperty(PhotoDome.prototype, "photoTexture", {
  108615. /**
  108616. * Gets or sets the texture being displayed on the sphere
  108617. */
  108618. get: function () {
  108619. return this._photoTexture;
  108620. },
  108621. set: function (value) {
  108622. if (this._photoTexture === value) {
  108623. return;
  108624. }
  108625. this._photoTexture = value;
  108626. if (this._useDirectMapping) {
  108627. this._photoTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  108628. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  108629. this._material.diffuseTexture = this._photoTexture;
  108630. }
  108631. else {
  108632. this._photoTexture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  108633. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  108634. this._material.reflectionTexture = this._photoTexture;
  108635. }
  108636. },
  108637. enumerable: true,
  108638. configurable: true
  108639. });
  108640. Object.defineProperty(PhotoDome.prototype, "fovMultiplier", {
  108641. /**
  108642. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  108643. * Also see the options.resolution property.
  108644. */
  108645. get: function () {
  108646. return this._material.fovMultiplier;
  108647. },
  108648. set: function (value) {
  108649. this._material.fovMultiplier = value;
  108650. },
  108651. enumerable: true,
  108652. configurable: true
  108653. });
  108654. /**
  108655. * Releases resources associated with this node.
  108656. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  108657. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  108658. */
  108659. PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  108660. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  108661. this._photoTexture.dispose();
  108662. this._mesh.dispose();
  108663. this._material.dispose();
  108664. this.onLoadErrorObservable.clear();
  108665. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  108666. };
  108667. return PhotoDome;
  108668. }(BABYLON.TransformNode));
  108669. BABYLON.PhotoDome = PhotoDome;
  108670. })(BABYLON || (BABYLON = {}));
  108671. //# sourceMappingURL=babylon.photoDome.js.map
  108672. var BABYLON;
  108673. (function (BABYLON) {
  108674. BABYLON.Engine.prototype.createQuery = function () {
  108675. return this._gl.createQuery();
  108676. };
  108677. BABYLON.Engine.prototype.deleteQuery = function (query) {
  108678. this._gl.deleteQuery(query);
  108679. return this;
  108680. };
  108681. BABYLON.Engine.prototype.isQueryResultAvailable = function (query) {
  108682. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  108683. };
  108684. BABYLON.Engine.prototype.getQueryResult = function (query) {
  108685. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  108686. };
  108687. BABYLON.Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  108688. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  108689. this._gl.beginQuery(glAlgorithm, query);
  108690. return this;
  108691. };
  108692. BABYLON.Engine.prototype.endOcclusionQuery = function (algorithmType) {
  108693. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  108694. this._gl.endQuery(glAlgorithm);
  108695. return this;
  108696. };
  108697. BABYLON.Engine.prototype._createTimeQuery = function () {
  108698. var timerQuery = this.getCaps().timerQuery;
  108699. if (timerQuery.createQueryEXT) {
  108700. return timerQuery.createQueryEXT();
  108701. }
  108702. return this.createQuery();
  108703. };
  108704. BABYLON.Engine.prototype._deleteTimeQuery = function (query) {
  108705. var timerQuery = this.getCaps().timerQuery;
  108706. if (timerQuery.deleteQueryEXT) {
  108707. timerQuery.deleteQueryEXT(query);
  108708. return;
  108709. }
  108710. this.deleteQuery(query);
  108711. };
  108712. BABYLON.Engine.prototype._getTimeQueryResult = function (query) {
  108713. var timerQuery = this.getCaps().timerQuery;
  108714. if (timerQuery.getQueryObjectEXT) {
  108715. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  108716. }
  108717. return this.getQueryResult(query);
  108718. };
  108719. BABYLON.Engine.prototype._getTimeQueryAvailability = function (query) {
  108720. var timerQuery = this.getCaps().timerQuery;
  108721. if (timerQuery.getQueryObjectEXT) {
  108722. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  108723. }
  108724. return this.isQueryResultAvailable(query);
  108725. };
  108726. BABYLON.Engine.prototype.startTimeQuery = function () {
  108727. var caps = this.getCaps();
  108728. var timerQuery = caps.timerQuery;
  108729. if (!timerQuery) {
  108730. return null;
  108731. }
  108732. var token = new BABYLON._TimeToken();
  108733. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  108734. if (caps.canUseTimestampForTimerQuery) {
  108735. token._startTimeQuery = this._createTimeQuery();
  108736. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  108737. }
  108738. else {
  108739. if (this._currentNonTimestampToken) {
  108740. return this._currentNonTimestampToken;
  108741. }
  108742. token._timeElapsedQuery = this._createTimeQuery();
  108743. if (timerQuery.beginQueryEXT) {
  108744. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  108745. }
  108746. else {
  108747. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  108748. }
  108749. this._currentNonTimestampToken = token;
  108750. }
  108751. return token;
  108752. };
  108753. BABYLON.Engine.prototype.endTimeQuery = function (token) {
  108754. var caps = this.getCaps();
  108755. var timerQuery = caps.timerQuery;
  108756. if (!timerQuery || !token) {
  108757. return -1;
  108758. }
  108759. if (caps.canUseTimestampForTimerQuery) {
  108760. if (!token._startTimeQuery) {
  108761. return -1;
  108762. }
  108763. if (!token._endTimeQuery) {
  108764. token._endTimeQuery = this._createTimeQuery();
  108765. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  108766. }
  108767. }
  108768. else if (!token._timeElapsedQueryEnded) {
  108769. if (!token._timeElapsedQuery) {
  108770. return -1;
  108771. }
  108772. if (timerQuery.endQueryEXT) {
  108773. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  108774. }
  108775. else {
  108776. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  108777. }
  108778. token._timeElapsedQueryEnded = true;
  108779. }
  108780. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  108781. var available = false;
  108782. if (token._endTimeQuery) {
  108783. available = this._getTimeQueryAvailability(token._endTimeQuery);
  108784. }
  108785. else if (token._timeElapsedQuery) {
  108786. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  108787. }
  108788. if (available && !disjoint) {
  108789. var result = 0;
  108790. if (caps.canUseTimestampForTimerQuery) {
  108791. if (!token._startTimeQuery || !token._endTimeQuery) {
  108792. return -1;
  108793. }
  108794. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  108795. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  108796. result = timeEnd - timeStart;
  108797. this._deleteTimeQuery(token._startTimeQuery);
  108798. this._deleteTimeQuery(token._endTimeQuery);
  108799. token._startTimeQuery = null;
  108800. token._endTimeQuery = null;
  108801. }
  108802. else {
  108803. if (!token._timeElapsedQuery) {
  108804. return -1;
  108805. }
  108806. result = this._getTimeQueryResult(token._timeElapsedQuery);
  108807. this._deleteTimeQuery(token._timeElapsedQuery);
  108808. token._timeElapsedQuery = null;
  108809. token._timeElapsedQueryEnded = false;
  108810. this._currentNonTimestampToken = null;
  108811. }
  108812. return result;
  108813. }
  108814. return -1;
  108815. };
  108816. BABYLON.Engine.prototype._getGlAlgorithmType = function (algorithmType) {
  108817. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  108818. };
  108819. // We also need to update AbstractMesh as there is a portion of the code there
  108820. BABYLON.AbstractMesh.prototype._checkOcclusionQuery = function () {
  108821. var engine = this.getEngine();
  108822. if (!engine.isQueryResultAvailable) { // Occlusion query where not referenced
  108823. this._isOccluded = false;
  108824. return;
  108825. }
  108826. if (engine.webGLVersion < 2 || this.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_NONE) {
  108827. this._isOccluded = false;
  108828. return;
  108829. }
  108830. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  108831. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  108832. if (isOcclusionQueryAvailable) {
  108833. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  108834. this._isOcclusionQueryInProgress = false;
  108835. this._occlusionInternalRetryCounter = 0;
  108836. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  108837. }
  108838. else {
  108839. this._occlusionInternalRetryCounter++;
  108840. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  108841. this._isOcclusionQueryInProgress = false;
  108842. this._occlusionInternalRetryCounter = 0;
  108843. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  108844. // if strict continue the last state of the object.
  108845. this._isOccluded = this.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  108846. }
  108847. else {
  108848. return;
  108849. }
  108850. }
  108851. }
  108852. var scene = this.getScene();
  108853. if (scene.getBoundingBoxRenderer) {
  108854. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  108855. if (!this._occlusionQuery) {
  108856. this._occlusionQuery = engine.createQuery();
  108857. }
  108858. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  108859. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  108860. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  108861. this._isOcclusionQueryInProgress = true;
  108862. }
  108863. };
  108864. })(BABYLON || (BABYLON = {}));
  108865. //# sourceMappingURL=babylon.engine.occlusionQuery.js.map
  108866. var BABYLON;
  108867. (function (BABYLON) {
  108868. /**
  108869. * Class used to generate noise procedural textures
  108870. */
  108871. var NoiseProceduralTexture = /** @class */ (function (_super) {
  108872. __extends(NoiseProceduralTexture, _super);
  108873. /**
  108874. * Creates a new NoiseProceduralTexture
  108875. * @param name defines the name fo the texture
  108876. * @param size defines the size of the texture (default is 256)
  108877. * @param scene defines the hosting scene
  108878. * @param fallbackTexture defines the texture to use if the NoiseProceduralTexture can't be created
  108879. * @param generateMipMaps defines if mipmaps must be generated (true by default)
  108880. */
  108881. function NoiseProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  108882. if (size === void 0) { size = 256; }
  108883. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  108884. var _this = _super.call(this, name, size, "noise", scene, fallbackTexture, generateMipMaps) || this;
  108885. _this._time = 0;
  108886. /** Gets or sets a value between 0 and 1 indicating the overall brightness of the texture (default is 0.2) */
  108887. _this.brightness = 0.2;
  108888. /** Defines the number of octaves to process */
  108889. _this.octaves = 3;
  108890. /** Defines the level of persistence (0.8 by default) */
  108891. _this.persistence = 0.8;
  108892. /** Gets or sets animation speed factor (default is 1) */
  108893. _this.animationSpeedFactor = 1;
  108894. _this._updateShaderUniforms();
  108895. return _this;
  108896. }
  108897. NoiseProceduralTexture.prototype._updateShaderUniforms = function () {
  108898. var scene = this.getScene();
  108899. if (!scene) {
  108900. return;
  108901. }
  108902. this._time += scene.getAnimationRatio() * this.animationSpeedFactor * 0.01;
  108903. this.setFloat("brightness", this.brightness);
  108904. this.setFloat("persistence", this.persistence);
  108905. this.setFloat("timeScale", this._time);
  108906. };
  108907. NoiseProceduralTexture.prototype._getDefines = function () {
  108908. return "#define OCTAVES " + this.octaves;
  108909. };
  108910. /** Generate the current state of the procedural texture */
  108911. NoiseProceduralTexture.prototype.render = function (useCameraPostProcess) {
  108912. this._updateShaderUniforms();
  108913. _super.prototype.render.call(this, useCameraPostProcess);
  108914. };
  108915. /**
  108916. * Serializes this noise procedural texture
  108917. * @returns a serialized noise procedural texture object
  108918. */
  108919. NoiseProceduralTexture.prototype.serialize = function () {
  108920. var serializationObject = BABYLON.SerializationHelper.Serialize(this, _super.prototype.serialize.call(this));
  108921. serializationObject.customType = "BABYLON.NoiseProceduralTexture";
  108922. return serializationObject;
  108923. };
  108924. /**
  108925. * Creates a NoiseProceduralTexture from parsed noise procedural texture data
  108926. * @param parsedTexture defines parsed texture data
  108927. * @param scene defines the current scene
  108928. * @param rootUrl defines the root URL containing noise procedural texture information
  108929. * @returns a parsed NoiseProceduralTexture
  108930. */
  108931. NoiseProceduralTexture.Parse = function (parsedTexture, scene, rootUrl) {
  108932. var texture = BABYLON.SerializationHelper.Parse(function () { return new NoiseProceduralTexture(parsedTexture.name, parsedTexture._size, scene, undefined, parsedTexture._generateMipMaps); }, parsedTexture, scene, rootUrl);
  108933. return texture;
  108934. };
  108935. return NoiseProceduralTexture;
  108936. }(BABYLON.ProceduralTexture));
  108937. BABYLON.NoiseProceduralTexture = NoiseProceduralTexture;
  108938. })(BABYLON || (BABYLON = {}));
  108939. //# sourceMappingURL=babylon.noiseProceduralTexture.js.map
  108940. var __assign = (this && this.__assign) || function () {
  108941. __assign = Object.assign || function(t) {
  108942. for (var s, i = 1, n = arguments.length; i < n; i++) {
  108943. s = arguments[i];
  108944. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  108945. t[p] = s[p];
  108946. }
  108947. return t;
  108948. };
  108949. return __assign.apply(this, arguments);
  108950. };
  108951. var BABYLON;
  108952. (function (BABYLON) {
  108953. /**
  108954. * This can helps recording videos from BabylonJS.
  108955. * This is based on the available WebRTC functionalities of the browser.
  108956. *
  108957. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_video
  108958. */
  108959. var VideoRecorder = /** @class */ (function () {
  108960. /**
  108961. * Create a new VideoCapture object which can help converting what you see in Babylon to
  108962. * a video file.
  108963. * @param engine Defines the BabylonJS Engine you wish to record
  108964. * @param options Defines options that can be used to customized the capture
  108965. */
  108966. function VideoRecorder(engine, options) {
  108967. if (options === void 0) { options = null; }
  108968. if (!VideoRecorder.IsSupported(engine)) {
  108969. throw "Your browser does not support recording so far.";
  108970. }
  108971. var canvas = engine.getRenderingCanvas();
  108972. if (!canvas) {
  108973. throw "The babylon engine must have a canvas to be recorded";
  108974. }
  108975. this._canvas = canvas;
  108976. this._canvas.isRecording = false;
  108977. this._options = __assign({}, VideoRecorder._defaultOptions, options);
  108978. var stream = this._canvas.captureStream(this._options.fps);
  108979. this._mediaRecorder = new MediaRecorder(stream, { mimeType: this._options.mimeType });
  108980. this._mediaRecorder.ondataavailable = this._handleDataAvailable.bind(this);
  108981. this._mediaRecorder.onerror = this._handleError.bind(this);
  108982. this._mediaRecorder.onstop = this._handleStop.bind(this);
  108983. }
  108984. /**
  108985. * Returns wehther or not the VideoRecorder is available in your browser.
  108986. * @param engine Defines the Babylon Engine to check the support for
  108987. * @returns true if supported otherwise false
  108988. */
  108989. VideoRecorder.IsSupported = function (engine) {
  108990. var canvas = engine.getRenderingCanvas();
  108991. return (!!canvas && typeof canvas.captureStream === "function");
  108992. };
  108993. Object.defineProperty(VideoRecorder.prototype, "isRecording", {
  108994. /**
  108995. * True wether a recording is already in progress.
  108996. */
  108997. get: function () {
  108998. return !!this._canvas && this._canvas.isRecording;
  108999. },
  109000. enumerable: true,
  109001. configurable: true
  109002. });
  109003. /**
  109004. * Stops the current recording before the default capture timeout passed in the startRecording
  109005. * functions.
  109006. */
  109007. VideoRecorder.prototype.stopRecording = function () {
  109008. if (!this._canvas || !this._mediaRecorder) {
  109009. return;
  109010. }
  109011. if (!this.isRecording) {
  109012. return;
  109013. }
  109014. this._canvas.isRecording = false;
  109015. this._mediaRecorder.stop();
  109016. };
  109017. /**
  109018. * Starts recording the canvas for a max duration specified in parameters.
  109019. * @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.
  109020. * @param maxDuration Defines the maximum recording time in seconds.
  109021. * It default to 7 seconds. A value of zero will not stop automatically, you would need to call stopRecording manually.
  109022. * @return a promise callback at the end of the recording with the video data in Blob.
  109023. */
  109024. VideoRecorder.prototype.startRecording = function (fileName, maxDuration) {
  109025. var _this = this;
  109026. if (fileName === void 0) { fileName = "babylonjs.webm"; }
  109027. if (maxDuration === void 0) { maxDuration = 7; }
  109028. if (!this._canvas || !this._mediaRecorder) {
  109029. throw "Recorder has already been disposed";
  109030. }
  109031. if (this.isRecording) {
  109032. throw "Recording already in progress";
  109033. }
  109034. if (maxDuration > 0) {
  109035. setTimeout(function () {
  109036. _this.stopRecording();
  109037. }, maxDuration * 1000);
  109038. }
  109039. this._fileName = fileName;
  109040. this._recordedChunks = [];
  109041. this._resolve = null;
  109042. this._reject = null;
  109043. this._canvas.isRecording = true;
  109044. this._mediaRecorder.start(this._options.recordChunckSize);
  109045. return new Promise(function (resolve, reject) {
  109046. _this._resolve = resolve;
  109047. _this._reject = reject;
  109048. });
  109049. };
  109050. /**
  109051. * Releases internal resources used during the recording.
  109052. */
  109053. VideoRecorder.prototype.dispose = function () {
  109054. this._canvas = null;
  109055. this._mediaRecorder = null;
  109056. this._recordedChunks = [];
  109057. this._fileName = null;
  109058. this._resolve = null;
  109059. this._reject = null;
  109060. };
  109061. VideoRecorder.prototype._handleDataAvailable = function (event) {
  109062. if (event.data.size > 0) {
  109063. this._recordedChunks.push(event.data);
  109064. }
  109065. };
  109066. VideoRecorder.prototype._handleError = function (event) {
  109067. this.stopRecording();
  109068. if (this._reject) {
  109069. this._reject(event.error);
  109070. }
  109071. else {
  109072. throw new event.error;
  109073. }
  109074. };
  109075. VideoRecorder.prototype._handleStop = function () {
  109076. this.stopRecording();
  109077. var superBuffer = new Blob(this._recordedChunks);
  109078. if (this._resolve) {
  109079. this._resolve(superBuffer);
  109080. }
  109081. window.URL.createObjectURL(superBuffer);
  109082. if (this._fileName) {
  109083. BABYLON.Tools.Download(superBuffer, this._fileName);
  109084. }
  109085. };
  109086. VideoRecorder._defaultOptions = {
  109087. mimeType: "video/webm",
  109088. fps: 25,
  109089. recordChunckSize: 3000
  109090. };
  109091. return VideoRecorder;
  109092. }());
  109093. BABYLON.VideoRecorder = VideoRecorder;
  109094. })(BABYLON || (BABYLON = {}));
  109095. //# sourceMappingURL=babylon.videoRecorder.js.map
  109096. var BABYLON;
  109097. (function (BABYLON) {
  109098. BABYLON.Scene.prototype.createDefaultLight = function (replace) {
  109099. if (replace === void 0) { replace = false; }
  109100. // Dispose existing light in replace mode.
  109101. if (replace) {
  109102. if (this.lights) {
  109103. for (var i = 0; i < this.lights.length; i++) {
  109104. this.lights[i].dispose();
  109105. }
  109106. }
  109107. }
  109108. // Light
  109109. if (this.lights.length === 0) {
  109110. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  109111. }
  109112. };
  109113. BABYLON.Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  109114. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  109115. if (replace === void 0) { replace = false; }
  109116. if (attachCameraControls === void 0) { attachCameraControls = false; }
  109117. // Dispose existing camera in replace mode.
  109118. if (replace) {
  109119. if (this.activeCamera) {
  109120. this.activeCamera.dispose();
  109121. this.activeCamera = null;
  109122. }
  109123. }
  109124. // Camera
  109125. if (!this.activeCamera) {
  109126. var worldExtends = this.getWorldExtends();
  109127. var worldSize = worldExtends.max.subtract(worldExtends.min);
  109128. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  109129. var camera;
  109130. var radius = worldSize.length() * 1.5;
  109131. // empty scene scenario!
  109132. if (!isFinite(radius)) {
  109133. radius = 1;
  109134. worldCenter.copyFromFloats(0, 0, 0);
  109135. }
  109136. if (createArcRotateCamera) {
  109137. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  109138. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  109139. arcRotateCamera.wheelPrecision = 100 / radius;
  109140. camera = arcRotateCamera;
  109141. }
  109142. else {
  109143. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  109144. freeCamera.setTarget(worldCenter);
  109145. camera = freeCamera;
  109146. }
  109147. camera.minZ = radius * 0.01;
  109148. camera.maxZ = radius * 1000;
  109149. camera.speed = radius * 0.2;
  109150. this.activeCamera = camera;
  109151. var canvas = this.getEngine().getRenderingCanvas();
  109152. if (attachCameraControls && canvas) {
  109153. camera.attachControl(canvas);
  109154. }
  109155. }
  109156. };
  109157. BABYLON.Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  109158. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  109159. if (replace === void 0) { replace = false; }
  109160. if (attachCameraControls === void 0) { attachCameraControls = false; }
  109161. this.createDefaultLight(replace);
  109162. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  109163. };
  109164. BABYLON.Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  109165. if (pbr === void 0) { pbr = false; }
  109166. if (scale === void 0) { scale = 1000; }
  109167. if (blur === void 0) { blur = 0; }
  109168. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  109169. if (!environmentTexture) {
  109170. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  109171. return null;
  109172. }
  109173. if (setGlobalEnvTexture) {
  109174. if (environmentTexture) {
  109175. this.environmentTexture = environmentTexture;
  109176. }
  109177. }
  109178. // Skybox
  109179. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  109180. if (pbr) {
  109181. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  109182. hdrSkyboxMaterial.backFaceCulling = false;
  109183. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  109184. if (hdrSkyboxMaterial.reflectionTexture) {
  109185. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  109186. }
  109187. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  109188. hdrSkyboxMaterial.disableLighting = true;
  109189. hdrSkyboxMaterial.twoSidedLighting = true;
  109190. hdrSkybox.infiniteDistance = true;
  109191. hdrSkybox.material = hdrSkyboxMaterial;
  109192. }
  109193. else {
  109194. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  109195. skyboxMaterial.backFaceCulling = false;
  109196. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  109197. if (skyboxMaterial.reflectionTexture) {
  109198. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  109199. }
  109200. skyboxMaterial.disableLighting = true;
  109201. hdrSkybox.infiniteDistance = true;
  109202. hdrSkybox.material = skyboxMaterial;
  109203. }
  109204. return hdrSkybox;
  109205. };
  109206. BABYLON.Scene.prototype.createDefaultEnvironment = function (options) {
  109207. if (BABYLON.EnvironmentHelper) {
  109208. return new BABYLON.EnvironmentHelper(options, this);
  109209. }
  109210. return null;
  109211. };
  109212. BABYLON.Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  109213. if (webVROptions === void 0) { webVROptions = {}; }
  109214. return new BABYLON.VRExperienceHelper(this, webVROptions);
  109215. };
  109216. })(BABYLON || (BABYLON = {}));
  109217. //# sourceMappingURL=babylon.sceneHelpers.js.map
  109218. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\n#ifdef REFLECTIONMAP_SKYBOX_TRANSFORMED\nvPositionUVW=(reflectionMatrix*vec4(position,1.0)).xyz;\n#else\nvPositionUVW=position;\n#endif\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n#ifdef ALPHATEST\nuniform float alphaCutOff;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<alphaCutOff)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0) {\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb;\n#endif\n#ifdef IS_REFRACTION_LINEAR\nrefractionColor=toGammaSpace(refractionColor);\n#endif\nrefractionColor*=vRefractionInfos.x;\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb;\n#endif\n#ifdef IS_REFLECTION_LINEAR\nreflectionColor=toGammaSpace(reflectionColor);\n#endif\nreflectionColor*=vReflectionInfos.x;\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\n#ifdef REFLECTIONMAP_SKYBOX_TRANSFORMED\nvPositionUVW=(reflectionMatrix*vec4(positionUpdated,1.0)).xyz;\n#else\nvPositionUVW=positionUpdated;\n#endif\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(SPECULARAA)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#ifdef SPECULARAA\nvec3 nDfdx=dFdx(normalW.xyz);\nvec3 nDfdy=dFdy(normalW.xyz);\nfloat slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));\n\nfloat geometricRoughnessFactor=pow(clamp(slopeSquare ,0.,1.),0.333);\n\nfloat geometricAlphaGFactor=sqrt(slopeSquare);\n#else\nfloat geometricRoughnessFactor=0.;\n#endif\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#ifdef SPECULARAA\n\n\nalphaG+=(0.75*geometricAlphaGFactor);\n#endif\n\n#ifdef REFRACTION\nvec4 environmentRefraction=vec4(0.,0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD);\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec4 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords);\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords),\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords),\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction.rgb=fromRGBD(environmentRefraction);\n#endif\n#ifdef RGBDREFRACTION\nenvironmentRefraction.rgb=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction.rgb*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec4 environmentRadiance=vec4(0.,0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef RGBDREFLECTION\nenvironmentRadiance.rgb=fromRGBD(environmentRadiance);\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance.rgb=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance.rgb*=vReflectionInfos.x;\nenvironmentRadiance.rgb*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb;\n#ifdef GAMMALIGHTMAP\nlightmapColor=toLinearSpace(lightmapColor);\n#endif\nlightmapColor*=vLightmapInfos.y;\n#endif\nlightingInfo info;\npointLightingInfo pointInfo;\nspotLightingInfo spotInfo;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(-viewDirectionW,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction.rgb*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance.rgb;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction.rgb;\nfinalRefraction*=refractance;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n#endif\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n#ifdef AMBIENT\nvec3 ambientOcclusionForDirectDiffuse=mix(vec3(1.),ambientOcclusionColor,vAmbientInfos.w);\n#else\nvec3 ambientOcclusionForDirectDiffuse=ambientOcclusionColor;\n#endif\n\n\n\nvec4 finalColor=vec4(\nfinalDiffuse*ambientOcclusionForDirectDiffuse*vLightingIntensity.x +\n#ifndef UNLIT\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","rgbdEncodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);\n}","rgbdDecodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute float angle;\nattribute vec2 size;\n#ifdef ANIMATESHEET \nattribute float cellIndex;\n#endif\n#ifndef BILLBOARD \nattribute vec3 direction;\n#endif\n#ifdef RAMPGRADIENT\nattribute vec4 remapData;\n#endif\nattribute vec2 offset;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n#ifdef ANIMATESHEET \nuniform vec3 particlesInfos; \n#endif\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef RAMPGRADIENT\nvarying vec4 remapRanges;\n#endif\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nuniform mat4 invView;\n#endif\n#include<clipPlaneVertexDeclaration>\n#ifdef BILLBOARD\nuniform vec3 eyePosition; \n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner; \n}\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#ifdef RAMPGRADIENT\nremapRanges=remapData;\n#endif\n\ngl_Position=projection*vec4(viewPos,1.0); \n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=normalize(direction);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\ngl_Position=projection*view*vec4(worldPos,1.0); \n#endif \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nvec4 worldPos=invView*vec4(viewPos,1.0);\n#endif\n#include<clipPlaneVertex>\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#include<clipPlaneFragmentDeclaration>\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n#ifdef RAMPGRADIENT\nvarying vec4 remapRanges;\nuniform sampler2D rampSampler;\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec4 textureColor=texture2D(diffuseSampler,vUV);\nvec4 baseColor=(textureColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n#ifdef RAMPGRADIENT\nfloat alpha=textureColor.a;\nfloat remappedColorIndex=clamp((alpha-remapRanges.x)/remapRanges.y,0.0,1.0);\nbaseColor.rgb*=texture2D(rampSampler,vec2(remappedColorIndex,0.)).rgb;\n\nbaseColor.a=clamp((alpha-remapRanges.z)/remapRanges.w,0.0,1.0);\n#endif\n#ifdef BLENDMULTIPLYMODE\nfloat sourceAlpha=vColor.a*textureColor.a;\nbaseColor.rgb=baseColor.rgb*sourceAlpha+vec3(1.0)*(1.0-sourceAlpha);\n#endif\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\nbaseColor.rgb=toLinearSpace(baseColor.rgb);\n#else\n#ifdef IMAGEPROCESSING\nbaseColor.rgb=toLinearSpace(baseColor.rgb);\nbaseColor=applyImageProcessing(baseColor);\n#endif\n#endif\ngl_FragColor=baseColor;\n}","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","gpuRenderParticlesVertexShader":"#version 300 es\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n\nin vec3 position;\nin float age;\nin float life;\nin vec3 size;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\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> \nvec4 textureColor=texture(textureSampler,vUV);\noutFragColor=textureColor*vColor;\n#ifdef BLENDMULTIPLYMODE\nfloat alpha=vColor.a*textureColor.a;\noutFragColor.rgb=outFragColor.rgb*alpha+vec3(1.0)*(1.0-alpha); \n#endif \n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\noutFragColor.rgb=toLinearSpace(outFragColor.rgb);\n#else\n#ifdef IMAGEPROCESSING\noutFragColor.rgb=toLinearSpace(outFragColor.rgb);\noutFragColor=applyImageProcessing(outFragColor);\n#endif\n#endif\n}\n","gpuUpdateParticlesVertexShader":"#version 300 es\n#define PI 3.14159\nuniform float currentCount;\nuniform float timeDelta;\nuniform float stopFactor;\nuniform mat4 emitterWM;\nuniform vec2 lifeTime;\nuniform vec2 emitPower;\nuniform vec2 sizeRange;\nuniform vec4 scaleRange;\n#ifndef COLORGRADIENTS\nuniform vec4 color1;\nuniform vec4 color2;\n#endif\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\nuniform sampler2D randomSampler2;\nuniform vec4 angleRange;\n#ifdef BOXEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\nuniform vec3 minEmitBox;\nuniform vec3 maxEmitBox;\n#endif\n#ifdef POINTEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#endif\n#ifdef HEMISPHERICEMITTER\nuniform float radius;\nuniform float radiusRange;\nuniform float directionRandomizer;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\nuniform float radiusRange;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CYLINDEREMITTER\nuniform float radius;\nuniform float height;\nuniform float radiusRange;\n#ifdef DIRECTEDCYLINDEREMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform vec2 radius;\nuniform float coneAngle;\nuniform vec2 height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin vec4 seed;\nin vec3 size;\n#ifndef COLORGRADIENTS\nin vec4 color;\n#endif\nin vec3 direction;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nin float angle;\n#else\nin vec2 angle;\n#endif\n#ifdef ANIMATESHEET\nin float cellIndex;\n#ifdef ANIMATESHEETRANDOMSTART\nin float cellStartOffset;\n#endif\n#endif\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout vec4 outSeed;\nout vec3 outSize;\n#ifndef COLORGRADIENTS\nout vec4 outColor;\n#endif\nout vec3 outDirection;\n#ifndef BILLBOARD\nout vec3 outInitialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nout float outAngle;\n#else\nout vec2 outAngle;\n#endif\n#ifdef ANIMATESHEET\nout float outCellIndex;\n#ifdef ANIMATESHEETRANDOMSTART\nout float outCellStartOffset;\n#endif\n#endif\n#ifdef SIZEGRADIENTS\nuniform sampler2D sizeGradientSampler;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nuniform sampler2D angularSpeedGradientSampler;\n#endif \n#ifdef VELOCITYGRADIENTS\nuniform sampler2D velocityGradientSampler;\n#endif\n#ifdef LIMITVELOCITYGRADIENTS\nuniform sampler2D limitVelocityGradientSampler;\nuniform float limitVelocityDamping;\n#endif\n#ifdef DRAGGRADIENTS\nuniform sampler2D dragGradientSampler;\n#endif\n#ifdef NOISE\nuniform vec3 noiseStrength;\nuniform sampler2D noiseSampler;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 cellInfos;\n#endif\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler2,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;\n}\nvec4 getRandomVec4(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));\n}\nvoid main() {\nfloat newAge=age+timeDelta;\n\nif (newAge>=life && stopFactor != 0.) {\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(seed.x);\n\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\noutAge=mod(newAge,outLife);\n\noutSeed=seed;\n\n#ifdef SIZEGRADIENTS \noutSize.x=texture(sizeGradientSampler,vec2(0,0)).r;\n#else\noutSize.x=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n#endif\noutSize.y=scaleRange.x+(scaleRange.y-scaleRange.x)*randoms.b;\noutSize.z=scaleRange.z+(scaleRange.w-scaleRange.z)*randoms.a; \n#ifndef COLORGRADIENTS\n\noutColor=color1+(color2-color1)*randoms.b;\n#endif\n\n#ifndef ANGULARSPEEDGRADIENTS \noutAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;\noutAngle.x=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#else\noutAngle=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#endif \n\n#ifdef POINTEMITTER\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nposition=vec3(0,0,0);\ndirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(BOXEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*randoms3; \n#elif defined(HEMISPHERICEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=acos(2.0*randoms2.y-1.0);\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,abs(randY),randZ);\ndirection=position+directionRandomizer*randoms3; \n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=acos(2.0*randoms2.y-1.0);\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,randY,randZ);\n#ifdef DIRECTEDSPHEREEMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\ndirection=position+directionRandomizer*randoms3;\n#endif\n#elif defined(CYLINDEREMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat yPos=(randoms2.x-0.5)*height;\nfloat angle=randoms2.y*PI*2.;\nfloat inverseRadiusRangeSquared=((1.-radiusRange)*(1.-radiusRange));\nfloat positionRadius=radius*sqrt(inverseRadiusRangeSquared+(randoms2.z*(1.-inverseRadiusRangeSquared)));\nfloat xPos=positionRadius*cos(angle);\nfloat zPos=positionRadius*sin(angle);\nposition=vec3(xPos,yPos,zPos);\n#ifdef DIRECTEDCYLINDEREMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\nangle=angle+((randoms3.x-0.5)*PI);\ndirection=vec3(cos(angle),randoms3.y-0.5,sin(angle));\ndirection=normalize(direction);\n#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nfloat s=2.0*PI*randoms2.x;\n#ifdef CONEEMITTERSPAWNPOINT\nfloat h=0.00001;\n#else\nfloat h=randoms2.y*height.y;\n\nh=1.-h*h; \n#endif\nfloat lRadius=radius.x-radius.x*randoms2.z*radius.y;\nlRadius=lRadius*h;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height.x;\nposition=vec3(randX,randY,randZ); \n\nif (abs(cos(coneAngle)) == 1.0) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(seed.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed.w)-vec3(0.5,0.5,0.5));\n#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\noutPosition=(emitterWM*vec4(position,1.)).xyz;\nvec3 initial=(emitterWM*vec4(normalize(direction),0.)).xyz;\noutDirection=initial*power;\n#ifndef BILLBOARD \noutInitialDirection=initial;\n#endif\n#ifdef ANIMATESHEET \noutCellIndex=cellInfos.x;\n#ifdef ANIMATESHEETRANDOMSTART\noutCellStartOffset=randoms.a*outLife;\n#endif \n#endif\n} else {\nfloat directionScale=timeDelta;\noutAge=newAge;\nfloat ageGradient=newAge/life;\n#ifdef VELOCITYGRADIENTS\ndirectionScale*=texture(velocityGradientSampler,vec2(ageGradient,0)).r;\n#endif\n#ifdef DRAGGRADIENTS\ndirectionScale*=1.0-texture(dragGradientSampler,vec2(ageGradient,0)).r;\n#endif\noutPosition=position+direction*directionScale;\noutLife=life;\noutSeed=seed;\n#ifndef COLORGRADIENTS \noutColor=color;\n#endif\n#ifdef SIZEGRADIENTS\noutSize.x=texture(sizeGradientSampler,vec2(ageGradient,0)).r;\noutSize.yz=size.yz;\n#else\noutSize=size;\n#endif \n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif\nvec3 updatedDirection=direction+gravity*timeDelta;\n#ifdef LIMITVELOCITYGRADIENTS\nfloat limitVelocity=texture(limitVelocityGradientSampler,vec2(ageGradient,0)).r;\nfloat currentVelocity=length(updatedDirection);\nif (currentVelocity>limitVelocity) {\nupdatedDirection=updatedDirection*limitVelocityDamping;\n}\n#endif\noutDirection=updatedDirection;\n#ifdef NOISE\nvec3 localPosition=outPosition-emitterWM[3].xyz;\nfloat fetchedR=texture(noiseSampler,vec2(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 offsetAge=outAge;\nfloat dist=cellInfos.y-cellInfos.x;\n#ifdef ANIMATESHEETRANDOMSTART\noutCellStartOffset=cellStartOffset;\noffsetAge+=cellStartOffset;\n#endif \nfloat ratio=clamp(mod(offsetAge*cellInfos.z,life)/life,0.,1.0);\noutCellIndex=float(int(cellInfos.x+ratio*dist));\n#endif\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\n","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\nuniform vec3 lightData;\n#endif\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\n#include<helperFunctions>\nuniform mat4 viewProjection;\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvec3 worldNor=normalize(normalWorld*normal);\n#ifdef DIRECTIONINLIGHTDATA\nvec3 worldLightDir=normalize(-lightData.xyz);\n#else\nvec3 directionToLight=lightData.xyz-worldPos.xyz;\nvec3 worldLightDir=normalize(directionToLight);\n#endif\nfloat ndl=dot(worldNor,worldLightDir);\nfloat sinNL=sqrt(1.0-ndl*ndl);\nfloat normalBias=biasAndScale.y*sinNL;\nworldPos.xyz-=worldNor*normalBias;\n#endif\n\ngl_Position=viewProjection*worldPos;\n#ifdef DEPTHTEXTURE\n\ngl_Position.z+=biasAndScale.x*gl_Position.w;\n#endif\n\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.z*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nfloat scales[16]=float[16](\n0.1,\n0.11406250000000001,\n0.131640625,\n0.15625,\n0.187890625,\n0.2265625,\n0.272265625,\n0.325,\n0.384765625,\n0.4515625,\n0.525390625,\n0.60625,\n0.694140625,\n0.7890625,\n0.891015625,\n1.0\n);\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\n\nfloat dotProduct=dot(rvec,normal);\nrvec=1.0-abs(dotProduct)>1e-2 ? rvec : vec3(-rvec.y,0.0,rvec.x);\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=scales[(i+int(random.x*16.0)) % 16]*tbn*sampleSphere[(i+int(random.y*16.0)) % 16];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\ndifference=depthSign*samplePosition.z-sampleDepth;\nfloat rangeCheck=1.0-smoothstep(correctedRadius*0.5,correctedRadius,difference);\nocclusion+=(difference>=0.0 ? 1.0 : 0.0)*rangeCheck;\n}\nocclusion=occlusion*(1.0-smoothstep(maxZ*0.75,maxZ,depth));\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nuniform vec4 viewport;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,viewport.xy+vUV*viewport.zw);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\n#ifndef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\n#endif\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\n#ifdef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\n}\nelse\n{\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}\n#else\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n#endif\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float radialIntensity;\nuniform vec2 direction;\nuniform vec2 centerPosition;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);\nvec2 directionOfEffect=direction;\nif(directionOfEffect.x == 0. && directionOfEffect.y == 0.){\ndirectionOfEffect=normalize(centered_screen_pos);\n}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;\nfloat ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\noriginal.a=clamp(texture2D(textureSampler,ref_coords_r).a+texture2D(textureSampler,ref_coords_g).a+texture2D(textureSampler,ref_coords_b).a,0.,1.);\ngl_FragColor=original;\n}","grainPixelShader":"#include<helperFunctions>\n\nuniform sampler2D textureSampler; \n\nuniform float intensity;\nuniform float animatedSeed;\n\nvarying vec2 vUV;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec2 seed=vUV*(animatedSeed);\nfloat grain=dither(seed,intensity);\n\nfloat lum=getLuminance(gl_FragColor.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\ngl_FragColor.rgb+=grain*grainAmount;\ngl_FragColor.rgb=max(gl_FragColor.rgb,0.0);\n}","sharpenPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\nfloat sampleCoC(const in vec2 offset) {\nfloat coc=texture2D(circleOfConfusionSampler,offset).r; \nreturn coc; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#ifdef DOF\nfloat sumOfWeights=CENTER_WEIGHT; \nfloat factor=0.0;\n\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;\n#else\nblend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;\n#endif\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\ngl_FragColor/=sumOfWeights;\n#endif\n}","depthOfFieldMergePixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\nuniform sampler2D circleOfConfusionSampler;\nuniform sampler2D blurStep0;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\n#if BLUR_LEVEL == 0\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred0=texture2D(blurStep0,vUV);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL == 1\nif(coc<0.5){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV); \nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nif(coc<0.33){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);\n}\n#endif\n}\n","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nvoid main(void)\n{\nfloat depth=texture2D(depthSampler,vUV).r;\nfloat pixelDistance=(cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,depth,coc,1.0);\n}\n","bloomMergePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D bloomBlur;\nvarying vec2 vUV;\nuniform float bloomWeight;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec3 blurred=texture2D(bloomBlur,vUV).rgb;\ngl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); \n}\n","extractHighlightsPixelShader":"#include<helperFunctions>\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float threshold;\nuniform float exposure;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat luma=getLuminance(gl_FragColor.rgb*exposure);\ngl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(positionUpdated,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\n#ifdef REFLECTIONMAP_SKYBOX_TRANSFORMED\nvPositionUVW=(reflectionMatrix*vec4(position,1.0)).xyz;\n#else\nvPositionUVW=position;\n#endif\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec4 reflectionColor=vec4(1.,1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample;\n#endif\n#ifdef RGBDREFLECTION\nreflectionColor.rgb=fromRGBD(reflectionColor);\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor.rgb=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor.rgb=reflectionColor.bgr;\n#endif\n\nreflectionColor.rgb*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor.rgb*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nvec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase);\n#else\nvec3 mainColor=vPrimaryColor.rgb;\n#endif\nvec3 finalColor=colorBase*mainColor;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor.rgb,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\ngl_FragColor=color;\n}\n","noisePixelShader":"\n\nuniform float brightness;\nuniform float persistence;\nuniform float timeScale;\n\nvarying vec2 vUV;\n\nvec2 hash22(vec2 p)\n{\np=p*mat2(127.1,311.7,269.5,183.3);\np=-1.0+2.0*fract(sin(p)*43758.5453123);\nreturn sin(p*6.283+timeScale);\n}\nfloat interpolationNoise(vec2 p)\n{\nvec2 pi=floor(p);\nvec2 pf=p-pi;\nvec2 w=pf*pf*(3.-2.*pf);\nfloat f00=dot(hash22(pi+vec2(.0,.0)),pf-vec2(.0,.0));\nfloat f01=dot(hash22(pi+vec2(.0,1.)),pf-vec2(.0,1.));\nfloat f10=dot(hash22(pi+vec2(1.0,0.)),pf-vec2(1.0,0.));\nfloat f11=dot(hash22(pi+vec2(1.0,1.)),pf-vec2(1.0,1.));\nfloat xm1=mix(f00,f10,w.x);\nfloat xm2=mix(f01,f11,w.x);\nfloat ym=mix(xm1,xm2,w.y); \nreturn ym;\n}\nfloat perlinNoise2D(float x,float y)\n{\nfloat sum=0.0;\nfloat frequency=0.0;\nfloat amplitude=0.0;\nfor(int i=0; i<OCTAVES; i++)\n{\nfrequency=pow(2.0,float(i));\namplitude=pow(persistence,float(i));\nsum=sum+interpolationNoise(vec2(x*frequency,y*frequency))*amplitude;\n}\nreturn sum;\n}\n\nvoid main(void)\n{\nfloat x=abs(vUV.x);\nfloat y=abs(vUV.y);\nfloat noise=brightness+(1.0-brightness)*perlinNoise2D(x,y);\ngl_FragColor=vec4(noise,noise,noise,1.0);\n}\n"};
  109219. 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};"};